<?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 = ['total_coins' => 0, 'show_ad' => true];

    // Fetch app settings for task limits
    $stmt_settings = $conn->prepare("SELECT 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();

    $conn->begin_transaction();
    try {
        // --- Task Limits Check and Update ---
        $task_limits_data = ['enabled' => false, 'remaining_limit' => null, 'daily_limit' => null];

        if ($settings['task_limits_enabled'] && !empty($by_task)) {
            // Check if task limits are enabled and by_task is provided
            // Only apply limits to valid task types that are in the ENUM
            $valid_task_types = ['emoji_maths', 'meaning_match', 'color_finder'];

            if (in_array($by_task, $valid_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 ($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;
                                }
                                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;
                            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);
                            }
                            // Update or insert usage count
                            if ($usage_data) {
                                $stmt_update_usage = $conn->prepare("UPDATE user_task_usage SET used_count = used_count + 1, updated_at = NOW() WHERE user_id = ? AND task_type = ? AND usage_date = ?");
                                if ($stmt_update_usage) {
                                    $stmt_update_usage->bind_param("iss", $user_id, $by_task, $today);
                                    $stmt_update_usage->execute();
                                    $stmt_update_usage->close();
                                }
                            } else {
                                $stmt_insert_usage = $conn->prepare("INSERT INTO user_task_usage (user_id, task_type, usage_date, used_count) VALUES (?, ?, ?, 1)");
                                if ($stmt_insert_usage) {
                                    $stmt_insert_usage->bind_param("iss", $user_id, $by_task, $today);
                                    $stmt_insert_usage->execute();
                                    $stmt_insert_usage->close();
                                }
                            }
                            $task_limits_data['remaining_limit'] = $remaining_limit - 1;
                            $task_limits_data['used_count'] = $current_usage + 1;
                        } else {
                            throw new Exception('Database query preparation failed for checking task usage: ' . $conn->error);
                        }
                    } else {
                        $task_limits_data['enabled'] = false;
                    }
                } else {
                    throw new Exception('Database query preparation failed for checking task limits: ' . $conn->error);
                }
            } else {
                // Task type not in valid list, treat as unlimited
                $task_limits_data['enabled'] = false;
            }
        }

        // Add task limits data to response
        if ($task_limits_data['enabled']) {
            $limits_array = [
                [
                    ['daily_limit', $task_limits_data['daily_limit']],
                    ['remaining_limit', $task_limits_data['remaining_limit']],
                    ['task_type', $by_task],
                    ['used_count', $task_limits_data['used_count']]
                ]
            ];
            $response_data['limits'] = $limits_array;
        }
        unset($response_data['task_limits']);

        // --- 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: Insert task completion record ---
        // Get task_id based on by_task (assuming by_task contains task type or task_id)
        $task_id = null;
        if (!empty($by_task)) {
            if (is_numeric($by_task)) {
                // If by_task is a number, assume it's task_id
                $task_id = (int)$by_task;
            } else {
                // If by_task is a string (task type), find the corresponding task_id
                $stmt_get_task = $conn->prepare("SELECT id FROM tasks WHERE task_type = ? LIMIT 1");
                if (!$stmt_get_task) {
                    throw new Exception('Database query preparation failed for fetching task: ' . $conn->error);
                }
                $stmt_get_task->bind_param("s", $by_task);
                $stmt_get_task->execute();
                $result_get_task = $stmt_get_task->get_result();
                if ($result_get_task->num_rows > 0) {
                    $task_data = $result_get_task->fetch_assoc();
                    $task_id = $task_data['id'];
                }
                $stmt_get_task->close();
            }
        }

        // Insert task completion record if task_id is found
        if ($task_id) {
            $stmt_insert_completion = $conn->prepare("INSERT INTO task_completions (user_id, task_id, earned_coins, by_task) VALUES (?, ?, ?, ?)");
            if (!$stmt_insert_completion) {
                throw new Exception('Database query preparation failed for inserting task completion: ' . $conn->error);
            }
            $stmt_insert_completion->bind_param("iiis", $user_id, $task_id, $earned_coins, $by_task);
            $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.');
        }

        $response_data['earned_coins'] = $earned_coins;

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

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

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