<?php

namespace serviciocorreo;

require_once __DIR__ . '/../conexion_bbdd/vendor/autoload.php';
require_once __DIR__ . '/../conexion_bbdd/Config/Database.php';
require_once __DIR__ . '/../Logger.php';
require_once __DIR__ . './7diasenvios.php';

use Utils\Database;
use Utils\Logger;
use Utils\EnvioDeCorreos;

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


    $consultadecorreoelectronicos = "
        SELECT ch.email, 
            CASE 
                WHEN cd.date = CURRENT_DATE + INTERVAL '7 days' THEN '7'
                WHEN cd.date = CURRENT_DATE + INTERVAL '5 days' THEN '5'
                WHEN cd.date = CURRENT_DATE + INTERVAL '3 days' THEN '3'
                WHEN cd.date = CURRENT_DATE + INTERVAL '1 days' THEN '1'
                WHEN cd.date = CURRENT_DATE THEN '0'
                ELSE 'Otro'
            END AS dias_restantes
        FROM clinic_history ch
        JOIN contract c ON ch.id = c.idclinichistory
        JOIN contract_detail cd ON c.id = cd.idcontract
        WHERE cd.date IN (CURRENT_DATE, CURRENT_DATE + INTERVAL '1 days', CURRENT_DATE + INTERVAL '3 days', CURRENT_DATE + INTERVAL '5 days', CURRENT_DATE + INTERVAL '7 days');";

    $consultadecorreoelectronicosejecutar = $pdo->query($consultadecorreoelectronicos);

    $emails = array(
        '7' => array(),
        '5' => array(),
        '3' => array(),
        '1' => array(),
        '0' => array(),
        'Otro' => array()
    );

    while ($row = $consultadecorreoelectronicosejecutar->fetch()) {
        $dias_restantes = $row['dias_restantes'];
        $emails[$dias_restantes][] = $row['email'];
    }

    foreach ($emails as $dias => $correos) {
        echo "Correos electrónicos con $dias días restantes para el vencimiento:</br>";
        foreach ($correos as $correo) {
            echo "$correo</br>";
            EnvioDeCorreos::Envio($correo);
            sleep(5);
        }
        echo "</br>";
    }
    
    $pdo = null;

    
    echo json_encode(['success' => true, 'message' => 'Correos electrónicos enviados correctamente']);
} catch (\PDOException $e) {
    $mensajeError = "Error al conectar con la base de datos: " . $e->getMessage();
    Logger::logError('ERROR', $mensajeError, __FILE__, __LINE__);
    echo json_encode(['success' => false, 'message' => 'Error ' . $mensajeError]);
} catch (\Exception $e) {
    $mensajeError = "Error no capturado: " . $e->getMessage();
    Logger::logError('ERROR', $mensajeError, __FILE__, __LINE__);
    echo json_encode(['success' => false, 'message' => 'Error ' . $mensajeError]);
}
