<?php
namespace App\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Contact;
use App\Models\Conversation;
use App\Models\PipelineStage;
use App\Models\Tag;
use App\Models\User;
use App\Models\Deal;

class ContactsController extends Controller {
    public function index(): void {
        $filters = [
            'search'      => Request::get('search'),
            'stage_id'    => Request::get('stage_id'),
            'assigned_to' => Request::get('assigned_to'),
            'tag_id'      => Request::get('tag_id')
        ];

        $contacts = Contact::getAllWithFilters($filters);
        $stages = PipelineStage::getOrdered();
        $tags = Tag::all('name ASC');
        $agents = User::getActiveAgents();

        $this->render('contacts/index', [
            'contacts' => $contacts,
            'stages'   => $stages,
            'tags'     => $tags,
            'agents'   => $agents,
            'filters'  => $filters
        ]);
    }

    public function view(int $id): void {
        $contact = Contact::getWithDetails($id);
        if (!$contact) {
            Response::redirect('/contacts?error=not_found');
        }

        $stages = PipelineStage::getOrdered();
        $tags = Tag::all('name ASC');
        $agents = User::getActiveAgents();
        $deals = Deal::getByContact($id);

        $this->render('contacts/view', [
            'contact' => $contact,
            'stages'  => $stages,
            'tags'    => $tags,
            'agents'  => $agents,
            'deals'   => $deals
        ]);
    }

    public function store(): void {
        $name = trim(Request::post('name', 'WhatsApp User'));
        $phone = trim(Request::post('phone_number', ''));
        $email = trim(Request::post('email', ''));
        $company = trim(Request::post('company', ''));
        $stageId = (int)Request::post('stage_id', 1);
        $assignedTo = Request::post('assigned_to') ? (int)Request::post('assigned_to') : null;
        $notes = trim(Request::post('notes', ''));
        $tagIds = Request::post('tag_ids', []);

        if (empty($phone)) {
            Response::error('Phone number is required');
        }

        $whatsappId = preg_replace('/[^0-9]/', '', $phone);

        $existing = Contact::findByWhatsAppId($whatsappId);
        if ($existing) {
            Response::error('Contact with this WhatsApp number already exists');
        }

        $contactId = Contact::create([
            'whatsapp_id'   => $whatsappId,
            'phone_number'  => '+' . $whatsappId,
            'name'          => $name,
            'email'         => $email ?: null,
            'company'       => $company ?: null,
            'stage_id'      => $stageId ?: 1,
            'assigned_to'   => $assignedTo,
            'notes'         => $notes ?: null,
            'source'        => 'manual',
            'created_at'    => date('Y-m-d H:i:s')
        ]);

        if (is_array($tagIds)) {
            Contact::syncTags($contactId, $tagIds);
        }

        // Initialize conversation thread
        Conversation::getOrCreateForContact($contactId, $assignedTo);

        if (Request::isAjax()) {
            Response::success(['contact_id' => $contactId], 'Contact created successfully');
        }
        Response::redirect("/contacts/{$contactId}");
    }

    public function update(int $id): void {
        $name = trim(Request::post('name', ''));
        $phone = trim(Request::post('phone_number', ''));
        $email = trim(Request::post('email', ''));
        $company = trim(Request::post('company', ''));
        $stageId = Request::post('stage_id') ? (int)Request::post('stage_id') : null;
        $assignedTo = Request::post('assigned_to') ? (int)Request::post('assigned_to') : null;
        $notes = trim(Request::post('notes', ''));
        $tagIds = Request::post('tag_ids', []);

        $contact = Contact::find($id);
        if (!$contact) {
            Response::error('Contact not found');
        }

        $updateData = [
            'name'        => $name ?: $contact['name'],
            'email'       => $email ?: null,
            'company'     => $company ?: null,
            'stage_id'    => $stageId,
            'assigned_to' => $assignedTo,
            'notes'       => $notes ?: null
        ];

        if (!empty($phone)) {
            $whatsappId = preg_replace('/[^0-9]/', '', $phone);
            $updateData['whatsapp_id'] = $whatsappId;
            $updateData['phone_number'] = '+' . $whatsappId;
        }

        Contact::update($id, $updateData);

        if (is_array($tagIds)) {
            Contact::syncTags($id, $tagIds);
        }

        if (Request::isAjax()) {
            Response::success(Contact::getWithDetails($id), 'Contact updated');
        }
        Response::redirect("/contacts/{$id}");
    }

    public function delete(int $id): void {
        Contact::delete($id);
        if (Request::isAjax()) {
            Response::success(null, 'Contact deleted');
        }
        Response::redirect('/contacts');
    }

    public function importCsv(): void {
        if (empty($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
            Response::error('Please choose a valid CSV file to import.');
        }

        $file = fopen($_FILES['csv_file']['tmp_name'], 'r');
        $headers = fgetcsv($file);

        $imported = 0;
        $skipped = 0;

        while (($row = fgetcsv($file)) !== false) {
            if (empty($row[0])) continue;
            // Expecting: Name, Phone, Email, Company, Notes
            $name = trim($row[0] ?? 'WhatsApp User');
            $phone = trim($row[1] ?? '');
            $email = trim($row[2] ?? '');
            $company = trim($row[3] ?? '');
            $notes = trim($row[4] ?? '');

            if (empty($phone)) {
                $skipped++;
                continue;
            }

            $whatsappId = preg_replace('/[^0-9]/', '', $phone);
            if (empty($whatsappId)) {
                $skipped++;
                continue;
            }

            $existing = Contact::findByWhatsAppId($whatsappId);
            if ($existing) {
                $skipped++;
                continue;
            }

            $cid = Contact::create([
                'whatsapp_id'   => $whatsappId,
                'phone_number'  => '+' . $whatsappId,
                'name'          => $name,
                'email'         => $email ?: null,
                'company'       => $company ?: null,
                'stage_id'      => 1,
                'notes'         => $notes ?: null,
                'source'        => 'csv_import',
                'created_at'    => date('Y-m-d H:i:s')
            ]);

            Conversation::getOrCreateForContact($cid);
            $imported++;
        }
        fclose($file);

        Response::success(['imported' => $imported, 'skipped' => $skipped], "Import complete: {$imported} added, {$skipped} skipped.");
    }

    public function exportCsv(): void {
        $contacts = Contact::getAllWithFilters();

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=whatsapp_crm_contacts_' . date('Y-m-d') . '.csv');

        $output = fopen('php://output', 'w');
        fputcsv($output, ['ID', 'Name', 'WhatsApp Phone', 'Email', 'Company', 'Stage', 'Assigned Agent', 'Created At']);

        foreach ($contacts as $c) {
            fputcsv($output, [
                $c['id'],
                $c['name'],
                $c['phone_number'],
                $c['email'] ?? '',
                $c['company'] ?? '',
                $c['stage_name'] ?? '',
                $c['assigned_user_name'] ?? 'Unassigned',
                $c['created_at']
            ]);
        }
        fclose($output);
        exit;
    }
}
