<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['status' => 401, 'error' => 'Unauthorized']);
    exit;
}

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

$pdo = new PDO("mysql:host=localhost;dbname=liongate;charset=utf8mb4", "root", "", [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

$userId = $_SESSION['user_id'];

// Sanitize inputs
$fullName = trim($_POST['name'] ?? '');
$phone    = trim($_POST['phone'] ?? '');
$country  = trim($_POST['country'] ?? '');

// Basic validation
$errors = [];
if (empty($fullName)) $errors[] = 'Full name is required.';
if (empty($phone))    $errors[] = 'Phone number is required.';
if (empty($country))  $errors[] = 'Country is required.';

if (!empty($errors)) {
    echo json_encode(['status' => 422, 'error' => implode(' ', $errors)]);
    exit;
}

try {
    $stmt = $pdo->prepare("UPDATE users SET full_name = :full_name, phone = :phone, country = :country WHERE id = :id");
    $stmt->execute([
        ':full_name' => $fullName,
        ':phone'     => $phone,
        ':country'   => $country,
        ':id'        => $userId
    ]);

    echo json_encode([
        'status'  => 200,
        'success' => 'Profile updated successfully!'
    ]);
} catch (Exception $e) {
    echo json_encode(['status' => 500, 'error' => 'Failed to update profile. Please try again.']);
}