<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\Response;
use App\Models\Database;
use App\Services\MailService;

class HealthController extends BaseController
{
    public function index(): void
    {
        $dbStatus = 'disconnected';
        try {
            Database::connect()->query('SELECT 1');
            $dbStatus = 'connected';
        } catch (\Exception $e) {
            $dbStatus = 'error: ' . $e->getMessage();
        }

        Response::success([
            'app' => 'ItalvetCRM API',
            'version' => '1.0',
            'environment' => APP_ENV,
            'status' => 'running',
            'database' => $dbStatus,
        ], 'API funcionando correctamente');
    }

    public function notifications(): void
    {
        $diagnostic = [];
        $diagnostic['timezone'] = date_default_timezone_get();
        $diagnostic['now'] = date('Y-m-d H:i:s');
        $diagnostic['later'] = date('Y-m-d H:i:s', strtotime('+1 hour'));

        $mailConfig = require BASE_PATH . '/config/mail.php';
        $diagnostic['mail_host'] = $mailConfig['host'] . ':' . $mailConfig['port'];
        $diagnostic['mail_user'] = $mailConfig['user'];
        $diagnostic['mail_encryption'] = $mailConfig['encryption'];

        try {
            $pdo = Database::connect();

            $total = $pdo->query("SELECT COUNT(*) as c FROM tasks")->fetch();
            $diagnostic['total_tasks'] = (int) $total['c'];

            $pendientes = $pdo->query("SELECT COUNT(*) as c FROM tasks WHERE status='pendiente'")->fetch();
            $diagnostic['pending_tasks'] = (int) $pendientes['c'];

            $now = date('Y-m-d H:i:s');
            $later = date('Y-m-d H:i:s', strtotime('+1 hour'));
            $stmt = $pdo->prepare(
                "SELECT t.id, t.scheduled_date, t.scheduled_time,
                        CONCAT(t.scheduled_date, ' ', IFNULL(t.scheduled_time, '00:00')) as full_date,
                        t.lead_id, t.assigned_to, t.type,
                        l.first_name, l.last_name,
                        u.email as user_email
                 FROM tasks t
                 LEFT JOIN leads l ON t.lead_id = l.id
                 LEFT JOIN users u ON t.assigned_to = u.id
                 WHERE t.status = 'pendiente'
                 AND CONCAT(t.scheduled_date, ' ', IFNULL(t.scheduled_time, '00:00')) BETWEEN :now AND :later
                 LIMIT 20"
            );
            $stmt->execute(['now' => $now, 'later' => $later]);
            $tasksInRange = $stmt->fetchAll();
            $diagnostic['tasks_in_range'] = [];
            foreach ($tasksInRange as $t) {
                $diagnostic['tasks_in_range'][] = [
                    'id' => $t['id'],
                    'full_date' => $t['full_date'],
                    'lead_id' => $t['lead_id'],
                    'type' => $t['type'],
                    'lead_name' => ($t['first_name'] ?? '') . ' ' . ($t['last_name'] ?? ''),
                    'user_email' => $t['user_email'],
                ];
            }

            $joined = $pdo->query(
                "SELECT COUNT(*) as c FROM tasks t
                 JOIN leads l ON t.lead_id = l.id
                 JOIN users u ON t.assigned_to = u.id
                 WHERE t.status = 'pendiente'"
            )->fetch();
            $diagnostic['tasks_with_valid_joins'] = (int) $joined['c'];

            $nullLead = $pdo->query(
                "SELECT COUNT(*) as c FROM tasks WHERE lead_id IS NULL AND status='pendiente'"
            )->fetch();
            $diagnostic['tasks_without_lead'] = (int) $nullLead['c'];

            $notifCount = $pdo->query(
                "SELECT COUNT(*) as c FROM notifications WHERE type='tarea_proxima'"
            )->fetch();
            $diagnostic['existing_notifications'] = (int) $notifCount['c'];

            $cfgs = $pdo->query("SELECT `key` FROM configurations WHERE `key` LIKE 'smtp_%'")->fetchAll();
            $diagnostic['smtp_overrides_in_db'] = count($cfgs);
            $diagnostic['smtp_override_keys'] = array_column($cfgs, 'key');

        } catch (\Throwable $e) {
            $diagnostic['db_error'] = $e->getMessage();
        }

        Response::success($diagnostic, 'Diagnóstico de notificaciones');
    }

    public function testNotification(): void
    {
        $output = [];
        $output['step1'] = 'Iniciando test...';

        try {
            $mailService = new MailService();
            $output['step2'] = 'MailService configurado: ' . ($mailService->isConfigured() ? 'SI' : 'NO');

            // Verificar búsqueda de tareas con EXACTAMENTE la misma query
            $db = \App\Models\Database::connect();
            $now = date('Y-m-d H:i:s');
            $later = date('Y-m-d H:i:s', strtotime('+1 hour'));

            $stmt = $db->prepare(
                "SELECT t.id, CONCAT(t.scheduled_date, ' ', IFNULL(t.scheduled_time, '00:00')) as full_date,
                        t.lead_id, t.assigned_to, t.type,
                        l.first_name, l.last_name, u.email as user_email
                 FROM tasks t
                 JOIN leads l ON t.lead_id = l.id
                 JOIN users u ON t.assigned_to = u.id
                 WHERE t.status = 'pendiente'
                 AND CONCAT(t.scheduled_date, ' ', IFNULL(t.scheduled_time, '00:00')) BETWEEN :now AND :later
                 AND NOT EXISTS (
                   SELECT 1 FROM notifications n
                   WHERE n.reference_type = 'task'
                   AND n.reference_id = t.id
                   AND n.type = 'tarea_proxima'
                 )
                 LIMIT 100"
            );
            $stmt->execute(['now' => $now, 'later' => $later]);
            $tasks = $stmt->fetchAll();
            $output['step4'] = 'Tareas encontradas por INNER JOIN: ' . count($tasks);
            foreach ($tasks as $t) {
                $output['task_' . $t['id']] = "lead={$t['lead_id']} user={$t['user_email']} date={$t['full_date']}";
            }

            // Forzar envío manual a bdelacruz654@gmail.com para probar
            if (count($tasks) > 0) {
                $task = $tasks[0];
                $typeLabel = 'TEST';
                $leadName = $task['first_name'] . ' ' . $task['last_name'];
                $output['step5'] = 'Intentando enviar correo a ' . $task['user_email'] . '...';
                try {
                    $mailService->sendTaskReminder(
                        $task['user_email'],
                        $typeLabel,
                        $leadName,
                        date('Y-m-d'),
                        date('H:i')
                    );
                    $output['step6'] = '✅ Correo enviado correctamente';
                } catch (\Throwable $e) {
                    $output['step6'] = '❌ Error enviando correo: ' . $e->getMessage();
                }
            } else {
                $output['step5'] = 'No hay tareas para probar envío';
            }

        } catch (\Throwable $e) {
            $output['error'] = $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine();
        }

        Response::success($output, 'Test de notificación');
    }
}
