<?php
require_once 'db.php';
session_start();
$user_id = $_SESSION['user_id'];
$task_id = $_POST['task_id'];

// Get task
$sql = "SELECT reward FROM tasks WHERE id = ? AND user_id = ? AND status = 'pending'";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $task_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 1) {
    $task = $result->fetch_assoc();
    $reward = $task['reward'];

    // Mark complete
    $conn->query("UPDATE tasks SET status = 'completed', completed_at = NOW() WHERE id = $task_id");

    // Update balance
    $conn->query("UPDATE users SET balance = balance + $reward WHERE id = $user_id");

    echo json_encode(['success' => true, 'reward' => $reward]);
} else {
    echo json_encode(['success' => false, 'message' => 'Task not valid']);
}
?>
