<?php
require_once 'config.php';

// Giriş kontrolü
if (!isset($_SESSION['logged_in'])) {
    header('Location: login.php'); exit;
}

require_once 'db.php';
$db = getDB();

// Lisans oluştur
$newKey = '';
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    if ($_POST['action'] === 'create') {
        $key = generateKey();
        $plan    = $_POST['plan'] ?? 'pro';
        $expiry  = $_POST['expiry'] ?? date('Y-m-d', strtotime('+1 year'));
        $maxDev  = (int)($_POST['max_devices'] ?? 2);
        $note    = trim($_POST['note'] ?? '');
        $stmt = $db->prepare("INSERT INTO licenses (lic_key,plan,expiry,max_devices,note) VALUES (?,?,?,?,?)");
        $stmt->execute([$key,$plan,$expiry,$maxDev,$note]);
        $newKey = $key;
        $msg = 'success';
    }

    if ($_POST['action'] === 'revoke') {
        $db->prepare("UPDATE licenses SET active=0 WHERE lic_key=?")->execute([$_POST['key']]);
        $msg = 'revoked';
    }

    if ($_POST['action'] === 'activate') {
        $db->prepare("UPDATE licenses SET active=1 WHERE lic_key=?")->execute([$_POST['key']]);
        $msg = 'activated';
    }

    if ($_POST['action'] === 'delete') {
        $db->prepare("DELETE FROM licenses WHERE lic_key=?")->execute([$_POST['key']]);
        $msg = 'deleted';
    }

    if ($_POST['action'] === 'reset_devices') {
        $db->prepare("DELETE FROM activations WHERE lic_key=?")->execute([$_POST['key']]);
        $msg = 'reset';
    }
}

// Arama ve filtre
$search  = trim($_GET['q'] ?? '');
$filter  = $_GET['filter'] ?? 'all';
$where   = '1=1';
$params  = [];
if ($search) { $where .= " AND (lic_key LIKE ? OR note LIKE ?)"; $params[] = "%$search%"; $params[] = "%$search%"; }
if ($filter === 'active')   { $where .= " AND active=1 AND expiry >= CURDATE()"; }
if ($filter === 'expired')  { $where .= " AND expiry < CURDATE()"; }
if ($filter === 'revoked')  { $where .= " AND active=0"; }

// Lisanslar
$stmt = $db->prepare("SELECT l.*, (SELECT COUNT(*) FROM activations a WHERE a.lic_key=l.lic_key) as device_count FROM licenses l WHERE $where ORDER BY l.created_at DESC");
$stmt->execute($params);
$licenses = $stmt->fetchAll();

// İstatistikler
$stats = $db->query("SELECT
    COUNT(*) as total,
    SUM(active=1 AND expiry>=CURDATE()) as active_count,
    SUM(expiry<CURDATE()) as expired_count,
    SUM(active=0) as revoked_count
FROM licenses")->fetch();

$totalDevices = $db->query("SELECT COUNT(*) as c FROM activations")->fetch()['c'];
$todayVerify  = $db->query("SELECT COUNT(*) as c FROM verify_logs WHERE DATE(created_at)=CURDATE() AND result='success'")->fetch()['c'];
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UA Changer — Lisans Paneli</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;background:#0A0E1A;color:#F0F4FF;min-height:100vh}
.sidebar{position:fixed;left:0;top:0;bottom:0;width:220px;background:#111827;border-right:1px solid #1E2D45;padding:24px 0;z-index:100}
.sidebar-logo{padding:0 20px 24px;border-bottom:1px solid #1E2D45}
.sidebar-logo .brand{color:#00D4FF;font-size:11px;font-weight:700;letter-spacing:2px}
.sidebar-logo h1{font-size:18px;font-weight:700;margin-top:2px}
.sidebar-nav{padding:16px 0}
.nav-item{display:flex;align-items:center;gap:10px;padding:10px 20px;color:#7B8DB0;text-decoration:none;font-size:14px;transition:.2s}
.nav-item:hover,.nav-item.active{color:#F0F4FF;background:#1A2235}
.nav-item .icon{font-size:16px;width:20px;text-align:center}
.main{margin-left:220px;padding:32px;min-height:100vh}
.page-header{margin-bottom:28px}
.page-header h2{font-size:24px;font-weight:700}
.page-header p{color:#7B8DB0;font-size:14px;margin-top:4px}
.stats-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:14px;margin-bottom:28px}
.stat-card{background:#111827;border:1px solid #1E2D45;border-radius:12px;padding:18px}
.stat-card .label{color:#7B8DB0;font-size:11px;font-weight:700;letter-spacing:1px;text-transform:uppercase}
.stat-card .value{font-size:28px;font-weight:700;margin-top:6px}
.stat-card.green .value{color:#00E676}
.stat-card.blue .value{color:#00D4FF}
.stat-card.red .value{color:#FF4757}
.stat-card.orange .value{color:#FFB300}
.card{background:#111827;border:1px solid #1E2D45;border-radius:12px;padding:24px;margin-bottom:20px}
.card-title{font-size:12px;font-weight:700;letter-spacing:1px;color:#7B8DB0;text-transform:uppercase;margin-bottom:16px}
.form-row{display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end}
.form-group{display:flex;flex-direction:column;gap:6px}
.form-group label{font-size:12px;color:#7B8DB0;font-weight:600}
.form-group input,.form-group select{background:#0A0E1A;border:1px solid #1E2D45;color:#F0F4FF;padding:9px 12px;border-radius:8px;font-size:14px;outline:none}
.form-group input:focus,.form-group select:focus{border-color:#00D4FF}
.btn{padding:9px 18px;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer;border:none;letter-spacing:.5px}
.btn-primary{background:#00D4FF;color:#0A0E1A}
.btn-primary:hover{background:#0099BB}
.btn-danger{background:#FF4757;color:#fff}
.btn-danger:hover{background:#CC3344}
.btn-success{background:#00E676;color:#0A0E1A}
.btn-sm{padding:5px 12px;font-size:12px;border-radius:6px}
.btn-outline{background:transparent;border:1px solid #1E2D45;color:#7B8DB0}
.btn-outline:hover{border-color:#00D4FF;color:#00D4FF}
.alert{padding:12px 16px;border-radius:8px;font-size:14px;margin-bottom:20px;display:flex;align-items:center;gap:8px}
.alert-success{background:#0D2B1A;border:1px solid #00E676;color:#00E676}
.alert-info{background:#0D2233;border:1px solid #00D4FF;color:#00D4FF}
.new-key{font-size:22px;font-weight:700;letter-spacing:3px;font-family:monospace;background:#0A0E1A;padding:12px 20px;border-radius:8px;border:1px solid #00D4FF;color:#00D4FF;cursor:pointer}
.filters{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px;align-items:center}
.filter-btn{padding:6px 14px;border-radius:20px;font-size:12px;font-weight:600;cursor:pointer;border:1px solid #1E2D45;background:transparent;color:#7B8DB0;text-decoration:none}
.filter-btn.active,.filter-btn:hover{border-color:#00D4FF;color:#00D4FF;background:#0D2233}
.search-box{margin-left:auto}
.search-box input{background:#0A0E1A;border:1px solid #1E2D45;color:#F0F4FF;padding:7px 14px;border-radius:20px;font-size:13px;outline:none;width:220px}
.search-box input:focus{border-color:#00D4FF}
table{width:100%;border-collapse:collapse;font-size:14px}
th{text-align:left;padding:10px 12px;color:#7B8DB0;font-size:11px;font-weight:700;letter-spacing:1px;border-bottom:1px solid #1E2D45}
td{padding:12px;border-bottom:1px solid #0F1929;vertical-align:middle}
tr:hover td{background:#0F1929}
.key-cell{font-family:monospace;font-size:13px;font-weight:700;color:#00D4FF;letter-spacing:1px}
.badge{display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:12px;font-size:11px;font-weight:700}
.badge-green{background:#0D2B1A;color:#00E676;border:1px solid #00E676}
.badge-red{background:#2B0D0D;color:#FF4757;border:1px solid #FF4757}
.badge-orange{background:#2B1A00;color:#FFB300;border:1px solid #FFB300}
.badge-gray{background:#1E2D45;color:#7B8DB0}
.actions{display:flex;gap:6px;flex-wrap:wrap}
.copy-btn{background:none;border:none;color:#7B8DB0;cursor:pointer;padding:2px 6px;font-size:12px}
.copy-btn:hover{color:#00D4FF}
.empty{text-align:center;padding:48px;color:#3D4F6E}
.empty .icon{font-size:48px;margin-bottom:12px}
.logout-btn{position:absolute;bottom:20px;left:0;right:0;padding:0 20px}
.logout-btn a{display:flex;align-items:center;gap:8px;padding:10px 16px;color:#FF4757;border:1px solid #2B0D0D;border-radius:8px;text-decoration:none;font-size:13px}
.logout-btn a:hover{background:#2B0D0D}
@media(max-width:768px){.sidebar{display:none}.main{margin-left:0;padding:16px}}
</style>
</head>
<body>

<div class="sidebar">
    <div class="sidebar-logo">
        <div class="brand">⚡ UA CHANGER</div>
        <h1>Lisans Paneli</h1>
    </div>
    <nav class="sidebar-nav">
        <a href="index.php" class="nav-item active"><span class="icon">🏠</span> Panel</a>
        <a href="logs.php" class="nav-item"><span class="icon">📋</span> Loglar</a>
        <a href="https://t.me/enployer" target="_blank" class="nav-item"><span class="icon">✈</span> Telegram</a>
    </nav>
    <div class="logout-btn">
        <a href="login.php?logout=1">🚪 Çıkış Yap</a>
    </div>
</div>

<div class="main">
    <div class="page-header">
        <h2>Lisans Yönetimi</h2>
        <p>UA Changer — <?= date('d.m.Y H:i') ?></p>
    </div>

    <?php if ($newKey): ?>
    <div class="alert alert-success">
        ✅ Yeni lisans oluşturuldu! Müşteriye bu anahtarı gönder:
        <br><br>
        <span class="new-key" onclick="navigator.clipboard.writeText('<?= $newKey ?>');this.innerText='✅ Kopyalandı!'">
            <?= $newKey ?>
        </span>
        <br><small style="color:#7B8DB0;margin-top:6px;display:block">Tıklayarak kopyala</small>
    </div>
    <?php endif; ?>

    <?php if ($msg === 'revoked'): ?>
    <div class="alert alert-info">🚫 Lisans iptal edildi.</div>
    <?php elseif ($msg === 'activated'): ?>
    <div class="alert alert-success">✅ Lisans yeniden aktifleştirildi.</div>
    <?php elseif ($msg === 'reset'): ?>
    <div class="alert alert-info">🔄 Cihazlar sıfırlandı.</div>
    <?php elseif ($msg === 'deleted'): ?>
    <div class="alert alert-info">🗑 Lisans silindi.</div>
    <?php endif; ?>

    <!-- İstatistikler -->
    <div class="stats-grid">
        <div class="stat-card blue">
            <div class="label">Toplam</div>
            <div class="value"><?= $stats['total'] ?></div>
        </div>
        <div class="stat-card green">
            <div class="label">Aktif</div>
            <div class="value"><?= $stats['active_count'] ?></div>
        </div>
        <div class="stat-card orange">
            <div class="label">Süresi Dolmuş</div>
            <div class="value"><?= $stats['expired_count'] ?></div>
        </div>
        <div class="stat-card red">
            <div class="label">İptal</div>
            <div class="value"><?= $stats['revoked_count'] ?></div>
        </div>
        <div class="stat-card blue">
            <div class="label">Aktif Cihazlar</div>
            <div class="value"><?= $totalDevices ?></div>
        </div>
        <div class="stat-card green">
            <div class="label">Bugün Doğrulama</div>
            <div class="value"><?= $todayVerify ?></div>
        </div>
    </div>

    <!-- Yeni Lisans Oluştur -->
    <div class="card">
        <div class="card-title">+ Yeni Lisans Oluştur</div>
        <form method="POST">
            <input type="hidden" name="action" value="create">
            <div class="form-row">
                <div class="form-group">
                    <label>Plan</label>
                    <select name="plan">
                        <option value="pro">Pro</option>
                        <option value="monthly">Aylık</option>
                        <option value="lifetime">Ömür Boyu</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Bitiş Tarihi</label>
                    <input type="date" name="expiry" value="<?= date('Y-m-d', strtotime('+1 year')) ?>">
                </div>
                <div class="form-group">
                    <label>Max Cihaz</label>
                    <select name="max_devices">
                        <option value="1">1</option>
                        <option value="2" selected>2</option>
                        <option value="3">3</option>
                        <option value="5">5</option>
                    </select>
                </div>
                <div class="form-group" style="flex:1;min-width:200px">
                    <label>Not (Müşteri adı)</label>
                    <input type="text" name="note" placeholder="örn: Ahmet K. — Telegram @ahmet">
                </div>
                <button type="submit" class="btn btn-primary">⚡ Oluştur</button>
            </div>
        </form>
    </div>

    <!-- Lisans Listesi -->
    <div class="card">
        <div class="card-title">Tüm Lisanslar (<?= count($licenses) ?>)</div>

        <div class="filters">
            <a href="?filter=all" class="filter-btn <?= $filter==='all'?'active':'' ?>">Tümü</a>
            <a href="?filter=active" class="filter-btn <?= $filter==='active'?'active':'' ?>">✅ Aktif</a>
            <a href="?filter=expired" class="filter-btn <?= $filter==='expired'?'active':'' ?>">⏰ Süresi Dolmuş</a>
            <a href="?filter=revoked" class="filter-btn <?= $filter==='revoked'?'active':'' ?>">🚫 İptal</a>
            <div class="search-box">
                <form method="GET" style="display:inline">
                    <input type="hidden" name="filter" value="<?= htmlspecialchars($filter) ?>">
                    <input type="text" name="q" value="<?= htmlspecialchars($search) ?>" placeholder="🔍 Anahtar veya not ara...">
                </form>
            </div>
        </div>

        <?php if (empty($licenses)): ?>
        <div class="empty">
            <div class="icon">🔑</div>
            <div>Lisans bulunamadı</div>
        </div>
        <?php else: ?>
        <div style="overflow-x:auto">
        <table>
            <thead>
                <tr>
                    <th>ANAHTAR</th>
                    <th>PLAN</th>
                    <th>BİTİŞ</th>
                    <th>CİHAZ</th>
                    <th>DURUM</th>
                    <th>NOT</th>
                    <th>TARİH</th>
                    <th>İŞLEM</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($licenses as $lic):
                $expired  = strtotime($lic['expiry']) < time();
                $revoked  = !$lic['active'];
                $isActive = !$expired && !$revoked;
            ?>
            <tr>
                <td>
                    <span class="key-cell"><?= $lic['lic_key'] ?></span>
                    <button class="copy-btn" onclick="navigator.clipboard.writeText('<?= $lic['lic_key'] ?>');this.innerText='✓'" title="Kopyala">📋</button>
                </td>
                <td><?= htmlspecialchars($lic['plan']) ?></td>
                <td><?= $lic['expiry'] ?></td>
                <td>
                    <span style="color:<?= $lic['device_count']>=$lic['max_devices']?'#FF4757':'#00E676' ?>">
                        <?= $lic['device_count'] ?>/<?= $lic['max_devices'] ?>
                    </span>
                </td>
                <td>
                    <?php if ($revoked): ?>
                        <span class="badge badge-red">🚫 İptal</span>
                    <?php elseif ($expired): ?>
                        <span class="badge badge-orange">⏰ Süresi Dolmuş</span>
                    <?php else: ?>
                        <span class="badge badge-green">✅ Aktif</span>
                    <?php endif; ?>
                </td>
                <td style="color:#7B8DB0;font-size:12px;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                    <?= htmlspecialchars($lic['note'] ?: '—') ?>
                </td>
                <td style="color:#7B8DB0;font-size:12px"><?= date('d.m.Y', strtotime($lic['created_at'])) ?></td>
                <td>
                    <div class="actions">
                        <?php if ($isActive): ?>
                        <form method="POST" style="display:inline">
                            <input type="hidden" name="action" value="revoke">
                            <input type="hidden" name="key" value="<?= $lic['lic_key'] ?>">
                            <button class="btn btn-sm btn-danger" title="İptal et">🚫</button>
                        </form>
                        <?php else: ?>
                        <form method="POST" style="display:inline">
                            <input type="hidden" name="action" value="activate">
                            <input type="hidden" name="key" value="<?= $lic['lic_key'] ?>">
                            <button class="btn btn-sm btn-success" title="Aktifleştir">✅</button>
                        </form>
                        <?php endif; ?>
                        <form method="POST" style="display:inline">
                            <input type="hidden" name="action" value="reset_devices">
                            <input type="hidden" name="key" value="<?= $lic['lic_key'] ?>">
                            <button class="btn btn-sm btn-outline" title="Cihazları sıfırla">🔄</button>
                        </form>
                        <form method="POST" style="display:inline" onsubmit="return confirm('Bu lisansı silmek istediğine emin misin?')">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="key" value="<?= $lic['lic_key'] ?>">
                            <button class="btn btn-sm btn-outline" title="Sil">🗑</button>
                        </form>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
