<?php
// FINAL ROBUST SCRIPT: update_user_profile.php

// Start output buffering to prevent any stray output from breaking the JSON response.
ob_start();

// Set up error logging for production.
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Set the header to indicate the response is JSON.
header('Content-Type: application/json');

$response = [];

// --- 1. Robustly include the database connection ---
try {
    require 'db_connect.php';
} catch (Throwable $t) {
    // This will catch any fatal error if the 'require' statement fails.
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = "FATAL ERROR: Could not include db_connect.php. Reason: " . $t->getMessage();
    ob_clean(); // Clean the buffer before sending the final JSON
    echo json_encode($response);
    exit;
}

// --- 2. Validate the database connection object ---
if (!isset($conn) || !($conn instanceof mysqli)) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = "Server Error: db_connect.php was included but did not create a valid \$conn object.";
    ob_clean();
    echo json_encode($response);
    exit;
}
if ($conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = "Server Error: Database connection failed. Server says: " . $conn->connect_error;
    ob_clean();
    echo json_encode($response);
    exit;
}


// --- 3. Validate the incoming data from the app ---
$userId = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$address = isset($_POST['address']) ? trim($_POST['address']) : '';
$currentPassword = isset($_POST['current_password']) ? $_POST['current_password'] : '';
$newPassword = isset($_POST['new_password']) ? $_POST['new_password'] : '';

if (empty($userId) || empty($name) || empty($address)) {
    http_response_code(400); // Bad Request
    $response['status'] = 'error';
    $response['message'] = 'User ID, name, and address are required.';
    ob_clean();
    echo json_encode($response);
    exit;
}

// --- 4. Prepare and execute the database update ---
try {
    $sql = "UPDATE users SET name = ?, address = ? WHERE id = ?";
    $params = [$name, $address, $userId];
    $types = "ssi";

    if (!empty($currentPassword) && !empty($newPassword)) {
        $user_sql = "SELECT password FROM users WHERE id = ?";
        $stmt_user = $conn->prepare($user_sql);
        $stmt_user->bind_param("i", $userId);
        $stmt_user->execute();
        $result = $stmt_user->get_result();
        $user = $result->fetch_assoc();
        $stmt_user->close();

        if ($user && password_verify($currentPassword, $user['password'])) {
            $hashedNewPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            $sql = "UPDATE users SET name = ?, address = ?, password = ? WHERE id = ?";
            $params = [$name, $address, $hashedNewPassword, $userId];
            $types = "sssi";
        } else {
            throw new Exception('Incorrect current password.');
        }
    }

    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);

    if ($stmt->execute()) {
        $response['status'] = 'success';
        $response['message'] = 'Profile updated successfully.';
    } else {
        throw new Exception('Failed to execute the update statement.');
    }

    $stmt->close();

} catch (Exception $e) {
    http_response_code(400);
    $response['status'] = 'error';
    $response['message'] = $e->getMessage();
}

// --- 5. Send the final JSON response ---
ob_clean();
echo json_encode($response);
$conn->close();
exit;
?>