<?php
/**
 * dashboard.php — Main admin dashboard with Top Quick Actions and DB Optimizer.
 * Auto-installs missing tables/columns on first load.
 */

declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/lib/i18n.php';
require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/settings.php';
require_once __DIR__ . '/lib/installer.php';   // ← auto-install

require_login();

$pdo = db();

// -----------------------------------------------------------------
// Auto-create any missing tables / columns
// -----------------------------------------------------------------
ensure_installed($pdo);

// Veritabanı Optimizasyon (VACUUM) İsteği Kontrolü
if (isset($_GET['action']) && $_GET['action'] === 'optimize_db') {
    try {
        $pdo->exec('VACUUM;');
        header('Location: dashboard.php?optimized=1');
        exit;
    } catch (Exception $e) {
        // Hata durumunda yoksay
    }
}

// İstatistik verilerini çekme
$totalDevices = (int) $pdo->query('SELECT COUNT(*) FROM devices')->fetchColumn();
$activeDevices = (int) $pdo->query('SELECT COUNT(*) FROM devices WHERE registered = 1 AND locked = 0')->fetchColumn();
$lockedDevices = (int) $pdo->query('SELECT COUNT(*) FROM devices WHERE locked = 1')->fetchColumn();
$expiredDevices = 0;
try {
    $expiredDevices = (int) $pdo->query("SELECT COUNT(*) FROM devices WHERE exp_date IS NOT NULL AND exp_date < datetime('now')")->fetchColumn();
} catch (Exception $e) {
    // Sütun yoksa 0 sayar
}

// Varsayılan ilk DNS ID'sini bul (Quick Actions'daki Users butonu için)
$defaultDnsId = 1;
try {
    $firstDns = $pdo->query('SELECT id FROM dns ORDER BY id ASC LIMIT 1')->fetch();
    if ($firstDns) {
        $defaultDnsId = (int) $firstDns['id'];
    }
} catch (Exception $e) {
    // Hata durumunda varsayılan 1 kalır
}

$pageTitle = __('Dashboard', 'Dashboard');
require __DIR__ . '/lib/header.php';
?>

<!-- APPVISION Panel Dynamic Theme Stilleri (Light & Dark Uyumlu) -->
<style>
    .kpi-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 20px;
        margin-bottom: 20px;
    }

    .kpi-card {
        background: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        padding: 22px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02);
        transition: transform 0.2s ease, box-shadow 0.2s ease, background 0.3s ease, border-color 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .kpi-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.05);
    }

    .kpi-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
    }

    .kpi-number {
        font-size: 28px;
        font-weight: 700;
        color: #111827;
        line-height: 1.1;
    }

    .kpi-icon-box {
        width: 44px;
        height: 44px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 22px;
    }

    .kpi-label {
        font-size: 13px;
        color: #6b7280;
        font-weight: 500;
    }

    .kpi-btn {
        margin-top: 14px;
        border-radius: 10px;
        font-size: 13px;
        font-weight: 600;
        padding: 8px 12px;
        text-align: center;
        text-decoration: none;
        display: block;
        transition: opacity 0.2s;
    }

    .kpi-btn:hover {
        opacity: 0.9;
    }

    /* Üst Yatay Quick Actions Bar */
    .quick-actions-bar {
        background: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        padding: 16px 24px;
        margin-bottom: 28px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02);
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .quick-actions-title {
        font-size: 11px;
        font-weight: 700;
        letter-spacing: 0.8px;
        text-transform: uppercase;
        color: #6b7280;
        margin-bottom: 12px;
    }

    .quick-actions-flex {
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
    }

    .quick-action-btn {
        background: #f8fafc;
        border: 1px solid #e5e7eb;
        border-radius: 10px;
        padding: 10px 18px;
        color: #374151;
        font-weight: 600;
        font-size: 0.9rem;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
        transition: all 0.2s ease;
    }

    .quick-action-btn i {
        font-size: 18px;
        color: #7c3aed;
    }

    .quick-action-btn:hover {
        background: #f5f3ff;
        border-color: #ddd6fe;
        color: #7c3aed;
        transform: translateY(-1px);
    }

    /* --- Dark Mode (Koyu Tema) Uyarlamaları --- */
    [data-bs-theme="dark"] .kpi-card,
    [data-bs-theme="dark"] .quick-actions-bar {
        background: #171426 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .kpi-number {
        color: #ffffff !important;
    }

    [data-bs-theme="dark"] .kpi-label,
    [data-bs-theme="dark"] .quick-actions-title {
        color: #9ca3af !important;
    }

    [data-bs-theme="dark"] .quick-action-btn {
        background: #141122;
        border-color: rgba(255, 255, 255, 0.08);
        color: #f3f4f6;
    }

    [data-bs-theme="dark"] .quick-action-btn:hover {
        background: rgba(124, 58, 237, 0.15);
        border-color: rgba(124, 58, 237, 0.3);
        color: #a78bfa;
    }

    [data-bs-theme="dark"] .h3, 
    [data-bs-theme="dark"] h1 {
        color: #ffffff !important;
    }
</style>

<div class="d-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 fw-bold"><?= __('Dashboard', 'Dashboard') ?></h1>
</div>

<?php if (isset($_GET['optimized'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="la la-check-circle me-1"></i> Veritabanı başarıyla optimize edildi ve temizlendi!
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- KPI İstatistik Kartları -->
<div class="kpi-grid">
    <div class="kpi-card">
        <div class="kpi-top">
            <div class="kpi-number"><?= $activeDevices ?></div>
            <div class="kpi-icon-box" style="background: #ecfdf5; color: #10b981;">
                <i class="la la-check-circle"></i>
            </div>
        </div>
        <div class="kpi-label"><?= __('Active Devices', 'Active Devices') ?></div>
        <a href="devices.php?filter=active" class="kpi-btn" style="background: #10b981; color: #fff;"><?= __('Active Devices', 'Active Devices') ?></a>
    </div>

    <div class="kpi-card">
        <div class="kpi-top">
            <div class="kpi-number"><?= $totalDevices ?></div>
            <div class="kpi-icon-box" style="background: #fff7ed; color: #f97316;">
                <i class="la la-tv"></i>
            </div>
        </div>
        <div class="kpi-label"><?= __('Total Devices', 'Total Devices') ?></div>
        <a href="devices.php" class="kpi-btn" style="background: #f97316; color: #fff;"><?= __('Total Devices', 'Total Devices') ?></a>
    </div>

    <div class="kpi-card">
        <div class="kpi-top">
            <div class="kpi-number"><?= $lockedDevices ?></div>
            <div class="kpi-icon-box" style="background: #fef2f2; color: #ef4444;">
                <i class="la la-lock"></i>
            </div>
        </div>
        <div class="kpi-label"><?= __('Locked Devices', 'Locked Devices') ?></div>
        <a href="devices.php?filter=locked" class="kpi-btn" style="background: #ef4444; color: #fff;"><?= __('Locked Devices', 'Locked Devices') ?></a>
    </div>

    <div class="kpi-card">
        <div class="kpi-top">
            <div class="kpi-number"><?= $expiredDevices ?></div>
            <div class="kpi-icon-box" style="background: #f5f3ff; color: #7c3aed;">
                <i class="la la-clock"></i>
            </div>
        </div>
        <div class="kpi-label"><?= __('Expired Subscriptions', 'Expired Subscriptions') ?></div>
        <a href="devices.php?filter=expired" class="kpi-btn" style="background: #7c3aed; color: #fff;"><?= __('Expired Subscriptions', 'Expired Subscriptions') ?></a>
    </div>
</div>

<!-- Üst Quick Actions Yatay Bar -->
<div class="quick-actions-bar">
    <div class="quick-actions-title"><?= __('Quick Actions', 'Quick Actions') ?></div>
    <div class="quick-actions-flex">
        <a href="activate.php" class="quick-action-btn"><i class="la la-bolt"></i> <?= __('Activate MAC', 'MAC Aktif Et') ?></a>
        <a href="dns_users.php?dns_id=<?= $defaultDnsId ?>" class="quick-action-btn"><i class="la la-users"></i> <?= __('Users', 'Kullanıcılar') ?></a>
        <a href="dns.php" class="quick-action-btn"><i class="la la-server"></i> <?= __('Manage DNS', 'DNS Yönetimi') ?></a>
        <a href="settings.php" class="quick-action-btn"><i class="la la-cog"></i> <?= __('App Settings', 'Uygulama Ayarları') ?></a>
        <a href="devices.php" class="quick-action-btn"><i class="la la-tv"></i> <?= __('All Registered Devices', 'Kayıtlı Cihazlar') ?></a>
        <a href="dashboard.php?action=optimize_db" class="quick-action-btn" onclick="return confirm('Veritabanı defrag edilerek optimize edilsin mi?');"><i class="la la-database"></i> <?= __('Optimize DB', 'DB Temizle & Optimize Et') ?></a>
    </div>
</div>

<?php require __DIR__ . '/lib/footer.php'; ?>
