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

try {
    require_once '../core/api.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);
    $state = filter_var(trim($input['state'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $timezone = filter_var(trim($input['timezone'] ?? ''), FILTER_SANITIZE_FULL_SPECIAL_CHARS);

    if (empty($full_name)) {
        throw new Exception('NOMBRE REQUERIDO');
    }
    if (empty($state)) {
        throw new Exception('ESTADO REQUERIDO');
    }
    if (empty($timezone)) {
        throw new Exception('ZONA HORARIA REQUERIDA');
    }

    $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_users = $pdo->prepare("UPDATE users SET full_name = ?, profile_photo_url = ? WHERE user_id = ?");
    $stmt_update_users->execute([$full_name, $new_profile_photo_url, $user_id]);

    $stmt_update_business = $pdo->prepare("UPDATE business_info SET state = ?, timezone = ? WHERE user_id = ?");
    $stmt_update_business->execute([$state, $timezone, $user_id]);


    $pdo->commit();

    if (!empty($old_profile_photo_url) && $old_profile_photo_url !== $new_profile_photo_url) {
        if (function_exists('deleteFileFromServer')) {
            deleteFileFromServer($old_profile_photo_url, $tenant_id);
        } else {
             error_log("Advertencia: deleteFileFromServer no está disponible para borrar el archivo: " . $old_profile_photo_url);
        }
    }

    $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;
?>