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

header('Content-Type: application/json');
ini_set('display_errors', 1);
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['status' => 'error', 'message' => 'Only POST allowed']);
    exit();
}

// Read JSON input
$input = json_decode(file_get_contents('php://input'), true);
$task_id = isset($input['task_id']) ? trim($input['task_id']) : '';

if (empty($task_id)) {
    echo json_encode(['status' => 'error', 'message' => 'task_id is required']);
    exit();
}

// Check session
if (!isset($_SESSION['email'])) {
    echo json_encode(['status' => 'error', 'message' => 'User not logged in']);
    exit();
}

$email = $_SESSION['email'];

// Normalize task_id
if (preg_match('/^(?:invite\s*)?(\d{1,3})$/i', $task_id, $m)) {
    $task_id = 'invite' . $m[1];
}

// Define milestones
$milestones = [
    'invite5'   => ['reward' => 0.1,  'required' => 5],
    'invite10'  => ['reward' => 0.2,  'required' => 10],
    'invite20'  => ['reward' => 1.0,  'required' => 20],
    'invite50'  => ['reward' => 1.5,  'required' => 50],
    'invite100' => ['reward' => 2.0,  'required' => 100],
];

if (!isset($milestones[$task_id])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid milestone']);
    exit();
}

$task = $milestones[$task_id];

// Check if already claimed
$chk = $conn->prepare("SELECT 1 FROM completed_tasks WHERE email = ? AND task_id = ?");
$chk->bind_param("ss", $email, $task_id);
$chk->execute();
$chk->bind_result($found);
$alreadyClaimed = $chk->fetch();
$chk->close();

if ($alreadyClaimed) {
    echo json_encode(['status' => 'error', 'message' => 'Milestone already claimed']);
    exit();
}

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

if ($totalReferrals < $task['required']) {
    $remaining = $task['required'] - $totalReferrals;
    echo json_encode([
        'status' => 'error',
        'message' => "Need {$task['required']} referrals. You have $totalReferrals (need $remaining more)."
    ]);
    exit();
}

// Claim reward
$conn->begin_transaction();

try {
    // Update balance
    $upd = $conn->prepare("UPDATE users SET task_balance = task_balance + ? WHERE email = ?");
    $upd->bind_param("ds", $task['reward'], $email);
    $upd->execute();
    $upd->close();

    // Mark as completed
    $ins = $conn->prepare("INSERT INTO completed_tasks (user_email, task_name, completed_at) VALUES (?, ?, NOW())");
    $ins->bind_param("ss", $email, $task_id);
    $ins->execute();
    $ins->close();

    $conn->commit();

    echo json_encode([
        'status' => 'success',
        'message' => "Claimed {$task_id}! Reward: {$task['reward']} GBL added.",
        'total_referrals' => $totalReferrals
    ]);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $e->getMessage()]);
}

$conn->close();
?>