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

try {
    require_once __DIR__ . '/../core/api.php';

    ini_set('display_errors', 0);
    error_reporting(E_ALL);

    $input = json_decode(file_get_contents('php://input'), true);
    $name = isset($input['name']) ? trim($input['name']) : '';

    if (empty($name)) {
        throw new Exception('El nombre de la fuente es obligatorio.');
    }

    $stmt = $pdo->prepare("SELECT id FROM lead_sources WHERE name = ?");
    $stmt->execute([$name]);
    if ($stmt->fetch()) {
        throw new Exception('Esta fuente ya existe.');
    }

    $stmt = $pdo->prepare("INSERT INTO lead_sources (name) VALUES (?)");
    if ($stmt->execute([$name])) {
        $response = [
            'success' => true, 
            'message' => 'FUENTE CREADA', 
            'id' => $pdo->lastInsertId(),
            'name' => $name
        ];
    } else {
        throw new Exception('No se pudo guardar en la base de datos.');
    }

} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

if (ob_get_length()) ob_clean();
echo json_encode($response);
exit;
?>