<?php
require_once '../config.php';
require_once '../middleware.php';

date_default_timezone_set('Asia/Kolkata');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the encrypted payload
    $encrypted_payload = file_get_contents('php://input');
    if (empty($encrypted_payload)) {
        sendResponse(400, 'Empty request body');
    }

    // Decrypt the payload
    $data = decryptRequestPayload($encrypted_payload);
    if (!$data) {
        sendResponse(400, 'Invalid request body');
    }

    $device_id = $_SERVER['HTTP_DEVICE_ID'] ?? '';
    $session_token = $_SERVER['HTTP_SESSION_TOKEN'] ?? '';

    $user_id = $data['user_id'];
    $earned_coins = (int)$data['earned_coins']; // Ensure earned_coins is an integer
    $by_task = $data['by_task'];
    $created_at = $data['created_at'] ?? date('Y-m-d H:i:s');

    authenticateSession($user_id, $device_id, $session_token);
    rateLimit($user_id); // Rate limit after session is confirmed valid
    $new_session_token = generateNewSessionToken($user_id, $device_id);

    $conn = getDbConnection();

    $response_data = ['show_ad' => true, 'total_coins' => 0]; // Initialize with total_coins

    // Fetch app settings for website task and referral rewards
    $stmt_settings = $conn->prepare("SELECT website_task_enabled, referral_coin_threshold, referrer_coins, referred_coins, task_limits_enabled, claim_timer FROM app_settings WHERE id = 1");
    if (!$stmt_settings) {
        sendResponse(500, 'Database query preparation failed for app_settings: ' . $conn->error);
    }
    $stmt_settings->execute();
    $result_settings = $stmt_settings->get_result();
    $settings = $result_settings->fetch_assoc();
    $stmt_settings->close();

    // Handle claim_timer randomization when show_ad is true
    if ($response_data['show_ad']) {
        $claim_timer = $settings['claim_timer'];
        if (strpos($claim_timer, '-') !== false) {
            list($min, $max) = explode('-', $claim_timer);
            $claim_timer = rand((int)$min, (int)$max);
        }
        $response_data['claim_timer'] = $claim_timer;
    }

    // Check for website task availability
    if ($settings['website_task_enabled']) {
        $stmt_website = $conn->prepare("SELECT id, web_url, timer FROM website_visit_tasks ORDER BY RAND() LIMIT 1");
        if (!$stmt_website) {
            sendResponse(500, 'Database query preparation failed for website_visit_tasks: ' . $conn->error);
        }
        $stmt_website->execute();
        $result_website = $stmt_website->get_result();
        if ($result_website->num_rows > 0) {
            $task = $result_website->fetch_assoc();
            $response_data['show_ad'] = false;
            $response_data['website_task'] = [
                'id' => $task['id'],
                'url' => $task['web_url'],
                'timer' => $task['timer']
            ];
        }
        $stmt_website->close();
    }

    // --- Task Limits Check (without updating usage) ---
    $task_limits_data = ['enabled' => false, 'remaining_limit' => null, 'daily_limit' => null];
    
    if ($settings['task_limits_enabled'] && !empty($by_task)) {
        // Only allow the four specified task types
        $allowed_task_types = ['big_vs_small', 'alphabet_find', 'sound_match', 'math_fun'];
        if (in_array($by_task, $allowed_task_types)) {
            $task_limits_data['enabled'] = true;
            
            // Get the daily limit for this task type
            $stmt_limit = $conn->prepare("SELECT daily_limit FROM task_limits WHERE task_type = ? AND is_enabled = 1");
            if ($stmt_limit) {
                $stmt_limit->bind_param("s", $by_task);
                $stmt_limit->execute();
                $result_limit = $stmt_limit->get_result();
                $limit_data = $result_limit->fetch_assoc();
                $stmt_limit->close();
                
                if ($limit_data) {
                    $daily_limit = $limit_data['daily_limit'];
                    $today = date('Y-m-d');
                    $stmt_usage = $conn->prepare("SELECT used_count, user_daily_limit FROM user_task_usage WHERE user_id = ? AND task_type = ? AND usage_date = ?");
                    if ($stmt_usage) {
                        $stmt_usage->bind_param("iss", $user_id, $by_task, $today);
                        $stmt_usage->execute();
                        $result_usage = $stmt_usage->get_result();
                        $usage_data = $result_usage->fetch_assoc();
                        $stmt_usage->close();
                        
                        $current_usage = $usage_data ? $usage_data['used_count'] : 0;
                        $user_daily_limit = $usage_data ? $usage_data['user_daily_limit'] : null;
                        // If no user_daily_limit, and daily_limit is a range, pick and store
                        if ($user_daily_limit === null) {
                            if (strpos($daily_limit, '-') !== false) {
                                list($min, $max) = explode('-', $daily_limit);
                                $user_daily_limit = rand((int)$min, (int)$max);
                            } else {
                                $user_daily_limit = (int)$daily_limit;
                            }
                            // Insert or update user_task_usage with user_daily_limit if not exists
                            if ($usage_data) {
                                $stmt_update = $conn->prepare("UPDATE user_task_usage SET user_daily_limit = ? WHERE user_id = ? AND task_type = ? AND usage_date = ?");
                                $stmt_update->bind_param("iiss", $user_daily_limit, $user_id, $by_task, $today);
                                $stmt_update->execute();
                                $stmt_update->close();
                            } else {
                                $stmt_insert = $conn->prepare("INSERT INTO user_task_usage (user_id, task_type, usage_date, used_count, user_daily_limit) VALUES (?, ?, ?, 0, ?)");
                                $stmt_insert->bind_param("issi", $user_id, $by_task, $today, $user_daily_limit);
                                $stmt_insert->execute();
                                $stmt_insert->close();
                            }
                        }
                        $task_limits_data['daily_limit'] = $user_daily_limit;
                        $remaining_limit = $user_daily_limit - $current_usage;
                        
                        // Check if user has reached the limit
                        if ($remaining_limit <= 0) {
                            $new_session_token = generateNewSessionToken($user_id, $device_id);
                            sendResponse(400, "Daily limit reached for task type: $by_task. Limit: $user_daily_limit per day.", [], $new_session_token);
                        }
                        
                        // Calculate remaining limit (no check for limit reached since we're not updating)
                        $task_limits_data['remaining_limit'] = $remaining_limit;
                    }
                }
            }
        }
    }
    
    // Add task limits data to response
    $response_data['task_limits'] = $task_limits_data;

    // Get current user coins (without updating)
    $stmt_get_coins = $conn->prepare("SELECT coins FROM users WHERE id = ?");
    if (!$stmt_get_coins) {
        sendResponse(500, 'Database query preparation failed for fetching user coins: ' . $conn->error);
    }
    $stmt_get_coins->bind_param("i", $user_id);
    $stmt_get_coins->execute();
    $result_get_coins = $stmt_get_coins->get_result();
    $user_current_data = $result_get_coins->fetch_assoc();
    $stmt_get_coins->close();

    if ($user_current_data) {
        $response_data['total_coins'] = $user_current_data['coins'];
    } else {
        sendResponse(500, 'User not found');
    }

    // Initialize referral reward data (no processing here)
    $response_data['referral_reward'] = ['awarded' => false];

    $conn->close();
    sendResponse(200, 'Task completed', $response_data, $new_session_token);
}
?>