<?php
session_start();
header('Content-Type: application/json');

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

// Database connection
try {
    $pdo = new PDO("mysql:host=localhost;dbname=liongate;charset=utf8mb4", "root", "", [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    echo json_encode(['status' => 500, 'error' => 'Database connection failed']);
    exit;
}

// Get POST data
$name = isset($_POST['name']) ? trim($_POST['name']) : '';
$phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
$country = isset($_POST['country']) ? trim($_POST['country']) : '';

// Validation
$errors = [];

if (empty($name) || strlen($name) < 2) {
    $errors[] = 'Full name is required (minimum 2 characters)';
}

if (empty($phone) || strlen($phone) < 5) {
    $errors[] = 'Valid phone number is required';
}

if (empty($country)) {
    $errors[] = 'Please select a country';
}

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

// Sanitize inputs
$name = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
$phone = htmlspecialchars($phone, ENT_QUOTES, 'UTF-8');
$country = htmlspecialchars($country, ENT_QUOTES, 'UTF-8');

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

    if ($stmt->rowCount() >= 0) {
        echo json_encode(['status' => 200, 'success' => 'Profile updated successfully']);
    } else {
        echo json_encode(['status' => 400, 'error' => 'No changes made']);
    }
} catch (PDOException $e) {
    echo json_encode(['status' => 500, 'error' => 'Failed to update profile']);
}
?>