<?php
require_once 'db.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
$userId = $_GET['id'] ?? $input['id'] ?? 0;

if (!$userId) {
    http_response_code(400);
    echo json_encode(['message' => 'User ID required']);
    exit;
}

if ($method === 'GET') {
    $stmt = $mysqli->prepare("SELECT id, name, email, username, role, streak_count, birthday, gender, social_networks FROM users WHERE id = ?");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($user = $result->fetch_assoc()) {
        echo json_encode($user);
    } else {
        http_response_code(404);
        echo json_encode(['message' => 'User not found']);
    }
} elseif ($method === 'POST' || $method === 'PUT') {
    // Update profile
    // Fields to update: username, email, password, birthday, gender, social_networks
    
    // First fetch current data
    $stmt = $mysqli->prepare("SELECT password_hash FROM users WHERE id = ?");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $current = $stmt->get_result()->fetch_assoc();
    
    if (!$current) {
        http_response_code(404);
        echo json_encode(['message' => 'User not found']);
        exit;
    }

    $username = $input['username'] ?? null;
    $email = $input['email'] ?? null;
    $password = $input['password'] ?? null;
    $birthday = $input['birthday'] ?? null;
    $gender = $input['gender'] ?? null;
    $socials = isset($input['social_networks']) ? json_encode($input['social_networks']) : null;

    $updates = [];
    $types = '';
    $params = [];

    if ($username) { $updates[] = "username = ?"; $types .= 's'; $params[] = $username; }
    if ($email) { $updates[] = "email = ?"; $types .= 's'; $params[] = $email; }
    if ($password) { $updates[] = "password_hash = ?"; $types .= 's'; $params[] = password_hash($password, PASSWORD_DEFAULT); }
    if ($birthday) { $updates[] = "birthday = ?"; $types .= 's'; $params[] = $birthday; }
    if ($gender) { $updates[] = "gender = ?"; $types .= 's'; $params[] = $gender; }
    if ($socials) { $updates[] = "social_networks = ?"; $types .= 's'; $params[] = $socials; }

    if (empty($updates)) {
        echo json_encode(['message' => 'No changes']);
        exit;
    }

    $sql = "UPDATE users SET " . implode(', ', $updates) . " WHERE id = ?";
    $types .= 'i';
    $params[] = $userId;

    $updateStmt = $mysqli->prepare($sql);
    $updateStmt->bind_param($types, ...$params);

    if ($updateStmt->execute()) {
        echo json_encode(['message' => 'Profile updated successfully']);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Update failed: ' . $mysqli->error]);
    }
}
?>
