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

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

$action = isset($data['action']) ? $data['action'] : 'public';

$conn = getDbConnection();

if ($action === 'public') {
    // Fetch app settings (public, no auth, no session token)
    $stmt = $conn->prepare("SELECT app_link, app_base_url, version, version_code, changelogs, maintenance_mode, vpn_allowed, how_to_link, telegram_link, support_link, privacy_policy_url, delete_url, packages, guest_mode, earning_mode, gamezop_timer, gamezop_card_status, ad_app_size, update_mode FROM app_settings WHERE id = 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $settings = $result->fetch_assoc();
    $stmt->close();

    // Fetch ads settings
    $stmt_ads = $conn->prepare("SELECT app_id, interstitial_ad_unit, native_ad_unit, banner_ad_unit, reward_ad_unit, appopen_ad_unit FROM ads_settings WHERE id = 1");
    $stmt_ads->execute();
    $result_ads = $stmt_ads->get_result();
    $ads_settings = $result_ads->fetch_assoc();
    $stmt_ads->close();

    // Fetch ad controls
    $stmt_adctrl = $conn->prepare("SELECT * FROM ad_controls");
    $stmt_adctrl->execute();
    $result_adctrl = $stmt_adctrl->get_result();
    $ad_controls = [];
    while ($row = $result_adctrl->fetch_assoc()) {
        $ad_controls[] = $row;
    }
    $stmt_adctrl->close();

    $conn->close();
    $response = [
        'update' => [
            'app_link' => $settings['app_link'],
            'app_base_url' => $settings['app_base_url'],
            'version' => $settings['version'],
            'version_code' => $settings['version_code'],
            'changelogs' => $settings['changelogs']
        ],
        'maintenance' => $settings['maintenance_mode'],
        'vpn_allowed' => $settings['vpn_allowed'],
        'guest_mode' => $settings['guest_mode'],
        'earning_mode' => $settings['earning_mode'],
        'gamezop_timer' => $settings['gamezop_timer'],
        'gamezop_card_status' => $settings['gamezop_card_status'],
        'ad_app_size' => $settings['ad_app_size'],
        'packages' => $settings['packages'],
        'update_mode' => isset($settings['update_mode']) ? $settings['update_mode'] : 'off',
        'ads_settings' => [
            'app_id' => $ads_settings['app_id'],
            'interstitial_ad_unit' => $ads_settings['interstitial_ad_unit'],
            'native_ad_unit' => $ads_settings['native_ad_unit'],
            'banner_ad_unit' => $ads_settings['banner_ad_unit'],
            'reward_ad_unit' => $ads_settings['reward_ad_unit'],
            'appopen_ad_unit' => $ads_settings['appopen_ad_unit']
        ],
        'ad_controls' => $ad_controls,
        'links' => [
            'how_to' => $settings['how_to_link'],
            'telegram' => $settings['telegram_link'],
            'support' => $settings['support_link'],
            'privacy_policy' => $settings['privacy_policy_url'],
            'delete_account' => $settings['delete_url']
        ]
    ];
    sendResponse(200, 'App settings fetched', $response);
} elseif ($action === 'user_blocked') {
    $user_id = isset($data['user_id']) ? (int)$data['user_id'] : 0;
    $device_id = $_SERVER['HTTP_DEVICE_ID'] ?? '';
    $session_token = $_SERVER['HTTP_SESSION_TOKEN'] ?? '';
    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);
    
    // Fetch user block status and coins
    $stmt = $conn->prepare("SELECT is_blocked, coins FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    if (!$user) {
        $conn->close();
        sendResponse(404, 'User not found');
    }
    
    // Check daily checkin status
    $today = date('Y-m-d');
    $can_claim = true;
    
    // Check if daily_checkins table exists
    $table_exists = false;
    try {
        $stmt = $conn->prepare("SHOW TABLES LIKE 'daily_checkins'");
        $stmt->execute();
        $result = $stmt->get_result();
        $table_exists = $result->num_rows > 0;
    } catch (Exception $e) {
        $table_exists = false;
    }
    
    if ($table_exists) {
        try {
            $stmt = $conn->prepare("SELECT claimed_at FROM daily_checkins WHERE user_id = ? AND DATE(claimed_at) = ? ORDER BY claimed_at DESC LIMIT 1");
            $stmt->bind_param("is", $user_id, $today);
            $stmt->execute();
            $result = $stmt->get_result();
            $can_claim = $result->num_rows === 0;
            $stmt->close();
        } catch (Exception $e) {
            $can_claim = true;
        }
    }
    
    // Fetch app settings
    $stmt = $conn->prepare("SELECT app_link, app_base_url, version, version_code, changelogs, maintenance_mode, vpn_allowed, how_to_link, telegram_link, support_link, privacy_policy_url, delete_url, packages, guest_mode, earning_mode, gamezop_timer, gamezop_card_status, ad_app_size, update_mode FROM app_settings WHERE id = 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $settings = $result->fetch_assoc();
    $stmt->close();

    // Fetch ads settings
    $stmt_ads = $conn->prepare("SELECT app_id, interstitial_ad_unit, native_ad_unit, banner_ad_unit, reward_ad_unit, appopen_ad_unit FROM ads_settings WHERE id = 1");
    $stmt_ads->execute();
    $result_ads = $stmt_ads->get_result();
    $ads_settings = $result_ads->fetch_assoc();
    $stmt_ads->close();

    // Fetch ad controls
    $stmt_adctrl = $conn->prepare("SELECT * FROM ad_controls");
    $stmt_adctrl->execute();
    $result_adctrl = $stmt_adctrl->get_result();
    $ad_controls = [];
    while ($row = $result_adctrl->fetch_assoc()) {
        $ad_controls[] = $row;
    }
    $stmt_adctrl->close();

    $conn->close();
    $response = [
        'update' => [
            'app_link' => $settings['app_link'],
            'app_base_url' => $settings['app_base_url'],
            'version' => $settings['version'],
            'version_code' => $settings['version_code'],
            'changelogs' => $settings['changelogs']
        ],
        'maintenance' => $settings['maintenance_mode'],
        'vpn_allowed' => $settings['vpn_allowed'],
        'guest_mode' => $settings['guest_mode'],
        'earning_mode' => $settings['earning_mode'],
        'gamezop_timer' => $settings['gamezop_timer'],
        'gamezop_card_status' => $settings['gamezop_card_status'],
        'ad_app_size' => $settings['ad_app_size'],
        'packages' => $settings['packages'],
        'update_mode' => isset($settings['update_mode']) ? $settings['update_mode'] : 'off',
        'ads_settings' => [
            'app_id' => $ads_settings['app_id'],
            'interstitial_ad_unit' => $ads_settings['interstitial_ad_unit'],
            'native_ad_unit' => $ads_settings['native_ad_unit'],
            'banner_ad_unit' => $ads_settings['banner_ad_unit'],
            'reward_ad_unit' => $ads_settings['reward_ad_unit'],
            'appopen_ad_unit' => $ads_settings['appopen_ad_unit']
        ],
        'ad_controls' => $ad_controls,
        'is_blocked' => $user['is_blocked'],
        'user_coins' => $user['coins'],
        'daily_checkin' => [
            'can_claim' => $can_claim
        ],
        'links' => [
            'how_to' => $settings['how_to_link'],
            'telegram' => $settings['telegram_link'],
            'support' => $settings['support_link'],
            'privacy_policy' => $settings['privacy_policy_url'],
            'delete_account' => $settings['delete_url']
        ]
    ];
    sendResponse(200, 'User block status and app settings fetched', $response, $new_session_token);
} else {
    sendResponse(400, 'Invalid action');
}