<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Broadcast;
use App\Models\BroadcastLog;
use App\Models\WhatsAppTemplate;
use App\Models\Tag;
use App\Models\PipelineStage;
use App\Models\Contact;
use App\Models\Conversation;
use App\Models\Message;
use App\Services\WhatsAppService;

class CampaignController extends Controller {
    public function index(): void {
        $broadcasts = Broadcast::getWithDetails();
        $templates = WhatsAppTemplate::getApproved();
        $tags = Tag::all('name ASC');
        $stages = PipelineStage::getOrdered();

        $this->render('campaigns/index', [
            'broadcasts' => $broadcasts,
            'templates'  => $templates,
            'tags'       => $tags,
            'stages'     => $stages
        ]);
    }

    public function create(): void {
        $templates = WhatsAppTemplate::getApproved();
        $tags = Tag::all('name ASC');
        $stages = PipelineStage::getOrdered();

        $this->render('campaigns/create', [
            'templates' => $templates,
            'tags'      => $tags,
            'stages'    => $stages
        ]);
    }

    public function store(): void {
        $name = trim(Request::post('name', ''));
        $templateId = (int)Request::post('template_id');
        $targetTagId = Request::post('target_tag_id') ? (int)Request::post('target_tag_id') : null;
        $targetStageId = Request::post('target_stage_id') ? (int)Request::post('target_stage_id') : null;

        if (empty($name) || empty($templateId)) {
            Response::error('Campaign name and WhatsApp Template are required.');
        }

        $template = WhatsAppTemplate::find($templateId);
        if (!$template) {
            Response::error('Selected template not found.');
        }

        // Filter target contacts
        $filters = [];
        if ($targetTagId) $filters['tag_id'] = $targetTagId;
        if ($targetStageId) $filters['stage_id'] = $targetStageId;

        $contacts = Contact::getAllWithFilters($filters);

        if (empty($contacts)) {
            Response::error('No contacts match the chosen audience filter.');
        }

        $broadcastId = Broadcast::create([
            'name'            => $name,
            'template_id'     => $templateId,
            'target_tag_id'   => $targetTagId,
            'target_stage_id' => $targetStageId,
            'total_contacts'  => count($contacts),
            'status'          => 'processing',
            'created_at'      => date('Y-m-d H:i:s')
        ]);

        // Send messages to each contact
        $sentCount = 0;
        $failedCount = 0;

        foreach ($contacts as $contact) {
            $apiRes = WhatsAppService::sendTemplate($contact['phone_number'], $template['name'], $template['language']);
            $metaMsgId = $apiRes['meta_message_id'] ?? null;
            $status = $apiRes['success'] ? 'sent' : 'failed';

            if ($apiRes['success']) {
                $sentCount++;
            } else {
                $failedCount++;
            }

            BroadcastLog::create([
                'broadcast_id'    => $broadcastId,
                'contact_id'      => (int)$contact['id'],
                'phone_number'    => $contact['phone_number'],
                'status'          => $status,
                'meta_message_id' => $metaMsgId,
                'error_message'   => $apiRes['error'] ?? null,
                'created_at'      => date('Y-m-d H:i:s')
            ]);

            // Also record in contact's chat conversation
            $conv = Conversation::getOrCreateForContact((int)$contact['id']);
            Message::create([
                'conversation_id' => (int)$conv['id'],
                'contact_id'      => (int)$contact['id'],
                'user_id'         => null,
                'direction'       => 'outbound',
                'message_type'    => 'template',
                'content'         => "📢 Campaign: {$name} (Template: {$template['name']})",
                'meta_message_id' => $metaMsgId ?: ('bcast_' . uniqid()),
                'status'          => $status,
                'created_at'      => date('Y-m-d H:i:s')
            ]);
            Conversation::updateLastMessage((int)$conv['id'], "📢 Campaign: {$name}", 'outbound');
        }

        Broadcast::update($broadcastId, [
            'sent_count'   => $sentCount,
            'failed_count' => $failedCount,
            'status'       => 'completed'
        ]);

        if (Request::isAjax()) {
            Response::success(['broadcast_id' => $broadcastId], "Campaign dispatched to {$sentCount} contacts.");
        }
        Response::redirect('/campaigns');
    }

    public function logs(int $id): void {
        $broadcast = Broadcast::find($id);
        $logs = BroadcastLog::getByBroadcast($id);
        Response::success(['broadcast' => $broadcast, 'logs' => $logs]);
    }
}
