<?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);

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

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

        $model = new WhatsAppConfig();
        $data = [
            'provider_name' => trim((string) ($_POST['provider_name'] ?? 'Webhook genérico')),
            'webhook_url' => trim((string) ($_POST['webhook_url'] ?? '')),
            'auth_token' => trim((string) ($_POST['auth_token'] ?? '')),
            'webhook_token' => trim((string) ($_POST['webhook_token'] ?? '')),
            '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 WhatsApp 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, 'Teste de integração Prefeitura Resolve V1.10.0.');
        Session::flash(!empty($res['success']) ? 'sucesso' : 'erro', !empty($res['success']) ? 'Mensagem de teste enviada.' : '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');
    }
}
