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

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

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        $http_code = 405; 
        throw new Exception('METODO NO PERMITIDO');
    }

    $data = json_decode(file_get_contents("php://input"), true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        $http_code = 400;
        throw new Exception('DATOS JSON INVALIDOS');
    }

    // Validación estricta
    $client_id = isset($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;
    $note_content = isset($data['content']) ? trim($data['content']) : null;

    if (!$client_id || empty($note_content)) {
        $http_code = 400;
        throw new Exception('ID O CONTENIDO FALTANTE');
    }

    // 1. Verificar que el cliente exista (Integridad Referencial - Sentencia preparada)
    $stmtCheck = $pdo->prepare("SELECT id FROM clients WHERE id = ?");
    $stmtCheck->execute([$client_id]);
    if (!$stmtCheck->fetch()) {
        $http_code = 404;
        throw new Exception('CLIENTE NO ENCONTRADO');
    }

    // 2. Sanitización para almacenamiento
    $safe_content = htmlspecialchars($note_content, ENT_QUOTES, 'UTF-8');
    $current_time = date('Y-m-d H:i:s');

    // 3. Inserción (Sentencia preparada)
    $stmt = $pdo->prepare("INSERT INTO client_notes (client_id, content, created_at) VALUES (?, ?, ?)");
    $stmt->execute([$client_id, $safe_content, $current_time]);
    
    $new_note_id = $pdo->lastInsertId();

    $response = [
        'success' => true,
        'message' => 'NOTA GUARDADA',
        'note' => [
            'id' => $new_note_id,
            'date' => date('Y-m-d', strtotime($current_time)), // Formato para JS
            'content' => $safe_content // Devolvemos el contenido seguro
        ]
    ];
    $http_code = 200;

} catch (PDOException $e) {
    error_log("Error DB en recurring-client-note.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    $response['message'] = strtoupper($e->getMessage());
    // Mantener 500 si no se especificó otro código
    $http_code = ($http_code === 200) ? 500 : $http_code;
}

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