<?php
session_start();
require_once __DIR__ . '/auth/db.php';

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

if (!isset($_SESSION['email'])) {
    echo json_encode(["eligible" => false, "completed" => false, "error" => "not_logged_in"]);
    exit;
}

$email = $_SESSION['email'];
$milestone = intval($_GET['milestone'] ?? 0);

// Step 1: Check if task already completed
$task_name = "invite_$milestone";
$check = $conn->prepare("SELECT 1 FROM completed_tasks WHERE email=? AND task_id=?");
$check->bind_param("ss", $email, $task_name);
$check->execute();
$check->bind_result($found);
$isCompleted = $check->fetch();
$check->close();

if ($isCompleted) {
    echo json_encode(["completed" => true, "eligible" => false]);
    exit;
}

// Step 2: Count referrals
$query = $conn->prepare("SELECT COUNT(*) FROM users WHERE referred_by=?");
$query->bind_param("s", $email);
$query->execute();
$query->bind_result($totalReferrals);
$query->fetch();
$query->close();

// Step 3: Required referrals for each milestone
$requirements = [
    5 => 5,
    10 => 10,
    20 => 20,
    50 => 50,
    100 => 100
];

$needed = $requirements[$milestone] ?? 0;

if ($needed > 0 && $totalReferrals >= $needed) {
    echo json_encode([
        "completed" => false, 
        "eligible" => true, 
        "current" => $totalReferrals,
        "needed" => $needed
    ]);
} else {
    echo json_encode([
        "completed" => false, 
        "eligible" => false, 
        "current" => $totalReferrals, 
        "needed" => $needed
    ]);
}
?>