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

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';
    include_once 'file_helpers.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('METODO NO PERMITIDO');
    }
    
    $input = json_decode(file_get_contents('php://input'), true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('ERROR AL PROCESAR DATOS');
    }
    if (empty($input)) {
        throw new Exception('DATOS VACIOS');
    }

    $user_id = 1; 
    $tenant_id = 1;

    $full_name = filter_var(trim($input['full_name'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $new_profile_photo_url = filter_var($input['profile_photo_url'] ?? null, FILTER_SANITIZE_URL);

    if (empty($full_name)) {
        throw new Exception('NOMBRE REQUERIDO');
    }

    $pdo->beginTransaction();

    $stmt_old_photo = $pdo->prepare("SELECT profile_photo_url FROM users WHERE user_id = ? FOR UPDATE");
    $stmt_old_photo->execute([$user_id]);
    $old_profile_photo_url = $stmt_old_photo->fetchColumn();

    $stmt_update = $pdo->prepare("UPDATE users SET full_name = ?, profile_photo_url = ? WHERE user_id = ?");
    $stmt_update->execute([$full_name, $new_profile_photo_url, $user_id]);

    $pdo->commit();

    if (!empty($old_profile_photo_url) && $old_profile_photo_url !== $new_profile_photo_url) {
        deleteFileFromServer($old_profile_photo_url, $tenant_id);
    }

    $response['success'] = true;
    $response['message'] = 'PERFIL ACTUALIZADO';

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("Error PDO en user-profile-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("General Error en user-profile-update.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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