<?php 
ob_start();
header('Content-Type: application/json');
$response_data = ['success' => false, 'data' => [], 'message' => 'ERROR DESCONOCIDO'];

try {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    $stmt = $pdo->query("SELECT id, name FROM lead_sources ORDER BY name ASC");
    $sources = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $formatted_sources = [];
    foreach ($sources as $source) {
        $formatted_sources[] = [
            'id' => (int)$source['id'],
            'name' => $source['name']
        ];
    }

    $response_data = ['success' => true, 'data' => $formatted_sources];

} catch (PDOException $e) {
    error_log("Error PDO al cargar fuentes de leads en lead-sources-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("Error general al cargar fuentes de leads en lead-sources-read.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR INESPERADO';
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response_data);
exit;
?>