<?php
// admin.php
session_start();
require_once 'config.php';
require_once 'helpers.php';

// Hardcoded admin login for security
$admin_password = 'admin'; // Change as needed
$logged_in = isset($_SESSION['admin_logged_in']);

if (isset($_POST['login'])) {
    if ($_POST['password'] === $admin_password) {
        $_SESSION['admin_logged_in'] = true;
        $logged_in = true;
    } else {
        $error = "Invalid Password!";
    }
}
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: admin.php");
    exit;
}

if ($logged_in && isset($_POST['action'])) {
    if ($_POST['action'] == 'update_settings') {
        update_config('BOT_TOKEN', $_POST['bot_token']);
        update_config('OWNER_ID', $_POST['owner_id']);
        update_config('CONTACT_TELEGRAM', $_POST['contact_telegram']);
        firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "settings/contact_telegram", 'PUT', $_POST['contact_telegram']);
        $message = "Settings updated successfully!";
    }
    
    if ($_POST['action'] == 'clone_server') {
        // Clone logic
        $old_conn = connect_ftp(FTP1_HOST, FTP1_USER, FTP1_PASS);
        $new_conn = connect_ftp(FTP2_HOST, FTP2_USER, FTP2_PASS);
        
        if ($old_conn && $new_conn) {
            $files = ftp_nlist($old_conn, FTP1_DIR);
            $cloned_count = 0;
            if ($files) {
                foreach ($files as $file) {
                    if (strpos($file, '.html') !== false) {
                        $local_tmp = sys_get_temp_dir() . '/' . basename($file);
                        if (ftp_get($old_conn, $local_tmp, $file, FTP_BINARY)) {
                            if (upload_to_ftp($new_conn, $local_tmp, FTP2_DIR, basename($file))) {
                                $cloned_count++;
                            }
                            unlink($local_tmp);
                        }
                    }
                }
            }
            // Update Firebase domains
            $websites = firebase_curl(FIREBASE_2_URL, FIREBASE_2_SECRET, "");
            if ($websites) {
                $updates = [];
                $base_url = rtrim(NEW_BASE_URL, '/');
                foreach ($websites as $key => $web) {
                    if (is_array($web) && isset($web['link'])) {
                        $updates[$key . '/link'] = $base_url . '/' . $key . '/';
                    }
                }
                if (!empty($updates)) {
                    firebase_curl(FIREBASE_2_URL, FIREBASE_2_SECRET, "", 'PATCH', $updates);
                }
            }
            $message = "Cloned $cloned_count files and updated Firebase domains!";
            ftp_close($old_conn);
            ftp_close($new_conn);
        } else {
            $error = "FTP Connection failed!";
            if (!$old_conn) {
                log_ftp_error("Migration failed: Connection to OLD Server (" . FTP1_HOST . ") could not be established.");
            }
            if (!$new_conn) {
                log_ftp_error("Migration failed: Connection to NEW Server (" . FTP2_HOST . ") could not be established.");
            }
        }
    }
    
    if ($_POST['action'] == 'clear_ftp_logs') {
        $log_path = __DIR__ . '/ftp_errors.log';
        if (file_exists($log_path)) {
            unlink($log_path);
        }
        $message = "FTP Error Logs cleared successfully!";
    }
    
    if ($_POST['action'] == 'update_notification') {
        $notif = [
            'enabled' => isset($_POST['n_enabled']) ? true : false,
            'message' => $_POST['n_message'] ?? '',
            'link' => $_POST['n_link'] ?? '',
            'image' => $_POST['n_image'] ?? '',
            'frequency_hours' => (int)($_POST['n_hours'] ?? 12)
        ];
        firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "settings/notification", 'PUT', $notif);
        $message = "Global App Notification updated successfully!";
    }

    if ($_POST['action'] == 'save_app') {
        $appid = trim($_POST['app_id']);
        $app_data = [
            'switch' => $_POST['switch'] ?? 'OFF',
            'variables' => [
                'name' => $_POST['name'] ?? '',
                'image' => $_POST['image'] ?? '',
                'deposit' => $_POST['deposit'] ?? '',
                'telegram' => $_POST['telegram'] ?? '',
                'domain' => $_POST['domain'] ?? '',
                'invitecode' => $_POST['invitecode'] ?? ''
            ]
        ];
        firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "apps/" . $appid, 'PUT', $app_data);
        $message = "App ID $appid saved successfully!";
    }
    
    if ($_POST['action'] == 'delete_app') {
        $appid = trim($_POST['app_id']);
        firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "apps/" . $appid, 'DELETE');
        $message = "App ID $appid deleted successfully!";
    }
    
    if ($_POST['action'] == 'toggle_app') {
        $appid = trim($_POST['app_id']);
        $current = firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "apps/" . $appid);
        $new_switch = ($current['switch'] ?? 'OFF') === 'ON' ? 'OFF' : 'ON';
        firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "apps/" . $appid, 'PATCH', ['switch' => $new_switch]);
        $message = "App ID $appid switched to $new_switch!";
    }
}

$apps = [];
$notif_settings = ['enabled' => false, 'message' => '', 'link' => '', 'frequency_hours' => 12];
$contact_telegram = CONTACT_TELEGRAM;
if ($logged_in) {
    $apps = firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "apps") ?: [];
    $ns = firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "settings/notification");
    if ($ns) $notif_settings = $ns;
    $ct = firebase_curl(FIREBASE_1_URL, FIREBASE_1_SECRET, "settings/contact_telegram");
    if ($ct) $contact_telegram = $ct;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Master Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<?php if (!$logged_in): ?>
    <div class="container mt-5" style="max-width: 400px;">
        <div class="card shadow">
            <div class="card-body">
                <h4 class="text-center">Admin Login</h4>
                <?php if(isset($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>
                <form method="POST">
                    <input type="password" name="password" class="form-control mb-3" placeholder="Password" required>
                    <button type="submit" name="login" class="btn btn-primary w-100">Login</button>
                </form>
            </div>
        </div>
    </div>
<?php else: ?>
    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>Dashboard</h2>
            <a href="?logout=1" class="btn btn-danger">Logout</a>
        </div>
        
        <?php if(isset($message)) echo "<div class='alert alert-success'>$message</div>"; ?>
        <?php if(isset($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>

        <div class="row">
            <div class="col-md-6">
                <div class="card mb-4 shadow-sm">
                    <div class="card-header bg-dark text-white">System Settings</div>
                    <div class="card-body">
                        <form method="POST">
                            <input type="hidden" name="action" value="update_settings">
                            <div class="mb-2">
                                <label>Bot Token</label>
                                <input type="text" name="bot_token" class="form-control" value="<?= htmlspecialchars(BOT_TOKEN) ?>">
                            </div>
                            <div class="mb-2">
                                <label>Owner ID</label>
                                <input type="text" name="owner_id" class="form-control" value="<?= htmlspecialchars(OWNER_ID) ?>">
                            </div>
                            <div class="mb-2">
                                <label>Contact Telegram Link</label>
                                <input type="url" name="contact_telegram" class="form-control" value="<?= htmlspecialchars($contact_telegram) ?>" placeholder="https://t.me/teacher_slex">
                            </div>

                            <button type="submit" class="btn btn-success w-100">Save Settings</button>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card mb-4 shadow-sm">
                    <div class="card-header bg-primary text-white">Server Migration (Clone Tool)</div>
                    <div class="card-body">
                        <p>This will copy files from Old FTP to New FTP and update domain links in Firebase.</p>
                        <form method="POST" onsubmit="return confirm('Are you sure you want to clone servers?');" class="mb-3">
                            <input type="hidden" name="action" value="clone_server">
                            <button type="submit" class="btn btn-warning w-100">Start Cloning Process</button>
                        </form>

                        <?php
                        $log_path = __DIR__ . '/ftp_errors.log';
                        if (file_exists($log_path) && filesize($log_path) > 0): ?>
                            <div class="mt-3">
                                <label class="font-weight-bold text-danger d-block mb-1">FTP Connection Log / Errors:</label>
                                <textarea class="form-control bg-light text-dark small" style="font-family: monospace; font-size: 11px;" rows="6" readonly><?= htmlspecialchars(file_get_contents($log_path)) ?></textarea>
                                <form method="POST" class="mt-2">
                                    <input type="hidden" name="action" value="clear_ftp_logs">
                                    <button type="submit" class="btn btn-sm btn-outline-danger mt-1">Clear Logs</button>
                                </form>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12 mb-4">
                <div class="card shadow-sm">
                    <div class="card-header bg-success text-white">Global App Notification Manager</div>
                    <div class="card-body">
                        <p class="text-muted small">Set a popup notification that appears inside the Android app after a user enters a valid key. It will only show once every X hours per user.</p>
                        <form method="POST">
                            <input type="hidden" name="action" value="update_notification">
                            
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" id="n_enabled" name="n_enabled" value="1" <?= $notif_settings['enabled'] ? 'checked' : '' ?>>
                                <label class="form-check-label font-weight-bold" for="n_enabled">Enable Global Popup</label>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <label>Popup Message / Text</label>
                                    <textarea name="n_message" class="form-control" rows="4" placeholder="Enter your notification message here..."><?= htmlspecialchars($notif_settings['message'] ?? '') ?></textarea>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-2">
                                        <label>Popup Image URL (Optional)</label>
                                        <input type="url" name="n_image" class="form-control" placeholder="https://.../image.png" value="<?= htmlspecialchars($notif_settings['image'] ?? '') ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label>Target Link (Optional)</label>
                                        <input type="url" name="n_link" class="form-control" placeholder="https://..." value="<?= htmlspecialchars($notif_settings['link'] ?? '') ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label>Frequency (Show every X hours)</label>
                                        <input type="number" name="n_hours" class="form-control" min="1" max="720" value="<?= (int)($notif_settings['frequency_hours'] ?? 12) ?>">
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-success w-100 mt-2">Save Notification Setup</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-4">
            <!-- App ID Form -->
            <div class="col-md-4">
                <div class="card shadow-sm">
                    <div class="card-header bg-primary text-white" id="formTitle">Add / Edit App ID</div>
                    <div class="card-body">
                        <form method="POST" id="appForm">
                            <input type="hidden" name="action" value="save_app">
                            
                            <div class="mb-2">
                                <label class="form-label font-weight-bold">App ID</label>
                                <input type="text" name="app_id" id="f_app_id" class="form-control" placeholder="e.g. APP_001" required>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label font-weight-bold">Status (Switch)</label>
                                <select name="switch" id="f_switch" class="form-select">
                                    <option value="ON">ON</option>
                                    <option value="OFF">OFF</option>
                                </select>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label font-weight-bold">Panel Name</label>
                                <input type="text" name="name" id="f_name" class="form-control" placeholder="Name" required>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label font-weight-bold">Image URL</label>
                                <input type="url" name="image" id="f_image" class="form-control" placeholder="https://..." required>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label font-weight-bold">Min Deposit</label>
                                <input type="number" name="deposit" id="f_deposit" class="form-control" placeholder="Deposit Amount" required>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label font-weight-bold">Telegram Link</label>
                                <input type="url" name="telegram" id="f_telegram" class="form-control" placeholder="https://t.me/..." required>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label font-weight-bold">Primary Domain</label>
                                <input type="url" name="domain" id="f_domain" class="form-control" placeholder="https://..." required>
                            </div>
                            
                            <div class="mb-2">
                                <label class="form-label font-weight-bold">Invite Code</label>
                                <input type="text" name="invitecode" id="f_invitecode" class="form-control" placeholder="Code" required>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 mt-2">Save App ID</button>
                            <button type="button" class="btn btn-outline-secondary w-100 mt-2" onclick="resetAppForm()">Clear / New</button>
                        </form>
                    </div>
                </div>
            </div>
            
            <!-- App ID Directory -->
            <div class="col-md-8">
                <div class="card shadow-sm">
                    <div class="card-header bg-secondary text-white">App IDs Directory (Firebase 1)</div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover align-middle mb-0" style="font-size:13px;">
                                <thead class="table-light">
                                    <tr>
                                        <th>App ID</th>
                                        <th>Name</th>
                                        <th>Domain</th>
                                        <th>Switch</th>
                                        <th class="text-end pe-3">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach($apps as $id => $app): ?>
                                         <tr>
                                             <td class="fw-bold"><?= htmlspecialchars($id) ?></td>
                                             <td><?= htmlspecialchars($app['variables']['name'] ?? '') ?></td>
                                             <td class="text-muted"><?= htmlspecialchars($app['variables']['domain'] ?? '') ?></td>
                                             <td>
                                                 <form method="POST" style="display:inline;">
                                                     <input type="hidden" name="action" value="toggle_app">
                                                     <input type="hidden" name="app_id" value="<?= htmlspecialchars($id) ?>">
                                                     <button type="submit" class="btn btn-sm btn-<?= ($app['switch']??'')=='ON'?'success':'danger' ?>" style="font-size:11px; padding:2px 8px;">
                                                         <?= $app['switch']??'OFF' ?>
                                                     </button>
                                                 </form>
                                             </td>
                                             <td class="text-end pe-3">
                                                 <button class="btn btn-sm btn-outline-primary" style="font-size:11px; padding:2px 6px;" 
                                                     onclick="editApp('<?= htmlspecialchars($id) ?>', '<?= htmlspecialchars($app['switch']??'OFF') ?>', '<?= htmlspecialchars($app['variables']['name']??'') ?>', '<?= htmlspecialchars($app['variables']['image']??'') ?>', '<?= htmlspecialchars($app['variables']['deposit']??'') ?>', '<?= htmlspecialchars($app['variables']['telegram']??'') ?>', '<?= htmlspecialchars($app['variables']['domain']??'') ?>', '<?= htmlspecialchars($app['variables']['invitecode']??'') ?>')">
                                                     Edit
                                                 </button>
                                                <form method="POST" style="display:inline;" onsubmit="return confirm('Delete App ID <?= htmlspecialchars($id) ?>?');">
                                                    <input type="hidden" name="action" value="delete_app">
                                                    <input type="hidden" name="app_id" value="<?= htmlspecialchars($id) ?>">
                                                    <button type="submit" class="btn btn-sm btn-outline-danger" style="font-size:11px; padding:2px 6px;">Delete</button>
                                                </form>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    <?php if(empty($apps)): ?>
                                        <tr><td colspan="5" class="text-center py-4 text-muted">No App IDs found.</td></tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
        function editApp(id, sw, name, img, dep, tg, dom, inv) {
            document.getElementById('f_app_id').value = id;
            document.getElementById('f_app_id').readOnly = true;
            document.getElementById('f_switch').value = sw;
            document.getElementById('f_name').value = name;
            document.getElementById('f_image').value = img;
            document.getElementById('f_deposit').value = dep;
            document.getElementById('f_telegram').value = tg;
            document.getElementById('f_domain').value = dom;
            document.getElementById('f_invitecode').value = inv;
            document.getElementById('formTitle').innerText = "Edit App ID: " + id;
        }
        function resetAppForm() {
            document.getElementById('f_app_id').value = '';
            document.getElementById('f_app_id').readOnly = false;
            document.getElementById('f_switch').value = 'ON';
            document.getElementById('f_name').value = '';
            document.getElementById('f_image').value = '';
            document.getElementById('f_deposit').value = '';
            document.getElementById('f_telegram').value = '';
            document.getElementById('f_domain').value = '';
            document.getElementById('f_invitecode').value = '';
            document.getElementById('formTitle').innerText = "Add / Edit App ID";
        }
        </script>
    </div>
<?php endif; ?>
</body>
</html>
