<?php

declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';

use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(dirname(__DIR__));
$dotenv->safeLoad();

define('BASE_PATH', dirname(__DIR__));
define('STORAGE_PATH', BASE_PATH . '/storage');
define('APP_ENV', $_ENV['APP_ENV'] ?? 'development');

date_default_timezone_set('America/Lima');

echo "Inicio: " . date('Y-m-d H:i:s') . "\n";
echo "BASE_PATH: " . BASE_PATH . "\n";
echo "TZ: " . date_default_timezone_get() . "\n";

// Verificar config de correo
$mailConfig = require BASE_PATH . '/config/mail.php';
echo "Mail host: {$mailConfig['host']}:{$mailConfig['port']}\n";
echo "Mail user: {$mailConfig['user']}\n";
echo "Mail enc:  {$mailConfig['encryption']}\n";

// Diagnosticar tareas pendientes
try {
    $db = \App\Models\Database::connect();
    $now = date('Y-m-d H:i:s');
    $later = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    // 1. Total de tareas pendientes
    $total = $db->query("SELECT COUNT(*) as c FROM tasks WHERE status='pendiente'")->fetch();
    echo "Total tareas pendientes: {$total['c']}\n";
    
    // 2. Tareas que DEBERÍAN coincidir con el rango
    $stmt = $db->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
         FROM tasks t
         WHERE t.status = 'pendiente'
         AND CONCAT(t.scheduled_date, ' ', IFNULL(t.scheduled_time, '00:00')) BETWEEN :now AND :later"
    );
    $stmt->execute(['now' => $now, 'later' => $later]);
    $matching = $stmt->fetchAll();
    echo "Tareas en rango horario: " . count($matching) . "\n";
    foreach ($matching as $t) {
        echo "  - ID {$t['id']}: fecha={$t['scheduled_date']} hora={$t['scheduled_time']} full={$t['full_date']} lead_id={$t['lead_id']} assigned={$t['assigned_to']}\n";
    }
    
    // 3. Notificaciones existentes
    echo "Rango now: {$now} | later: {$later}\n";
    
} catch (\Throwable $e) {
    echo "ERROR DB: " . $e->getMessage() . "\n";
}

try {
    $service = new \App\Services\NotificationService();
    $count = $service->checkUpcomingTasks();
    echo "Resultado checkUpcomingTasks: {$count} notificaciones\n";
} catch (\Throwable $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
    echo "File: " . $e->getFile() . ":" . $e->getLine() . "\n";
}

echo "Fin: " . date('Y-m-d H:i:s') . "\n";
