<?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('db_connection.php'); 
    require_once '../files/guardiankey.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');
    }

    $client_id = isset($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;
    $note_content = isset($data['content']) ? filter_var($data['content'], FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $current_time = date('Y-m-d H:i:s');

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

    $stmt = $pdo->prepare("INSERT INTO client_notes (client_id, content, created_at) VALUES (?, ?, ?)");
    $stmt->execute([$client_id, $note_content, $current_time]);
    
    $new_note_id = $pdo->lastInsertId();

    $response['success'] = true;
    $response['message'] = 'NOTA GUARDADA';
    $response['note'] = [
        'id' => $new_note_id,
        'date' => date('Y-m-d', strtotime($current_time)),
        'content' => $note_content
    ];
    $http_code = 200;

} catch (PDOException $e) {
    error_log("Error al guardar la nota del cliente (ID: $client_id): " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
    $http_code = 500;
} catch (Exception $e) {
    $response['message'] = strtoupper($e->getMessage());
    $http_code = isset($http_code) && $http_code !== 500 ? $http_code : 500;
    error_log($response['message']);
}

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