<?php
/**
 * devices.php — Devices management page with Nxs Panel dynamic light/dark style and Per-Page Selector.
 */

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_login();

$pdo = db();

// --- TEK DOSYA İÇİNDE İŞLEM YÖNETİMİ ---
if (isset($_GET['action']) && isset($_GET['id'])) {
    $action = trim((string) $_GET['action']);
    $id = (int) $_GET['id'];

    if ($id > 0) {
        if ($action === 'delete') {
            $stmt = $pdo->prepare("DELETE FROM devices WHERE id = ?");
            $stmt->execute([$id]);
        } elseif ($action === 'lock') {
            $stmt = $pdo->prepare("SELECT locked FROM devices WHERE id = ?");
            $stmt->execute([$id]);
            $dev = $stmt->fetch();
            if ($dev) {
                $newLock = ((int) $dev['locked'] === 1) ? 0 : 1;
                $upd = $pdo->prepare("UPDATE devices SET locked = ? WHERE id = ?");
                $upd->execute([$newLock, $id]);
            }
        } elseif ($action === 'deactivate') {
            $stmt = $pdo->prepare("SELECT registered FROM devices WHERE id = ?");
            $stmt->execute([$id]);
            $dev = $stmt->fetch();
            if ($dev) {
                $newReg = ((int) $dev['registered'] === 1) ? 0 : 1;
                $upd = $pdo->prepare("UPDATE devices SET registered = ? WHERE id = ?");
                $upd->execute([$newReg, $id]);
            }
        }
    }

    $redirectParams = [];
    if (isset($_GET['q']) && trim((string)$_GET['q']) !== '') $redirectParams['q'] = trim((string)$_GET['q']);
    if (isset($_GET['filter']) && trim((string)$_GET['filter']) !== 'all') $redirectParams['filter'] = trim((string)$_GET['filter']);
    if (isset($_GET['limit']) && in_array((int)$_GET['limit'], [25, 50, 100], true)) $redirectParams['limit'] = (int)$_GET['limit'];
    if (isset($_GET['p']) && (int)$_GET['p'] > 1) $redirectParams['p'] = (int)$_GET['p'];
    
    $queryString = !empty($redirectParams) ? '?' . http_build_query($redirectParams) : '';
    header('Location: devices.php' . $queryString);
    exit;
}
// --------------------------------------------------------------------------

// Arama, Filtreleme ve Sayfa Başına Kayıt Limiti
$search = trim((string) ($_GET['q'] ?? ''));
$filter = trim((string) ($_GET['filter'] ?? 'all'));
$allowedLimits = [25, 50, 100];
$perPage = isset($_GET['limit']) && in_array((int)$_GET['limit'], $allowedLimits, true) ? (int)$_GET['limit'] : 25;

$page = max(1, (int) ($_GET['p'] ?? 1));
$offset = ($page - 1) * $perPage;

// KPI İstatistikleri
$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) {
    $expiredDevices = 0;
}

// Sorgu Oluşturma (Filtreler)
$whereClauses = [];
$params = [];

if ($search !== '') {
    $whereClauses[] = "(account_name LIKE ? OR mac LIKE ? OR device_key LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($filter === 'active') {
    $whereClauses[] = "registered = 1 AND locked = 0";
} elseif ($filter === 'locked') {
    $whereClauses[] = "locked = 1";
} elseif ($filter === 'expired') {
    try {
        $pdo->query("SELECT exp_date LIMIT 1");
        $whereClauses[] = "exp_date IS NOT NULL AND exp_date < datetime('now')";
    } catch (Exception $e) {
        $whereClauses[] = "1 = 0";
    }
}

$whereSql = count($whereClauses) > 0 ? 'WHERE ' . implode(' AND ', $whereClauses) : '';

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM devices $whereSql");
$countStmt->execute($params);
$totalFilteredDevices = (int) $countStmt->fetchColumn();
$totalPages = max(1, ceil($totalFilteredDevices / $perPage));

if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $perPage;
}

$dataSql = "SELECT * FROM devices $whereSql ORDER BY id DESC LIMIT ? OFFSET ?";
$stmt = $pdo->prepare($dataSql);

$bindIndex = 1;
foreach ($params as $val) {
    $stmt->bindValue($bindIndex++, $val);
}
$stmt->bindValue($bindIndex++, $perPage, PDO::PARAM_INT);
$stmt->bindValue($bindIndex++, $offset, PDO::PARAM_INT);
$stmt->execute();
$devices = $stmt->fetchAll();

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

<style>
    .kpi-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
        gap: 20px;
        margin-bottom: 28px;
    }

    .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;
    }

    .glass-card {
        background: #ffffff !important;
        border: 1px solid #e5e7eb !important;
        border-radius: 16px !important;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02) !important;
        overflow: hidden;
        margin-bottom: 24px;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .filter-bar {
        padding: 20px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f8fafc;
        display: flex;
        align-items: center;
        gap: 16px;
        flex-wrap: wrap;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .filter-bar .search-input-group {
        flex: 1;
        min-width: 280px;
        position: relative;
    }

    .filter-bar .search-input-group i {
        position: absolute;
        left: 14px;
        top: 50%;
        transform: translateY(-50%);
        color: #9ca3af;
        font-size: 18px;
    }

    .filter-bar .search-input-group input {
        width: 100%;
        padding: 10px 14px 10px 42px;
        border: 1px solid #e5e7eb;
        border-radius: 10px;
        font-size: 0.9rem;
        background: #ffffff;
        color: #1f2937;
        outline: none;
        transition: border-color 0.2s, background 0.3s ease, color 0.3s ease;
    }

    .filter-bar .search-input-group input:focus {
        border-color: #7c3aed;
    }

    .filter-select {
        padding: 10px 16px;
        border: 1px solid #e5e7eb;
        border-radius: 10px;
        font-size: 0.9rem;
        background: #ffffff;
        color: #374151;
        outline: none;
        font-weight: 500;
        transition: border-color 0.2s, background 0.3s ease, color 0.3s ease;
    }

    .titan-table {
        margin-bottom: 0;
        color: #1f2937;
        width: 100%;
    }

    .titan-table th {
        font-size: 0.75rem;
        font-weight: 700;
        letter-spacing: 0.8px;
        text-transform: uppercase;
        color: #4b5563;
        background: #f8fafc;
        border-bottom: 2px solid #e5e7eb;
        padding: 14px 20px;
        white-space: nowrap;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table td {
        border-bottom: 1px solid #e5e7eb !important;
        padding: 14px 20px;
        vertical-align: middle;
        font-size: 0.9rem;
        color: #374151;
        white-space: nowrap;
        transition: background 0.3s ease, color 0.3s ease, border-color 0.3s ease;
    }

    .titan-table tbody tr:hover {
        background: #f8fafc;
    }

    .code-badge {
        font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
        background: #f3f4f6;
        padding: 4px 8px;
        border-radius: 6px;
        border: 1px solid #e5e7eb;
        color: #7c3aed;
        font-weight: 600;
        font-size: 0.85rem;
    }

    .pagination-container {
        padding: 16px 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: #f8fafc;
        border-top: 1px solid #e5e7eb;
        flex-wrap: wrap;
        gap: 12px;
    }

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

    [data-bs-theme="dark"] .filter-bar,
    [data-bs-theme="dark"] .pagination-container {
        background: #141122 !important;
        border-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .filter-bar .search-input-group input,
    [data-bs-theme="dark"] .filter-select {
        background: #171426 !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #f3f4f6 !important;
    }

    [data-bs-theme="dark"] .titan-table th {
        background: #141122 !important;
        color: #9ca3af !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table td {
        background: #171426 !important;
        color: #f3f4f6 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .titan-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02) !important;
    }

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

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

    [data-bs-theme="dark"] .code-badge {
        background: rgba(255, 255, 255, 0.05) !important;
        border-color: rgba(255, 255, 255, 0.1) !important;
        color: #a78bfa !important;
    }

    /* Koyu Modda Sayfa Başlığının Görünürlüğü */
    [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"><?= __('Devices', 'Devices') ?></h1>
</div>

<!-- 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>

<!-- Arama ve Tablo Kartı -->
<div class="glass-card">
    <form method="GET" action="devices.php" class="filter-bar">
        <?php if ($filter !== 'all'): ?>
            <input type="hidden" name="filter" value="<?= e($filter) ?>">
        <?php endif; ?>
        <?php if ($perPage !== 25): ?>
            <input type="hidden" name="limit" value="<?= $perPage ?>">
        <?php endif; ?>
        <div class="search-input-group">
            <i class="la la-search"></i>
            <input type="text" name="q" value="<?= e($search) ?>" placeholder="<?= __('Search by Device Name, MAC, or Device Key...', 'Search by Device Name, MAC, or Device Key...') ?>">
        </div>
        
        <!-- Sayfa Başına Kayıt Seçici (Sadece Rakam) -->
        <select name="limit" class="filter-select" onchange="this.form.submit()">
            <option value="25" <?= $perPage === 25 ? 'selected' : '' ?>>25</option>
            <option value="50" <?= $perPage === 50 ? 'selected' : '' ?>>50</option>
            <option value="100" <?= $perPage === 100 ? 'selected' : '' ?>>100</option>
        </select>

        <select name="filter" class="filter-select" onchange="this.form.submit()">
            <option value="all" <?= $filter === 'all' ? 'selected' : '' ?>><?= __('All Devices', 'All Devices') ?></option>
            <option value="active" <?= $filter === 'active' ? 'selected' : '' ?>><?= __('Active Devices', 'Active Devices') ?></option>
            <option value="locked" <?= $filter === 'locked' ? 'selected' : '' ?>><?= __('Locked Devices', 'Locked Devices') ?></option>
            <option value="expired" <?= $filter === 'expired' ? 'selected' : '' ?>><?= __('Expired Subscriptions', 'Expired Subscriptions') ?></option>
        </select>
        <?php if ($search !== '' || $filter !== 'all' || $perPage !== 25): ?>
            <a href="devices.php" class="btn btn-outline-secondary btn-sm"><?= __('Reset', 'Reset') ?></a>
        <?php endif; ?>
    </form>

    <div class="table-responsive">
        <table class="table titan-table">
            <thead>
                <tr>
                    <th style="width: 50px;">#</th>
                    <th><?= __('DEVICE NAME', 'DEVICE NAME') ?></th>
                    <th><?= __('MAC ADDRESS', 'MAC ADDRESS') ?></th>
                    <th><?= __('DEVICE KEY', 'DEVICE KEY') ?></th>
                    <th><?= __('PLAYLISTS', 'PLAYLISTS') ?></th>
                    <th><?= __('SUBSCRIPTION', 'SUBSCRIPTION') ?></th>
                    <th><?= __('STATUS', 'STATUS') ?></th>
                    <th><?= __('LAST ACCESS', 'LAST ACCESS') ?></th>
                    <th class="text-end"><?= __('ACTIONS', 'ACTIONS') ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if (count($devices) === 0): ?>
                    <tr>
                        <td colspan="9" class="text-center text-muted py-4"><?= __('No devices registered yet.', 'No devices registered yet.') ?></td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($devices as $d): ?>
                        <?php 
                        $isLocked = (int) ($d['locked'] ?? 0) === 1;
                        $isRegistered = (int) ($d['registered'] ?? 0) === 1;
                        $name = trim((string) ($d['account_name'] ?? '')) ?: '—';
                        $mac = trim((string) ($d['mac'] ?? '—'));
                        $deviceKey = trim((string) ($d['device_key'] ?? '—'));
                        $lastAccess = trim((string) ($d['last_seen'] ?? ($d['updated_at'] ?? '—')));
                        $expDate = $d['exp_date'] ?? null;
                        $isExpired = $expDate && strtotime($expDate) < time();
                        ?>
                        <tr>
                            <td class="text-muted fw-bold"><?= (int) $d['id'] ?></td>
                            <td><strong><?= e($name) ?></strong></td>
                            <td><span class="code-badge"><?= e($mac) ?></span></td>
                            <td><span class="code-badge" style="color: #6366f1;"><?= e($deviceKey) ?></span></td>
                            <td>
                                <span class="badge bg-purple" style="background: #7c3aed; color: #fff; font-weight: 500; padding: 5px 10px; border-radius: 6px;">
                                    1 playlist
                                </span>
                            </td>
                            <td>
                                <span class="badge bg-secondary" style="background: #6b7280; font-weight: 500; padding: 5px 10px; border-radius: 6px;">
                                    <?= $expDate ? e($expDate) : 'No Expiry' ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($isLocked): ?>
                                    <span class="badge bg-danger" style="background: #ef4444; padding: 6px 12px; border-radius: 6px; font-weight: 600;"><?= __('Locked', 'Locked') ?></span>
                                <?php elseif ($isExpired): ?>
                                    <span class="badge bg-warning text-dark" style="background: #f59e0b; color: #fff !important; padding: 6px 12px; border-radius: 6px; font-weight: 600;"><?= __('Expired', 'Expired') ?></span>
                                <?php elseif ($isRegistered): ?>
                                    <span class="badge bg-success" style="background: #10b981; padding: 6px 12px; border-radius: 6px; font-weight: 600;"><?= __('Activated', 'Activated') ?></span>
                                <?php else: ?>
                                    <span class="badge bg-secondary" style="background: #9ca3af; padding: 6px 12px; border-radius: 6px; font-weight: 600;"><?= __('Not Activated', 'Not Activated') ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="text-muted" style="font-size: 0.85rem;"><?= e($lastAccess) ?></td>
                            <td class="text-end">
                                <a class="btn btn-sm btn-primary py-1 px-2" href="device_edit.php?id=<?= (int) $d['id'] ?>" style="background: #3b82f6; border-color: #3b82f6;">
                                    <i class="la la-edit"></i> <?= __('Edit', 'Edit') ?>
                                </a>
                                <a class="btn btn-sm btn-warning py-1 px-2 text-dark" href="devices.php?action=lock&id=<?= (int) $d['id'] ?>" style="background: #f59e0b; border-color: #f59e0b; color: #fff !important;">
                                    <i class="la la-lock"></i> <?= $isLocked ? __('Unlock', 'Unlock') : __('Lock', 'Lock') ?>
                                </a>
                                <a class="btn btn-sm btn-info py-1 px-2 text-white" href="devices.php?action=deactivate&id=<?= (int) $d['id'] ?>" style="background: #06b6d4; border-color: #06b6d4;">
                                    <i class="la la-bolt"></i> <?= $isRegistered ? __('Deactivate', 'Deactivate') : __('Activate', 'Activate') ?>
                                </a>
                                <a class="btn btn-sm btn-danger py-1 px-2" href="devices.php?action=delete&id=<?= (int) $d['id'] ?>" onclick="return confirm('Silmek istediğinize emin misiniz?');" style="background: #ef4444; border-color: #ef4444;">
                                    <i class="la la-trash"></i> <?= __('Delete', 'Delete') ?>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Sayfalama Alt Barı -->
    <?php if ($totalPages > 1 || $totalFilteredDevices > 25): ?>
        <div class="pagination-container">
            <div class="text-muted" style="font-size: 0.85rem;">
                Toplam <strong><?= $totalFilteredDevices ?></strong> kayıttan <strong><?= $totalFilteredDevices > 0 ? $offset + 1 : 0 ?></strong> - <strong><?= min($offset + $perPage, $totalFilteredDevices) ?></strong> arası gösteriliyor.
            </div>
            <?php if ($totalPages > 1): ?>
                <nav>
                    <ul class="pagination pagination-sm mb-0">
                        <?php 
                        $paginationParams = [];
                        if ($search !== '') $paginationParams['q'] = $search;
                        if ($filter !== 'all') $paginationParams['filter'] = $filter;
                        if ($perPage !== 25) $paginationParams['limit'] = $perPage;
                        ?>
                        <!-- Önceki -->
                        <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                            <?php 
                            $paginationParams['p'] = $page - 1;
                            $prevUrl = 'devices.php?' . http_build_query($paginationParams);
                            ?>
                            <a class="page-link" href="<?= $prevUrl ?>">Önceki</a>
                        </li>

                        <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                            <?php if ($i == 1 || $i == $totalPages || ($i >= $page - 2 && $i <= $page + 2)): ?>
                                <?php 
                                $paginationParams['p'] = $i;
                                $pageUrl = 'devices.php?' . http_build_query($paginationParams);
                                ?>
                                <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                                    <a class="page-link" href="<?= $pageUrl ?>"><?= $i ?></a>
                                </li>
                            <?php elseif ($i == $page - 3 || $i == $page + 3): ?>
                                <li class="page-item disabled"><span class="page-link">...</span></li>
                            <?php endif; ?>
                        <?php endfor; ?>

                        <!-- Sonraki -->
                        <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : '' ?>">
                            <?php 
                            $paginationParams['p'] = $page + 1;
                            $nextUrl = 'devices.php?' . http_build_query($paginationParams);
                            ?>
                            <a class="page-link" href="<?= $nextUrl ?>">Sonraki</a>
                        </li>
                    </ul>
                </nav>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

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