<?php
// Update user details API (name, email, age, phone, gender)
header('Content-Type: application/json; charset=utf-8');
session_start();

// Check authentication
if (empty($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

// Load database config with short retry loop (FTP/cPanel may be syncing files)
$config_file = __DIR__ . '/db_config.php';
$included = false;
for ($i=0; $i<5; $i++) {
    if (file_exists($config_file) && is_readable($config_file)) { include $config_file; $included = true; break; }
    usleep(200000);
}
if (!$included) {
    error_log('api_update_user_details.php: db_config.php not found');
    echo json_encode(['success' => false, 'message' => 'Server configuration not ready']);
    exit;
}

// Get POST data
$user_id = (int)($_POST['user_id'] ?? 0);
$email = $_POST['email'] ?? '';
$name = $_POST['name'] ?? '';
$age = (int)($_POST['age'] ?? 0);
$phone = $_POST['phone'] ?? '';
$gender = $_POST['gender'] ?? '';

// Validate
if ($user_id <= 0 || empty($email)) {
    echo json_encode(['success' => false, 'message' => 'Invalid user ID or email']);
    exit;
}

// Check if current user is admin or editing own profile
$is_admin = !empty($_SESSION['is_admin']);
$is_own_profile = ($_SESSION['user_id'] == $user_id);

if (!$is_admin && !$is_own_profile) {
    echo json_encode(['success' => false, 'message' => 'Permission denied']);
    exit;
}

// Update database
if (isset($conn) && is_object($conn) && !$conn->connect_error) {
    $query = "UPDATE users SET email = ?, name = ?, age = ?, phone = ?, gender = ? WHERE id = ?";
    
    if ($stmt = $conn->prepare($query)) {
        // types: email(s), name(s), age(i), phone(s), gender(s), user_id(i)
        $stmt->bind_param('ssissi', $email, $name, $age, $phone, $gender, $user_id);
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'User updated']);
        } else {
            error_log('api_update_user_details.php: execute failed: ' . $conn->error);
            echo json_encode(['success' => false, 'message' => 'Update failed']);
        }
        $stmt->close();
    } else {
        error_log('api_update_user_details.php: prepare failed: ' . $conn->error);
        echo json_encode(['success' => false, 'message' => 'Server error preparing statement']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
}
exit;
?>
