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

$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 maintenance_mode, vpn_allowed, how_to_link, telegram_link, support_link, guest_mode, earning_mode, gamezop_timer, ad_index, gamezop_card_status, ad_app_size FROM app_settings WHERE id = 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $settings = $result->fetch_assoc();
    $stmt->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 = [
        'maintenance' => $settings['maintenance_mode'],
        'vpn_allowed' => $settings['vpn_allowed'],
        'guest_mode' => $settings['guest_mode'],
        'earning_mode' => $settings['earning_mode'],
        'gamezop_timer' => $settings['gamezop_timer'],
        'ad_index' => $settings['ad_index'],
        'gamezop_card_status' => $settings['gamezop_card_status'],
        'ad_app_size' => $settings['ad_app_size'],
        'ad_controls' => $ad_controls,
        'links' => [
            'how_to' => $settings['how_to_link'],
            'telegram' => $settings['telegram_link'],
            'support' => $settings['support_link']
        ]
    ];
    sendResponse(200, 'App settings fetched', $response);
} elseif ($action === 'auth') {
    $user_id = isset($data['user_id']) ? (int)$data['user_id'] : 0;
    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 coins
    $stmt = $conn->prepare("SELECT coins FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    $user_coins = $user ? $user['coins'] : 0;

    // Check daily check-in claim status
    $today = date('Y-m-d');
    $can_claim = true;
    $table_exists = false;
    try {
        $stmt = $conn->prepare("SHOW TABLES LIKE 'daily_checkins'");
        $stmt->execute();
        $result = $stmt->get_result();
        $table_exists = $result->num_rows > 0;
        $stmt->close();
    } 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 (except update fields)
    $stmt = $conn->prepare("SELECT maintenance_mode, vpn_allowed, how_to_link, telegram_link, support_link, guest_mode, earning_mode, gamezop_timer, ad_index, gamezop_card_status, ad_app_size FROM app_settings WHERE id = 1");
    $stmt->execute();
    $result = $stmt->get_result();
    $settings = $result->fetch_assoc();
    $stmt->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 = [
        'maintenance' => $settings['maintenance_mode'],
        'vpn_allowed' => $settings['vpn_allowed'],
        'guest_mode' => $settings['guest_mode'],
        'earning_mode' => $settings['earning_mode'],
        'gamezop_timer' => $settings['gamezop_timer'],
        'ad_index' => $settings['ad_index'],
        'gamezop_card_status' => $settings['gamezop_card_status'],
        'ad_app_size' => $settings['ad_app_size'],
        'ad_controls' => $ad_controls,
        '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']
        ]
    ];
    sendResponse(200, 'Home data fetched', $response, $new_session_token);
} else {
    sendResponse(400, 'Invalid action');
} 