<?php 
ob_start();
header('Content-Type: application/json');
$response_data = ['success' => false, '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';

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log("Error al decodificar JSON en lead-sources-delete.php: " . json_last_error_msg());
            throw new Exception('ERROR AL PROCESAR DATOS');
        }

        $source_id = isset($input['id']) ? filter_var($input['id'], FILTER_VALIDATE_INT) : null;

        if ($source_id === false || is_null($source_id)) {
            $response_data['message'] = 'ID INVALIDO';
        } else {
            try {
                $stmt = $pdo->prepare("DELETE FROM lead_sources WHERE id = :id");
                if ($stmt->execute([':id' => $source_id])) {
                    if ($stmt->rowCount() > 0) {
                        $response_data['success'] = true;
                        $response_data['message'] = 'FUENTE ELIMINADA';
                    } else {
                        $response_data['message'] = 'NO ENCONTRADA';
                    }
                } else {
                    throw new Exception('FALLO AL EJECUTAR ELIMINACION');
                }
            } catch (PDOException $e) {
                error_log("Error PDO al eliminar fuente de lead en lead-sources-delete.php: " . $e->getMessage());
                $response_data['message'] = 'ERROR DE BASE DE DATOS';
            } catch (Exception $e) {
                error_log("Error general al eliminar fuente de lead en lead-sources-delete.php: " . $e->getMessage());
                $response_data['message'] = strtoupper($e->getMessage());
            }
        }
    } else {
        $response_data['message'] = 'METODO NO PERMITIDO';
    }

} catch (Exception $e) {
    error_log("Error critico en lead-sources-delete.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR CRITICO';
}

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