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

date_default_timezone_set('Asia/Kolkata');

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

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method !== 'POST') {
    sendResponse(405, 'Method not allowed');
}

// 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');
}

$user_id = $data['user_id'] ?? 0;
$task_type = $data['task_type'] ?? null;

if ($user_id <= 0) {
    sendResponse(400, 'Invalid user_id');
}

authenticateSession($user_id, $device_id, $session_token);
rateLimit($user_id);
$new_session_token = generateNewSessionToken($user_id, $device_id);

$conn = getDbConnection();

// Check if task limits are enabled globally
$stmt_settings = $conn->prepare("SELECT task_limits_enabled, earning_mode, vpn_allowed, native_ad_load_refresh_count FROM app_settings WHERE id = 1");
$stmt_settings->execute();
$result_settings = $stmt_settings->get_result();
$settings = $result_settings->fetch_assoc();
$stmt_settings->close();

$task_limits_enabled = $settings['task_limits_enabled'] ?? false;
$earning_mode = $settings['earning_mode'] ?? false;
$vpn_allowed = $settings['vpn_allowed'] ?? false;
$native_ad_load_refresh_count = isset($settings['native_ad_load_refresh_count']) ? (int)$settings['native_ad_load_refresh_count'] : 0;

// Get user's coins
$stmt_user = $conn->prepare("SELECT coins FROM users WHERE id = ?");
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$result_user = $stmt_user->get_result();
$user_data = $result_user->fetch_assoc();
$stmt_user->close();

$user_coins = $user_data ? $user_data['coins'] : 0;

$response_data = [
    'enabled' => $task_limits_enabled,
    'earning_mode' => $earning_mode,
    'vpn_allowed' => $vpn_allowed,
    'native_ad_load_refresh_count' => $native_ad_load_refresh_count,
    'coins' => $user_coins,
    'limits' => []
];
$ad_index_list = [];

if ($task_limits_enabled) {
    $today = date('Y-m-d');

    if ($task_type) {
        $allowed_task_types = ['word_puzzle', 'alphabet_puzzle', 'count_images', 'big_vs_small'];
        if (!in_array($task_type, $allowed_task_types)) {
            sendResponse(400, 'Invalid task_type');
        }

        $stmt_limit = $conn->prepare("SELECT task_type, daily_limit, ad_index, important_ad_type FROM task_limits WHERE task_type = ? AND is_enabled = 1");
        $stmt_limit->bind_param("s", $task_type);
        $stmt_limit->execute();
        $result_limit = $stmt_limit->get_result();
        $limit_data = $result_limit->fetch_assoc();
        $stmt_limit->close();
        
        if ($limit_data) {
            // Reward coins
            $stmt_reward = $conn->prepare("SELECT reward_coins FROM tasks WHERE task_type = ? AND is_enabled = 1");
            $stmt_reward->bind_param("s", $task_type);
            $stmt_reward->execute();
            $result_reward = $stmt_reward->get_result();
            $reward_row = $result_reward->fetch_assoc();
            $stmt_reward->close();
            $reward_coins = $reward_row ? $reward_row['reward_coins'] : null;
            if ($reward_coins !== null && strpos($reward_coins, '-') !== false) {
                list($min, $max) = explode('-', $reward_coins);
                $reward_coins = rand((int)$min, (int)$max);
            } elseif ($reward_coins !== null) {
                $reward_coins = (int)$reward_coins;
            }

            // User usage (daily_limit + ad_index dono)
            $stmt_usage = $conn->prepare("SELECT used_count, user_daily_limit, ad_index FROM user_task_usage WHERE user_id = ? AND task_type = ? AND usage_date = ?");
            $stmt_usage->bind_param("iss", $user_id, $task_type, $today);
            $stmt_usage->execute();
            $result_usage = $stmt_usage->get_result();
            $usage_data = $result_usage->fetch_assoc();
            $stmt_usage->close();
            
            $used_count = $usage_data ? $usage_data['used_count'] : 0;
            $user_daily_limit = $usage_data ? $usage_data['user_daily_limit'] : null;
            $user_ad_index = $usage_data ? $usage_data['ad_index'] : null;

            if ($user_daily_limit === null) {
                $daily_limit = $limit_data['daily_limit'];
                if (is_string($daily_limit) && 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;
                }
            }

            if ($user_ad_index === null) {
                $ad_index = $limit_data['ad_index'];
                if ($ad_index !== null && is_string($ad_index) && strpos($ad_index, '-') !== false) {
                    list($min, $max) = explode('-', $ad_index);
                    $user_ad_index = rand((int)$min, (int)$max);
                } elseif ($ad_index !== null) {
                    $user_ad_index = (int)$ad_index;
                } else {
                    $user_ad_index = null;
                }
            }

            // Insert / Update user_task_usage
            if ($usage_data) {
                $stmt_update = $conn->prepare("UPDATE user_task_usage SET user_daily_limit = ?, ad_index = ? WHERE user_id = ? AND task_type = ? AND usage_date = ?");
                $stmt_update->bind_param("iiiss", $user_daily_limit, $user_ad_index, $user_id, $task_type, $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, ad_index) VALUES (?, ?, ?, 0, ?, ?)");
                $stmt_insert->bind_param("issii", $user_id, $task_type, $today, $user_daily_limit, $user_ad_index);
                $stmt_insert->execute();
                $stmt_insert->close();
            }

            $remaining_limit = max(0, $user_daily_limit - $used_count);
            $ad_index_list[] = $user_ad_index;

            $response_data['limits'][] = [
                'task_type' => $limit_data['task_type'],
                'daily_limit' => $user_daily_limit,
                'used_count' => $used_count,
                'remaining_limit' => $remaining_limit,
                'reward_coins' => $reward_coins,
                'ad_index' => $user_ad_index,
                'important_ad_type' => $limit_data['important_ad_type'] ?? null
            ];
        }
    } else {
        // All task types
        $stmt_limits = $conn->prepare("SELECT task_type, daily_limit, ad_index, important_ad_type FROM task_limits WHERE is_enabled = 1 AND task_type IN ('Number_Puzzle', 'Finder_Puzzle', 'Sound_Match') ORDER BY task_type");
        $stmt_limits->execute();
        $result_limits = $stmt_limits->get_result();
        $stmt_limits->close();
        
        while ($limit_data = $result_limits->fetch_assoc()) {
            $current_task_type = $limit_data['task_type'];

            // Reward coins
            $stmt_reward = $conn->prepare("SELECT reward_coins FROM tasks WHERE task_type = ? AND is_enabled = 1");
            $stmt_reward->bind_param("s", $current_task_type);
            $stmt_reward->execute();
            $result_reward = $stmt_reward->get_result();
            $reward_row = $result_reward->fetch_assoc();
            $stmt_reward->close();
            $reward_coins = $reward_row ? $reward_row['reward_coins'] : null;
            if ($reward_coins !== null && strpos($reward_coins, '-') !== false) {
                list($min, $max) = explode('-', $reward_coins);
                $reward_coins = rand((int)$min, (int)$max);
            } elseif ($reward_coins !== null) {
                $reward_coins = (int)$reward_coins;
            }

            // Usage (daily_limit + ad_index dono)
            $stmt_usage = $conn->prepare("SELECT used_count, user_daily_limit, ad_index FROM user_task_usage WHERE user_id = ? AND task_type = ? AND usage_date = ?");
            $stmt_usage->bind_param("iss", $user_id, $current_task_type, $today);
            $stmt_usage->execute();
            $result_usage = $stmt_usage->get_result();
            $usage_data = $result_usage->fetch_assoc();
            $stmt_usage->close();

            $used_count = $usage_data ? $usage_data['used_count'] : 0;
            $user_daily_limit = $usage_data ? $usage_data['user_daily_limit'] : null;
            $user_ad_index = $usage_data ? $usage_data['ad_index'] : null;

            if ($user_daily_limit === null) {
                $daily_limit = $limit_data['daily_limit'];
                if (is_string($daily_limit) && 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;
                }
            }

            if ($user_ad_index === null) {
                $ad_index = $limit_data['ad_index'];
                if ($ad_index !== null && is_string($ad_index) && strpos($ad_index, '-') !== false) {
                    list($min, $max) = explode('-', $ad_index);
                    $user_ad_index = rand((int)$min, (int)$max);
                } elseif ($ad_index !== null) {
                    $user_ad_index = (int)$ad_index;
                } else {
                    $user_ad_index = null;
                }
            }

            if ($usage_data) {
                $stmt_update = $conn->prepare("UPDATE user_task_usage SET user_daily_limit = ?, ad_index = ? WHERE user_id = ? AND task_type = ? AND usage_date = ?");
                $stmt_update->bind_param("iiiss", $user_daily_limit, $user_ad_index, $user_id, $current_task_type, $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, ad_index) VALUES (?, ?, ?, 0, ?, ?)");
                $stmt_insert->bind_param("issii", $user_id, $current_task_type, $today, $user_daily_limit, $user_ad_index);
                $stmt_insert->execute();
                $stmt_insert->close();
            }

            $remaining_limit = max(0, $user_daily_limit - $used_count);
            $ad_index_list[] = $user_ad_index;

            $response_data['limits'][] = [
                'task_type' => $current_task_type,
                'daily_limit' => $user_daily_limit,
                'used_count' => $used_count,
                'remaining_limit' => $remaining_limit,
                'reward_coins' => $reward_coins,
                'ad_index' => $user_ad_index,
                'important_ad_type' => $limit_data['important_ad_type'] ?? null
            ];
        }
    }
}
$response_data['ad_index'] = $ad_index_list;

$conn->close();

sendResponse(200, 'Task limits fetched', $response_data, $new_session_token);
?>