<?php
require_once '../../config/database.php';
require_once '../../includes/functions.php';

// Initialize database connection
if (!isset($conn)) {
    $conn = getConnection(); // Try function first
}
if (!isset($conn)) {
    // If still not set, create new connection
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        die(json_encode(['success' => false, 'message' => 'Database connection failed']));
    }
}

// Check admin authentication
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$adminId = $_SESSION['admin_id'];

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

$submissionId = $input['submission_id'] ?? 0;
$taskId = $input['task_id'] ?? 0;
$userId = $input['user_id'] ?? 0;
$reward = $input['reward'] ?? 0;
$category = $input['category'] ?? '';

// Validate input
if (!$submissionId || !$taskId || !$userId || !$reward) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit();
}

try {
    $conn->begin_transaction();

    // 1. Update task_completions - mark as approved
    $stmt = $conn->prepare("
        UPDATE task_completions 
        SET status = 'approved',
            reviewed_at = NOW(),
            reviewer_id = ?
        WHERE id = ? 
        AND status = 'pending'
    ");
    $stmt->bind_param("ii", $adminId, $submissionId);
    $stmt->execute();

    if ($stmt->affected_rows == 0) {
        throw new Exception('Task already processed or not found');
    }

    // 2. Create or update task_wallet for this category
    $taskName = $category . ' Tasks';
    
    // Check if wallet exists for this specific task
    $stmt = $conn->prepare("
        SELECT id, balance 
        FROM task_wallets 
        WHERE user_id = ? AND task_id = ?
    ");
    $stmt->bind_param("ii", $userId, $taskId);
    $stmt->execute();
    $wallet = $stmt->get_result()->fetch_assoc();

    if ($wallet) {
        // Update existing wallet
        $newBalance = $wallet['balance'] + $reward;
        $stmt = $conn->prepare("
            UPDATE task_wallets 
            SET balance = ?, task_name = ? 
            WHERE id = ?
        ");
        $stmt->bind_param("dsi", $newBalance, $taskName, $wallet['id']);
        $stmt->execute();
    } else {
        // Create new wallet
        $stmt = $conn->prepare("
            INSERT INTO task_wallets (user_id, task_id, task_name, balance) 
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("iisd", $userId, $taskId, $taskName, $reward);
        $stmt->execute();
    }

    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Task approved and reward credited'
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>