<?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-create.php: " . json_last_error_msg());
            throw new Exception('ERROR AL PROCESAR DATOS');
        }

        $source_name = filter_var(trim($input['name'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);

        if (empty($source_name)) {
            $response_data['message'] = 'NOMBRE REQUERIDO';
        } else {
            try {
                $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM lead_sources WHERE name = :name");
                $stmt_check->execute([':name' => $source_name]);
                if ($stmt_check->fetchColumn() > 0) {
                    $response_data['message'] = 'FUENTE YA EXISTE';
                } else {
                    $stmt = $pdo->prepare("INSERT INTO lead_sources (name) VALUES (:name)");
                    if ($stmt->execute([':name' => $source_name])) {
                        $response_data['success'] = true;
                        $response_data['message'] = 'FUENTE CREADA';
                        $response_data['id'] = $pdo->lastInsertId();
                        $response_data['name'] = $source_name;
                    } else {
                        throw new Exception('FALLO AL AGREGAR FUENTE');
                    }
                }
            } catch (PDOException $e) {
                error_log("Error PDO al crear fuente de lead en lead-sources-create.php: " . $e->getMessage());
                $response_data['message'] = 'ERROR DE BASE DE DATOS';
            } catch (Exception $e) {
                error_log("Error general al crear fuente de lead en lead-sources-create.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-create.php: " . $e->getMessage());
    $response_data['message'] = 'ERROR CRITICO';
}

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