<?php

declare(strict_types=1);

require_once __DIR__ . '/../models/WhatsAppConfig.php';
require_once __DIR__ . '/../models/WhatsAppLog.php';
require_once __DIR__ . '/../models/WhatsAppDispatch.php';
require_once __DIR__ . '/../services/WhatsAppService.php';

class WhatsAppController extends Controller
{
    public function index(): void
    {
        Auth::requireAdmin();

        $service = new WhatsAppService();
        $config = $service->config();
        $logs = $service->latestLogs(20);
        $payloadPreview = $service->outboundPayloadPreview();

        $this->view('whatsapp/index', compact('config', 'logs', 'payloadPreview'), 'admin');
    }

    public function save(): void
    {
        Auth::requireAdmin();

        $model = new WhatsAppConfig();
        $data = [
            'provider_name' => trim((string) ($_POST['provider_name'] ?? 'WayChat')),
            'integration_mode' => trim((string) ($_POST['integration_mode'] ?? 'waychat')),
            'webhook_url' => trim((string) ($_POST['webhook_url'] ?? '')),
            'auth_token' => trim((string) ($_POST['auth_token'] ?? '')),
            'company_auth_token' => trim((string) ($_POST['company_auth_token'] ?? '')),
            'webhook_token' => trim((string) ($_POST['webhook_token'] ?? '')),
            'waychat_base_url' => trim((string) ($_POST['waychat_base_url'] ?? 'https://waychat.app.br')),
            'waychat_connection_type' => trim((string) ($_POST['waychat_connection_type'] ?? 'cloud')),
            'waychat_send_mode' => trim((string) ($_POST['waychat_send_mode'] ?? 'message')),
            'waychat_template_name' => trim((string) ($_POST['waychat_template_name'] ?? '')),
            'waychat_template_language' => trim((string) ($_POST['waychat_template_language'] ?? 'pt_BR')),
            'waychat_create_deal' => isset($_POST['waychat_create_deal']) ? 1 : 0,
            'waychat_sector_name' => trim((string) ($_POST['waychat_sector_name'] ?? '')),
            'waychat_column_name' => trim((string) ($_POST['waychat_column_name'] ?? '')),
            'waychat_status_on_send' => trim((string) ($_POST['waychat_status_on_send'] ?? 'waiting')),
            'telefone_remetente' => trim((string) ($_POST['telefone_remetente'] ?? '')),
            'ativo' => isset($_POST['ativo']) ? 1 : 0,
            'auto_notify_new' => isset($_POST['auto_notify_new']) ? 1 : 0,
            'auto_notify_status' => isset($_POST['auto_notify_status']) ? 1 : 0,
            'auto_notify_sla' => isset($_POST['auto_notify_sla']) ? 1 : 0,
            'auto_create_from_webhook' => isset($_POST['auto_create_from_webhook']) ? 1 : 0,
            'template_nova_ocorrencia' => trim((string) ($_POST['template_nova_ocorrencia'] ?? '')),
            'template_status' => trim((string) ($_POST['template_status'] ?? '')),
            'template_sla' => trim((string) ($_POST['template_sla'] ?? '')),
        ];

        $model->save($data);
        Session::flash('sucesso', 'Configurações do WayChat/CRM salvas com sucesso.');
        $this->redirect('/admin/whatsapp');
    }

    public function test(): void
    {
        Auth::requireAdmin();

        $telefone = preg_replace('/\D+/', '', (string) ($_POST['telefone_teste'] ?? ''));
        if ($telefone === '') {
            Session::flash('erro', 'Informe um telefone para teste.');
            $this->redirect('/admin/whatsapp');
        }

        $service = new WhatsAppService();
        $res = $service->sendTest($telefone, 'Olá! Este é um teste do Prefeitura Resolve com integração real do WayChat.');
        Session::flash(!empty($res['success']) ? 'sucesso' : 'erro', !empty($res['success']) ? 'Mensagem de teste enviada com sucesso.' : 'Falha no teste: ' . (($res['error'] ?? '') ?: ($res['body'] ?? 'sem retorno.')));
        $this->redirect('/admin/whatsapp');
    }

    public function processSla(): void
    {
        Auth::requireAdmin();
        $service = new WhatsAppService();
        $result = $service->processSlaAlerts();
        Session::flash('sucesso', 'Automação de SLA executada. Enviados: ' . (int) $result['enviados'] . ' | Ignorados: ' . (int) $result['ignorados']);
        $this->redirect('/admin/whatsapp');
    }
}
