<?php
header('Content-Type: application/json; charset=UTF-8');
ini_set('display_errors', 1);
error_reporting(E_ALL);

try {
    $host = 'localhost';
    $dbname = 'CORREOS';
    $user = 'root';
    $pass = 'root';

    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);

    // Traer correos con sus áreas
    $stmt = $pdo->query("
        SELECT 
            c.ID_CORREO,
            c.REMITENTE,
            c.ASUNTO,
            c.FECHA_ENVIO,
            IFNULL(ca.AREA, '') AS AREA,
            IFNULL(ca.ESTADO, '') AS ESTADO,
            IFNULL(ca.NOTA, '') AS NOTA
        FROM CORREO c
        LEFT JOIN CORREO_AREAS ca 
            ON c.ID_CORREO = ca.ID_CORREO
        ORDER BY c.FECHA_ENVIO DESC
    ");

    $correos = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        "success" => true,
        "data" => $correos
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error: " . $e->getMessage()
    ]);
}
