<?php
declare(strict_types=1);
require_once __DIR__ . '/db/config.php';

// Fetch settings
$settings = [];
try {
    $stmt = db()->query("SELECT * FROM settings");
    while ($row = $stmt->fetch()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (Exception $e) {
    // Table might not exist yet or other error
}

$discordToken = $settings['discord_token'] ?? '';
$applicationId = $settings['application_id'] ?? '';

// Helper function to check if bot is running (simplified)
function isBotRunning(): bool {
    $output = [];
    exec("ps aux | grep 'node index.js' | grep -v grep", $output);
    return !empty($output);
}

// Project info
$projectName = $_SERVER['PROJECT_NAME'] ?? 'Sahur Alarm Bot';
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? 'Discord voice bot for sahur alarms.';

?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= htmlspecialchars($projectName) ?> - Control Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/css/custom.css?v=<?= time() ?>" rel="stylesheet">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom mb-4">
    <div class="container">
        <a class="navbar-brand" href="#"><?= htmlspecialchars($projectName) ?></a>
        <div class="ms-auto d-flex align-items-center">
            <span class="status-badge <?= isBotRunning() ? 'status-online' : 'status-offline' ?> me-3">
                <?= isBotRunning() ? '● ONLINE' : '○ OFFLINE' ?>
            </span>
            <?php if (isBotRunning()): ?>
                <a href="bot_control.php?action=stop" class="btn btn-danger btn-sm">Stop Bot</a>
            <?php else: ?>
                <a href="bot_control.php?action=start" class="btn btn-success btn-sm">Start Bot</a>
            <?php endif; ?>
        </div>
    </div>
</nav>

<div class="container">
    <div class="row">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">System Overview</div>
                <div class="card-body">
                    <h3>Welcome to your Sahur Bot Panel</h3>
                    <p class="text-muted"><?= htmlspecialchars($projectDescription) ?></p>
                    <hr>
                    <h5>Bot Source Code (index.js)</h5>
                    <p>The bot is built using Node.js and discord.js v14. It handles the <code>/join</code> and <code>/sahur</code> commands, joins your voice channel, and plays the alarm.</p>
                    
                    <div class="alert alert-light border">
                        <strong>Quick Start:</strong>
                        <ol class="mb-0 mt-2">
                            <li>Masukkan <strong>Application ID</strong> dan <strong>Bot Token</strong> di panel kanan, lalu klik <strong>Save</strong>.</li>
                            <li>Klik <strong>Deploy Slash Commands</strong> agar perintah <code>/join</code> dan <code>/sahur</code> muncul di Discord.</li>
                            <li>Klik <strong>Start Bot</strong> untuk mengaktifkan bot.</li>
                        </ol>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span>Logs & Activity</span>
                    <button class="btn btn-link btn-sm p-0 text-decoration-none" onclick="location.reload()">Refresh</button>
                </div>
                <div class="card-body">
                    <pre id="bot-logs" style="max-height: 300px; overflow-y: auto; background: #1e1e1e; color: #d4d4d4; padding: 15px; border-radius: 4px; font-family: 'Courier New', monospace; font-size: 0.85rem;"><?php 
                        if (file_exists('bot.log')) {
                            $logs = file_get_contents('bot.log');
                            echo htmlspecialchars($logs ?: '[Empty logs]');
                        } else {
                            echo '[System] No logs found. Start the bot to generate logs.';
                        }
                    ?></pre>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card">
                <div class="card-header">Audio Management</div>
                <div class="card-body">
                    <p class="small text-muted">Upload your <code>sahur.mp3</code> file here. Ensure it is named exactly <code>sahur.mp3</code>.</p>
                    <form action="upload_audio.php" method="post" enctype="multipart/form-data">
                        <div class="mb-3">
                            <input class="form-control" type="file" name="audio_file" accept=".mp3" required>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">Upload MP3</button>
                    </form>
                    
                    <?php if (file_exists('sahur.mp3')): ?>
                        <div class="mt-3 p-2 border rounded bg-light d-flex align-items-center">
                            <span class="me-2">🔊</span>
                            <span class="small">sahur.mp3 (<?= round(filesize('sahur.mp3') / 1024 / 1024, 2) ?> MB)</span>
                        </div>
                    <?php else: ?>
                        <div class="mt-3 p-2 border rounded bg-light text-danger small">
                            ⚠️ sahur.mp3 not found.
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="card">
                <div class="card-header">Bot Configuration</div>
                <div class="card-body">
                    <p class="small text-muted">To link your bot, you need to provide credentials from the Discord Developer Portal.</p>
                    
                    <?php if (isset($_GET['success'])): ?>
                        <div class="alert alert-success py-1 small">Settings saved!</div>
                    <?php endif; ?>
                    <?php if (isset($_GET['deploy_success'])): ?>
                        <div class="alert alert-success py-1 small">Slash commands deployed!</div>
                    <?php endif; ?>
                    <?php if (isset($_GET['deploy_error'])): ?>
                        <div class="alert alert-danger py-1 small">Error deploying commands. Check logs.</div>
                    <?php endif; ?>
                    <?php if (isset($_GET['error'])): ?>
                        <div class="alert alert-danger py-1 small">Error saving settings.</div>
                    <?php endif; ?>

                    <form action="save_settings.php" method="post">
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Application ID</label>
                            <input type="text" name="application_id" class="form-control form-control-sm" placeholder="Paste ID here" value="<?= htmlspecialchars($applicationId) ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold">Bot Token</label>
                            <input type="password" name="discord_token" class="form-control form-control-sm" placeholder="Paste Token here" value="<?= htmlspecialchars($discordToken) ?>">
                        </div>
                        <button type="submit" class="btn btn-primary btn-sm w-100 mb-2">Save Configuration</button>
                    </form>
                    
                    <hr>
                    <label class="form-label small fw-bold">Command Deployment</label>
                    <p class="x-small text-muted" style="font-size: 0.7rem;">Click this if slash commands (<code>/sahur</code>) are not showing up in Discord.</p>
                    <a href="deploy_commands.php" class="btn btn-outline-secondary btn-sm w-100">Deploy Slash Commands</a>
                    
                    <p class="text-center x-small mt-3 text-muted" style="font-size: 0.7rem;">Config is saved to the database and <code>config.json</code>.</p>
                </div>
            </div>
        </div>
    </div>
</div>

<footer class="text-center py-4 text-muted border-top bg-white mt-5">
    <div class="container">
        <p class="mb-0 small">&copy; <?= date('Y') ?> <?= htmlspecialchars($projectName) ?>. Built with LAMP + Node.js.</p>
    </div>
</footer>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
