<?php
require_once '../config.php';

$data = json_decode(file_get_contents("php://input"), true);

if (empty($data['user_id'])) {
    http_response_code(400);
    echo json_encode(["status" => "error", "message" => "user_id is required."]);
    exit();
}

$userId = intval($data['user_id']);
$points = isset($data['points']) ? intval($data['points']) : null;
$pointsQuiz = isset($data['points_quiz']) ? intval($data['points_quiz']) : null;
$pointsChallenges = isset($data['points_challenges']) ? intval($data['points_challenges']) : null;
$pointsReferrals = isset($data['points_referrals']) ? intval($data['points_referrals']) : null;
$pointsOther = isset($data['points_other']) ? intval($data['points_other']) : null;

try {
    $db = getDBConnection();

    // Self-healing columns check
    try {
        $db->exec("ALTER TABLE users ADD COLUMN points INT DEFAULT 0");
    } catch(Exception $e) {}
    try {
        $db->exec("ALTER TABLE users ADD COLUMN points_quiz INT DEFAULT 0");
    } catch(Exception $e) {}
    try {
        $db->exec("ALTER TABLE users ADD COLUMN points_challenges INT DEFAULT 0");
    } catch(Exception $e) {}
    try {
        $db->exec("ALTER TABLE users ADD COLUMN points_referrals INT DEFAULT 0");
    } catch(Exception $e) {}
    try {
        $db->exec("ALTER TABLE users ADD COLUMN points_other INT DEFAULT 0");
    } catch(Exception $e) {}

    $updates = [];
    $params = [];

    if ($points !== null) {
        $updates[] = "points = ?";
        $params[] = $points;
    }
    if ($pointsQuiz !== null) {
        $updates[] = "points_quiz = ?";
        $params[] = $pointsQuiz;
    }
    if ($pointsChallenges !== null) {
        $updates[] = "points_challenges = ?";
        $params[] = $pointsChallenges;
    }
    if ($pointsReferrals !== null) {
        $updates[] = "points_referrals = ?";
        $params[] = $pointsReferrals;
    }
    if ($pointsOther !== null) {
        $updates[] = "points_other = ?";
        $params[] = $pointsOther;
    }

    if (empty($updates)) {
        http_response_code(400);
        echo json_encode(["status" => "error", "message" => "No points metrics were provided for update."]);
        exit();
    }

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

    $stmt = $db->prepare($sql);
    $stmt->execute($params);

    // Fetch updated user data
    $stmt = $db->prepare("SELECT id, full_name, email, phone, avatar, last_profile_edit, points, points_quiz, points_challenges, points_referrals, points_other FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $updatedUser = $stmt->fetch();

    if (!$updatedUser) {
        http_response_code(404);
        echo json_encode(["status" => "error", "message" => "Account not found after update."]);
        exit();
    }

    // Fetch wallet info
    $stmt = $db->prepare("SELECT balance FROM wallets WHERE user_id = ?");
    $stmt->execute([$userId]);
    $wallet = $stmt->fetch();

    echo json_encode([
        "status" => "success",
        "message" => "Points successfully synchronized with database.",
        "user" => [
            "id" => intval($updatedUser['id']),
            "full_name" => $updatedUser['full_name'],
            "email" => $updatedUser['email'],
            "phone" => $updatedUser['phone'],
            "avatar" => $updatedUser['avatar'] ?? null,
            "last_profile_edit" => $updatedUser['last_profile_edit'],
            "balance" => floatval($wallet ? $wallet['balance'] : 0.00),
            "today_winnings" => getTodayWinnings($userId),
            "points" => intval($updatedUser['points']),
            "points_quiz" => intval($updatedUser['points_quiz']),
            "points_challenges" => intval($updatedUser['points_challenges']),
            "points_referrals" => intval($updatedUser['points_referrals']),
            "points_other" => intval($updatedUser['points_other'])
        ]
    ]);

} catch(Exception $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Failed to update user points: " . $e->getMessage()]);
}
?>
