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

ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php';

header('Content-Type: application/json');
ob_clean();

$response = [];

if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = "Database Connection Failed.";
    echo json_encode($response);
    exit;
}

$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)) { /* ... validation ... */ }

try {
    $sql = "UPDATE users SET name = ?, address = ? WHERE id = ?";
    $params = [$name, $address, $userId];
    $types = "ssi";

    if (!empty($currentPassword) && !empty($newPassword)) {
        // THE FIX: Select the 'password_hash' column
        $user_sql = "SELECT password_hash 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();

        // THE FIX: Verify against the 'password_hash' column
        if ($user && password_verify($currentPassword, $user['password_hash'])) {
            $hashedNewPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            // THE FIX: Update the 'password_hash' column
            $sql = "UPDATE users SET name = ?, address = ?, password_hash = ? 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();
}

echo json_encode($response);
$conn->close();
exit;
?>