<?php
header('Content-Type: application/json');
require_once '../includes/auth.php';
require_once '../includes/functions.php';

if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit();
}

$user_id = $auth->getCurrentUserId();
$functions = new Functions();

// Get POST data
$full_name = isset($_POST['full_name']) ? $functions->sanitize($_POST['full_name']) : '';
$phone = isset($_POST['phone']) ? $functions->sanitize($_POST['phone']) : '';
$country = isset($_POST['country']) ? $functions->sanitize($_POST['country']) : '';
$city = isset($_POST['city']) ? $functions->sanitize($_POST['city']) : '';
$address = isset($_POST['address']) ? $functions->sanitize($_POST['address']) : '';
$postal_code = isset($_POST['postal_code']) ? $functions->sanitize($_POST['postal_code']) : '';

// Validate required fields
if (empty($full_name)) {
    echo json_encode(['success' => false, 'message' => 'Full name is required']);
    exit();
}

try {
    // Update user profile
    $stmt = $functions->db->prepare("
        UPDATE users SET
            full_name = ?,
            phone = ?,
            country = ?,
            city = ?,
            address = ?,
            postal_code = ?,
            updated_at = NOW()
        WHERE id = ?
    ");

    $result = $stmt->execute([
        $full_name,
        $phone,
        $country,
        $city,
        $address,
        $postal_code,
        $user_id
    ]);

    if ($result) {
        // Log activity
        $functions->logActivity($user_id, 'profile_updated', 'Updated profile information');

        echo json_encode([
            'success' => true,
            'message' => 'Profile updated successfully',
            'data' => [
                'full_name' => $full_name,
                'phone' => $phone,
                'country' => $country,
                'city' => $city,
                'address' => $address,
                'postal_code' => $postal_code
            ]
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update profile']);
    }

} catch (Exception $e) {
    error_log("Profile update error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Failed to update profile. Please try again.']);
}
?>
