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

ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// Get raw POST data (JSON)
$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['email']) || !isset($input['task_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Email and task_id are required']);
    exit();
}

$email   = $input['email'];
$task_id = $input['task_id'];

// Define available tasks + rewards
$tasks = [
    'twitter'   => ['reward' => 0.01, 'type' => 'social'],
    'youtube'   => ['reward' => 0.01, 'type' => 'social'],
    'telegram'  => ['reward' => 0.01, 'type' => 'social'],
    'invite5'   => ['reward' => 0.1,  'type' => 'invite', 'required' => 5],
    'invite10'  => ['reward' => 0.2,  'type' => 'invite', 'required' => 10],
    'invite20'  => ['reward' => 1,    'type' => 'invite', 'required' => 20],
    'invite50'  => ['reward' => 1.5,  'type' => 'invite', 'required' => 50],
    'invite100' => ['reward' => 2,    'type' => 'invite', 'required' => 100],
];

// Validate task
if (!isset($tasks[$task_id])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid task']);
    exit();
}

$task = $tasks[$task_id];

// 1. Check if task already completed
$stmt = $conn->prepare("SELECT 1 FROM completed_tasks WHERE email = ? AND task_id = ?");
$stmt->bind_param("ss", $email, $task_id);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    echo json_encode(['status' => 'error', 'message' => 'Task already completed']);
    $stmt->close();
    $conn->close();
    exit();
}
$stmt->close();

// 2. Special handling for invite tasks
if ($task['type'] === 'invite') {
    $required = $task['required'];

    // Count successful referrals (assuming you have a referrals table)
    $refQuery = $conn->prepare("SELECT COUNT(*) FROM users WHERE referred_by = ?");
    $refQuery->bind_param("s", $email);
    $refQuery->execute();
    $refQuery->bind_result($refCount);
    $refQuery->fetch();
    $refQuery->close();

    if ($refCount < $required) {
        echo json_encode(['status' => 'error', 'message' => "You need at least $required referrals. Current: $refCount"]);
        $conn->close();
        exit();
    }
}

// 3. Award reward: update task_balance
$reward = $task['reward'];
$update = $conn->prepare("UPDATE users SET task_balance = task_balance + ? WHERE email = ?");
$update->bind_param("ds", $reward, $email);

if (!$update->execute()) {
    echo json_encode(['status' => 'error', 'message' => 'Failed to update balance']);
    $update->close();
    $conn->close();
    exit();
}
$update->close();

// 4. Mark task as completed
$insert = $conn->prepare("INSERT INTO completed_tasks (email, task_id) VALUES (?, ?)");
$insert->bind_param("ss", $email, $task_id);

if ($insert->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Task completed and reward added']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to log completed task']);
}

$insert->close();
$conn->close();
?>