<?php
/**
 * Profile Update API
 * Handle user profile updates
 */

require_once __DIR__ . '/../config/session.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/helpers.php';

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

// Check if user is logged in
if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode([
        'success' => false,
        'message' => 'Not authenticated'
    ]);
    exit();
}

$userId = getCurrentUserId();
$dbHelper = new DBHelper($conn);

// Get POST data
$data = [
    'first_name' => htmlspecialchars($_POST['first_name'] ?? ''),
    'last_name' => htmlspecialchars($_POST['last_name'] ?? ''),
    'phone' => htmlspecialchars($_POST['phone'] ?? ''),
    'address' => htmlspecialchars($_POST['address'] ?? ''),
    'city' => htmlspecialchars($_POST['city'] ?? ''),
    'country' => htmlspecialchars($_POST['country'] ?? ''),
    'postal_code' => htmlspecialchars($_POST['postal_code'] ?? '')
];

// Validate required fields
if (empty($data['first_name']) || empty($data['last_name'])) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'First name and last name are required'
    ]);
    exit();
}

// Update user profile
try {
    if ($dbHelper->updateUserProfile($userId, $data)) {
        // Update session data
        if (session_status() === PHP_SESSION_ACTIVE) {
            $_SESSION['user_data']['first_name'] = $data['first_name'];
            $_SESSION['user_data']['last_name'] = $data['last_name'];
        }

        echo json_encode([
            'success' => true,
            'message' => 'Profile updated successfully'
        ]);
    } else {
        throw new Exception('Failed to update profile');
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error updating profile: ' . $e->getMessage()
    ]);
}
?>
