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

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

// Get request method
$method = $_SERVER['REQUEST_METHOD'];

// Get headers for authentication
$device_id = isset($_SERVER['HTTP_DEVICE_ID']) ? $_SERVER['HTTP_DEVICE_ID'] : '';
$session_token = isset($_SERVER['HTTP_SESSION_TOKEN']) ? $_SERVER['HTTP_SESSION_TOKEN'] : '';

if ($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');
    }

    $user_id = isset($data['user_id']) ? (int)$data['user_id'] : 0;
    $action = isset($data['action']) ? $data['action'] : '';

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

    // Authenticate the user session
    authenticateSession($user_id, $device_id, $session_token);
    rateLimit($user_id);

    $conn = getDbConnection();

    if ($action === 'list_categories') {
        // Fetch all categories
        $query = "SELECT id, category_name, category_image_url FROM redeem_options_categories";
        $result = $conn->query($query);

        $categories = [];
        while ($row = $result->fetch_assoc()) {
            $categories[] = [
                'category_id' => $row['id'],
                'category_name' => $row['category_name'],
                'category_image_url' => $row['category_image_url']
            ];
        }

        // Ensure "Gift Card & Payments" is the first category
        usort($categories, function($a, $b) {
            if ($a['category_name'] === 'Gift Card & Payments') return -1;
            if ($b['category_name'] === 'Gift Card & Payments') return 1;
            return strcmp($a['category_name'], $b['category_name']);
        });

        $new_session_token = generateNewSessionToken($user_id, $device_id);
        sendResponse(200, 'Categories fetched', ['categories' => $categories], $new_session_token);
    } elseif ($action === 'list_subcategories') {
        $category_id = isset($data['category_id']) ? (int)$data['category_id'] : 0;
        if ($category_id <= 0) {
            sendResponse(400, 'Invalid category ID');
        }

        // Check if the category is Upi Transfer
        $stmt = $conn->prepare("SELECT category_name FROM redeem_options_categories WHERE id = ?");
        $stmt->bind_param("i", $category_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $cat_row = $result->fetch_assoc();
        $stmt->close();
        $category_name = $cat_row ? strtolower(trim($cat_row['category_name'])) : '';
        if ($category_name === 'upi transfer') {
            // Check upi_transfer_enable in app_settings
            $stmt = $conn->prepare("SELECT upi_transfer_enable FROM app_settings WHERE id = 1");
            $stmt->execute();
            $result = $stmt->get_result();
            $settings = $result->fetch_assoc();
            $stmt->close();
            if (empty($settings) || (int)$settings['upi_transfer_enable'] !== 1) {
                sendResponse(400, 'Upi Transfer mode come in Next update !');
            }
        }

        // Check if filtering for Google Play subcategories
        $filter_google_play = false;
        if (isset($data['sub_category_name']) && $data['sub_category_name'] === 'Google Play') {
            $filter_google_play = true;
        }

        // Fetch subcategories for the selected category
        $query = "SELECT id, sub_category_name, sub_category_image_url, coins, cash, is_enabled 
                  FROM redeem_options_subcategories 
                  WHERE category_id = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("i", $category_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $subcategories = [];
        while ($row = $result->fetch_assoc()) {
            if ($filter_google_play && !str_contains($row['sub_category_name'], 'Google Play')) {
                continue;
            }
            $subcategories[] = [
                'id' => $row['id'],
                'sub_category_name' => $row['sub_category_name'],
                'sub_category_image_url' => $row['sub_category_image_url'],
                'coins' => $row['coins'],
                'cash' => $row['cash'],
                'is_enabled' => $row['is_enabled']
            ];
        }

        $stmt->close();
        $new_session_token = generateNewSessionToken($user_id, $device_id);
        sendResponse(200, 'Subcategories fetched', ['subcategories' => $subcategories], $new_session_token);
    } elseif ($action === 'redeem') {
        $subcategory_id = isset($data['subcategory_id']) ? (int)$data['subcategory_id'] : 0;
        if ($subcategory_id <= 0) {
            sendResponse(400, 'Missing or invalid subcategory_id');
        }

        // Check if the subcategory exists and is enabled, and get category_id
        $stmt = $conn->prepare("SELECT sub_category_name, sub_category_image_url, coins, is_enabled, category_id FROM redeem_options_subcategories WHERE id = ?");
        $stmt->bind_param("i", $subcategory_id);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 0) {
            $stmt->close();
            $conn->close();
            sendResponse(400, 'Invalid subcategory');
        }

        $subcategory = $result->fetch_assoc();
        if ($subcategory['is_enabled'] == 0) {
            $new_session_token = generateNewSessionToken($user_id, $device_id);
            sendResponse(400, 'Redeem option is disabled', [], $new_session_token);
        }
        $required_coins = $subcategory['coins'];
        $image_url = $subcategory['sub_category_image_url'];
        $category_id = $subcategory['category_id'];

        // Get category_name
        $stmt = $conn->prepare("SELECT category_name FROM redeem_options_categories WHERE id = ?");
        $stmt->bind_param("i", $category_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $category = $result->fetch_assoc();
        $category_name = $category ? $category['category_name'] : '';
        $stmt->close();

        // 1. Check daily withdraw limit
        $today = date('Y-m-d');
        $stmt = $conn->prepare("SELECT daily_withdraw_limit FROM app_settings WHERE id = 1");
        $stmt->execute();
        $result = $stmt->get_result();
        $settings = $result->fetch_assoc();
        $daily_withdraw_limit = isset($settings['daily_withdraw_limit']) ? (int)$settings['daily_withdraw_limit'] : 1;
        $stmt->close();

        $stmt = $conn->prepare("SELECT COUNT(*) as withdraw_count FROM redeem_history WHERE user_id = ? AND DATE(created_at) = ?");
        $stmt->bind_param("is", $user_id, $today);
        $stmt->execute();
        $result = $stmt->get_result();
        $withdraw_data = $result->fetch_assoc();
        $withdraw_count = $withdraw_data ? (int)$withdraw_data['withdraw_count'] : 0;
        $stmt->close();
        if ($withdraw_count >= $daily_withdraw_limit) {
            $new_session_token = generateNewSessionToken($user_id, $device_id);
            sendResponse(400, 'You have reached your daily withdraw limit.', [], $new_session_token);
        }

        // 2. Check if all daily tasks are completed (only for tasks enabled in BOTH tasks and task_limits)
        // Set timezone explicitly and get today's date in IST
        date_default_timezone_set('Asia/Kolkata');
        $today = date('Y-m-d');
        // Debug log for user and date
        error_log('Checking tasks for user_id: ' . $user_id . ', date: ' . $today);
        $all_tasks_done = true;
        $remaining_tasks = [];
        $stmt = $conn->prepare("SELECT t.task_type, tl.daily_limit FROM tasks t INNER JOIN task_limits tl ON t.task_type = tl.task_type AND tl.is_enabled = 1 WHERE t.is_enabled = 1");
        $stmt->execute();
        $result = $stmt->get_result();
        $tasks_to_check = [];
        while ($row = $result->fetch_assoc()) {
            $tasks_to_check[] = $row;
        }
        $stmt->close();
        foreach ($tasks_to_check as $row) {
            $stmt = $conn->prepare("SELECT used_count, user_daily_limit FROM user_task_usage WHERE user_id = ? AND task_type = ? AND usage_date = ?");
            $stmt->bind_param("iss", $user_id, $row['task_type'], $today);
            $stmt->execute();
            $result = $stmt->get_result();
            $usage = $result->fetch_assoc();
            $used_count = $usage ? (int)$usage['used_count'] : 0;
            $user_daily_limit = $usage && isset($usage['user_daily_limit']) ? (int)$usage['user_daily_limit'] : (int)$row['daily_limit'];
            $remaining = $user_daily_limit - $used_count;
            // Debug log for each task
            error_log('Task: ' . $row['task_type'] . ', used_count: ' . $used_count . ', user_daily_limit: ' . $user_daily_limit . ', remaining: ' . $remaining);
            if ($remaining > 0) {
                $all_tasks_done = false;
                $remaining_tasks[] = [
                    'task_type' => $row['task_type'],
                    'used_count' => $used_count,
                    'user_daily_limit' => $user_daily_limit,
                    'remaining' => $remaining
                ];
            }
            $stmt->close();
        }
        if (!$all_tasks_done) {
            $new_session_token = generateNewSessionToken($user_id, $device_id);
            $pending_msg = [];
            foreach ($remaining_tasks as $task) {
                $pending_msg[] = $task['task_type'] . ' (' . $task['remaining'] . ' left)';
            }
            $pending_str = 'Pending tasks: ' . implode(', ', $pending_msg);
            sendResponse(400, 'Complete all daily tasks before withdrawing. ' . $pending_str, ['remaining_tasks' => $remaining_tasks], $new_session_token);
        }

        // 3. Check if user has sufficient coins
        $stmt = $conn->prepare("SELECT coins FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows === 0) {
            $stmt->close();
            $conn->close();
            sendResponse(400, 'Invalid user');
        }
        $user = $result->fetch_assoc();
        $user_coins = $user['coins'];
        $stmt->close();
        if ($user_coins < $required_coins) {
            $new_session_token = generateNewSessionToken($user_id, $device_id);
            sendResponse(400, 'Insufficient coins', [], $new_session_token);
        }

        // 4. If category_name is 'Upi Transfer', insert as pending
        if (strtolower($category_name) === 'upi transfer') {
            $new_coins = $user_coins - $required_coins;
            $stmt = $conn->prepare("UPDATE users SET coins = ? WHERE id = ?");
            $stmt->bind_param("ii", $new_coins, $user_id);
            $stmt->execute();
            $stmt = $conn->prepare("INSERT INTO redeem_history (user_id, subcategory_id, image_url, status, created_at) VALUES (?, ?, ?, 'pending', NOW())");
            $stmt->bind_param("iis", $user_id, $subcategory_id, $image_url);
            $stmt->execute();
            $stmt->close();
            $new_session_token = generateNewSessionToken($user_id, $device_id);
            sendResponse(200, 'Redeem request in pending', ['coins' => $new_coins], $new_session_token);
        }

        // 5. For other categories, check for available gift code
        // Now match category_id and coins value and pick random
        $stmt = $conn->prepare("SELECT id, code, pin FROM giftcodes WHERE category_id = ? AND coins = ? AND is_used = 0 ORDER BY RAND() LIMIT 1");
        $stmt->bind_param("ii", $category_id, $required_coins);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows === 0) {
            $stmt->close();
            $conn->close();
            $new_session_token = generateNewSessionToken($user_id, $device_id);
            sendResponse(400, 'Currently Codes Not Available Wait Please!', [], $new_session_token);
        }
        $giftcode = $result->fetch_assoc();
        $stmt->close();

        // Mark gift code as used and assign to user
        $stmt = $conn->prepare("UPDATE giftcodes SET is_used = 1, assigned_to = ?, assigned_at = NOW() WHERE id = ?");
        $stmt->bind_param("ii", $user_id, $giftcode['id']);
        $stmt->execute();
        $stmt->close();

        // Deduct coins from the user
        $new_coins = $user_coins - $required_coins;
        $stmt = $conn->prepare("UPDATE users SET coins = ? WHERE id = ?");
        $stmt->bind_param("ii", $new_coins, $user_id);
        $stmt->execute();

        // Insert the redeem request into redeem_history with approved status, gift_code, and pin (if Flipkart)
        if (strtolower($category_name) === 'flipkart voucher') {
            $stmt = $conn->prepare("INSERT INTO redeem_history (user_id, subcategory_id, image_url, gift_code, pin, status, created_at) VALUES (?, ?, ?, ?, ?, 'approved', NOW())");
            $stmt->bind_param("iisss", $user_id, $subcategory_id, $image_url, $giftcode['code'], $giftcode['pin']);
        } else {
            $stmt = $conn->prepare("INSERT INTO redeem_history (user_id, subcategory_id, image_url, gift_code, pin, status, created_at) VALUES (?, ?, ?, ?, NULL, 'approved', NOW())");
            $stmt->bind_param("iiss", $user_id, $subcategory_id, $image_url, $giftcode['code']);
        }
        $stmt->execute();
        $redeem_id = $conn->insert_id;
        $stmt->close();

        // Fetch and format created_at
        $stmt = $conn->prepare("SELECT created_at FROM redeem_history WHERE id = ?");
        $stmt->bind_param("i", $redeem_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $stmt->close();
        $created_at = $row ? $row['created_at'] : '';
        $date = $created_at ? date('d/m/Y', strtotime($created_at)) : '';
        $time = $created_at ? date('h:i A', strtotime($created_at)) : '';
        $formatted_created_at = $date && $time ? ($date . ' ' . $time) : '';

        // --- Referral reward logic: award on first redeem ---
        // Check if user was referred and hasn't received referral reward
        $stmt_user_referral = $conn->prepare("SELECT referred_by FROM users WHERE id = ?");
        $stmt_user_referral->bind_param("i", $user_id);
        $stmt_user_referral->execute();
        $result_user_referral = $stmt_user_referral->get_result();
        $user_referral_info = $result_user_referral->fetch_assoc();
        $stmt_user_referral->close();
        if ($user_referral_info && $user_referral_info['referred_by']) {
            $referrer_id = $user_referral_info['referred_by'];
            // Check if reward already given
            $stmt_check_reward = $conn->prepare("SELECT id FROM referral_rewards WHERE referrer_id = ? AND referred_id = ?");
            $stmt_check_reward->bind_param("ii", $referrer_id, $user_id);
            $stmt_check_reward->execute();
            $result_check_reward = $stmt_check_reward->get_result();
            if ($result_check_reward->num_rows === 0) {
                $stmt_check_reward->close();
                // Get reward values
                $stmt_settings = $conn->prepare("SELECT referrer_coins, referred_coins FROM app_settings WHERE id = 1");
                $stmt_settings->execute();
                $result_settings = $stmt_settings->get_result();
                $settings = $result_settings->fetch_assoc();
                $stmt_settings->close();
                if ($settings) {
                    $referrer_coins_award = $settings['referrer_coins'];
                    $referred_coins_award = $settings['referred_coins'];
                    // Award coins to referrer
                    $stmt_update_referrer = $conn->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
                    $stmt_update_referrer->bind_param("ii", $referrer_coins_award, $referrer_id);
                    $stmt_update_referrer->execute();
                    $stmt_update_referrer->close();
                    // Award coins to referred user
                    $stmt_update_referred = $conn->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
                    $stmt_update_referred->bind_param("ii", $referred_coins_award, $user_id);
                    $stmt_update_referred->execute();
                    $stmt_update_referred->close();
                    // Record the reward
                    $stmt_record_reward = $conn->prepare("INSERT INTO referral_rewards (referrer_id, referred_id, referrer_coins, referred_coins) VALUES (?, ?, ?, ?)");
                    $stmt_record_reward->bind_param("iiii", $referrer_id, $user_id, $referrer_coins_award, $referred_coins_award);
                    $stmt_record_reward->execute();
                    $stmt_record_reward->close();
                }
            } else {
                $stmt_check_reward->close();
            }
        }
        // --- End referral reward logic ---

        $conn->close();
        $new_session_token = generateNewSessionToken($user_id, $device_id);
        sendResponse(200, 'Redeem request successful', ['coins' => $new_coins, 'gift_code' => $giftcode['code'], 'created_at' => $formatted_created_at], $new_session_token);
    } else {
        sendResponse(400, 'Invalid action');
    }

    $conn->close();
} else {
    sendResponse(405, 'Method not allowed');
}
?>