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

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'];
    $visit_duration = (int)$data['visit_duration']; // Duration user spent on the website (in seconds)
    $earned_coins = (int)$data['earned_coins']; // Coins earned from website task completion
    $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 = ['total_coins' => 0, 'show_ad' => false];

    // 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 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();

    // Check if website tasks are enabled
    if (!$settings['website_task_enabled']) {
        sendResponse(400, 'Website tasks are currently disabled');
    }

    // Get a random website task for completion
    $stmt_website_task = $conn->prepare("SELECT id, web_url, timer FROM website_visit_tasks ORDER BY RAND() LIMIT 1");
    if (!$stmt_website_task) {
        sendResponse(500, 'Database query preparation failed for website_visit_tasks: ' . $conn->error);
    }
    $stmt_website_task->execute();
    $result_website_task = $stmt_website_task->get_result();
    
    if ($result_website_task->num_rows === 0) {
        $stmt_website_task->close();
        sendResponse(400, 'No website tasks available');
    }
    
    $website_task = $result_website_task->fetch_assoc();
    $website_task_id = $website_task['id']; // Get the ID for database operations
    $stmt_website_task->close();

    // Verify that the user spent enough time on the website
    if ($visit_duration < $website_task['timer']) {
        sendResponse(400, 'Insufficient visit duration. Required: ' . $website_task['timer'] . ' seconds, Actual: ' . $visit_duration . ' seconds');
    }

    $conn->begin_transaction();
    try {
        // --- Website tasks are unlimited - no task limits ---
        $task_limits_data = ['enabled' => false, 'remaining_limit' => null, 'daily_limit' => null];
        
        // Add task limits data to response (always disabled for website tasks)
        $response_data['task_limits'] = $task_limits_data;

        // --- Step 1: Update user coins with earned_coins ---
        $stmt_update_coins = $conn->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
        if (!$stmt_update_coins) {
            throw new Exception('Database query preparation failed for updating user coins: ' . $conn->error);
        }
        $stmt_update_coins->bind_param("ii", $earned_coins, $user_id);
        $stmt_update_coins->execute();
        $stmt_update_coins->close();

        // --- Step 2: Record website task completion ---
        $stmt_insert_completion = $conn->prepare("INSERT INTO website_task_completions (user_id, website_task_id, earned_coins, visit_duration, completed_at) VALUES (?, ?, ?, ?, ?)");
        if (!$stmt_insert_completion) {
            throw new Exception('Database query preparation failed for inserting website task completion: ' . $conn->error);
        }
        $stmt_insert_completion->bind_param("iiiss", $user_id, $website_task_id, $earned_coins, $visit_duration, $created_at);
        $stmt_insert_completion->execute();
        $stmt_insert_completion->close();

        // --- Step 3: Get the user's NEW total coin balance ---
        $stmt_get_coins = $conn->prepare("SELECT coins FROM users WHERE id = ?");
        if (!$stmt_get_coins) {
            throw new Exception('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 {
            throw new Exception('User not found after coin update.');
        }

        // --- Step 4: Check for referral rewards ---
        $referral_reward_data = ['awarded' => false];
        $stmt_user_referral = $conn->prepare("SELECT referred_by, coins FROM users WHERE id = ?");
        if (!$stmt_user_referral) {
            throw new Exception('Database query preparation failed for fetching user referral info: ' . $conn->error);
        }
        $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();

        // Only proceed with referral logic if referred_by is set
        if ($user_referral_info && $user_referral_info['referred_by']) {
            $referrer_id = $user_referral_info['referred_by'];

            // Check if rewards have already been given for this referral pair
            $stmt_check_reward = $conn->prepare("SELECT id FROM referral_rewards WHERE referrer_id = ? AND referred_id = ?");
            if (!$stmt_check_reward) {
                throw new Exception('Database query preparation failed for checking referral rewards: ' . $conn->error);
            }
            $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();
                
                $referrer_coins_award = $settings['referrer_coins'];
                $referred_coins_award = $settings['referred_coins'];

                // Update referrer's coins
                $stmt_update_referrer = $conn->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
                if (!$stmt_update_referrer) {
                    throw new Exception('Database query preparation failed for updating referrer coins: ' . $conn->error);
                }
                $stmt_update_referrer->bind_param("ii", $referrer_coins_award, $referrer_id);
                $stmt_update_referrer->execute();
                $stmt_update_referrer->close();

                // Record the referral reward
                $stmt_record_reward = $conn->prepare("INSERT INTO referral_rewards (referrer_id, referred_id, referrer_coins, referred_coins) VALUES (?, ?, ?, ?)");
                if (!$stmt_record_reward) {
                    throw new Exception('Database query preparation failed for recording referral reward: ' . $conn->error);
                }
                $stmt_record_reward->bind_param("iiii", $referrer_id, $user_id, $referrer_coins_award, $referred_coins_award);
                $stmt_record_reward->execute();
                $stmt_record_reward->close();

                $referral_reward_data['awarded'] = true;
            } else {
                $stmt_check_reward->close();
            }
        }

        $response_data['referral_reward'] = $referral_reward_data;
        $response_data['earned_coins'] = $earned_coins;
        $response_data['website_task'] = [
            'id' => $website_task['id'],
            'url' => $website_task['web_url'],
            'timer' => $website_task['timer'],
            'visit_duration' => $visit_duration
        ];

        $conn->commit();
        sendResponse(200, 'Website task completed successfully', $response_data, $new_session_token);

    } catch (Exception $e) {
        $conn->rollback();
        $conn->close();
        sendResponse(500, 'Failed to complete website task: ' . $e->getMessage());
    }

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