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

    $data = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR AL PROCESAR DATOS');
    }
    if (!isset($data['lead_id']) || empty($data['content'])) {
        throw new Exception('DATOS INCOMPLETOS');
    }

    $lead_id = filter_var($data['lead_id'], FILTER_VALIDATE_INT);
    $content = filter_var($data['content'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if ($lead_id === false) {
        throw new Exception('ID INVALIDO');
    }

    $stmt = $pdo->prepare("INSERT INTO lead_notes (lead_id, content) VALUES (?, ?)");
    $stmt->execute([$lead_id, $content]);
    
    $new_note_id = $pdo->lastInsertId();
    $stmt = $pdo->prepare("SELECT id, content, created_at FROM lead_notes WHERE id = ?");
    $stmt->execute([$new_note_id]);
    $note = $stmt->fetch(PDO::FETCH_ASSOC);

    $response = ['success' => true, 'message' => 'NOTA GUARDADA', 'note' => $note];
    
} catch (PDOException $e) {
    error_log("Error PDO en leads-add-note.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    error_log("General Error en leads-add-note.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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