<?php
session_start();
require_once __DIR__ . '/../config/db.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];
$response = ['success' => false, 'message' => 'An error occurred'];

// Get POST data
$first_name = isset($_POST['first_name']) ? trim($_POST['first_name']) : '';
$last_name = isset($_POST['last_name']) ? trim($_POST['last_name']) : '';
$phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
$address = isset($_POST['address']) ? trim($_POST['address']) : '';
$current_password = isset($_POST['current_password']) ? $_POST['current_password'] : '';
$new_password = isset($_POST['new_password']) ? $_POST['new_password'] : '';
$confirm_password = isset($_POST['confirm_password']) ? $_POST['confirm_password'] : '';

// Validation
if (empty($first_name) || empty($last_name)) {
    $response['message'] = 'First name and last name are required';
    echo json_encode($response);
    exit;
}

// Update basic info
$full_name = $first_name . ' ' . $last_name;
$update_query = "UPDATE users SET name = ?, phone = ?, address = ? WHERE id = ?";
$stmt = $conn->prepare($update_query);
$stmt->bind_param("sssi", $full_name, $phone, $address, $user_id);

if (!$stmt->execute()) {
    $response['message'] = 'Failed to update profile';
    echo json_encode($response);
    exit;
}

// Handle password change
if (!empty($current_password) || !empty($new_password)) {
    if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
        $response['message'] = 'Please fill all password fields';
        echo json_encode($response);
        exit;
    }

    if ($new_password !== $confirm_password) {
        $response['message'] = 'New passwords do not match';
        echo json_encode($response);
        exit;
    }

    if (strlen($new_password) < 6) {
        $response['message'] = 'Password must be at least 6 characters';
        echo json_encode($response);
        exit;
    }

    // Verify current password
    $user_query = "SELECT password FROM users WHERE id = ?";
    $stmt = $conn->prepare($user_query);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $user_result = $stmt->get_result();
    $user = $user_result->fetch_assoc();

    if (!password_verify($current_password, $user['password'])) {
        $response['message'] = 'Current password is incorrect';
        echo json_encode($response);
        exit;
    }

    // Update password
    $new_password_hash = password_hash($new_password, PASSWORD_BCRYPT);
    $password_query = "UPDATE users SET password = ? WHERE id = ?";
    $stmt = $conn->prepare($password_query);
    $stmt->bind_param("si", $new_password_hash, $user_id);
    
    if (!$stmt->execute()) {
        $response['message'] = 'Failed to update password';
        echo json_encode($response);
        exit;
    }
}

// Update session
$_SESSION['user_name'] = $full_name;

$response['success'] = true;
$response['message'] = 'Profile updated successfully!';
echo json_encode($response);
?>
