<?php
// Hata raporlama
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require_once 'lib/db.php';

$macInput = isset($_GET['mac']) ? trim((string)$_GET['mac']) : '';

// 1. MAC / Device Key Dönüştürme
if ($macInput !== '' && (strpos($macInput, 'IBO-') === 0 || !preg_match('/^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/', $macInput))) {
    try {
        $stmt = db()->prepare('SELECT mac FROM devices WHERE device_key = ? LIMIT 1');
        $stmt->execute([$macInput]);
        $foundMac = $stmt->fetchColumn();
        if ($foundMac) {
            $macInput = (string) $foundMac;
        }
    } catch (Throwable $e) {}
}

// 2. Veritabanından Tüm DNS Sunucularını Çekme
$dnsList = [];
try {
    $dnsStmt = db()->query('SELECT id, title FROM dns ORDER BY id ASC');
    if ($dnsStmt) {
        $dnsList = $dnsStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
} catch (Throwable $e) {}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NXS ULTIMATE - Playlist Activate</title>
    <!-- Modern Font Yüklemesi -->
    <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=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        :root {
            --primary: #7c3aed;
            --primary-hover: #6d28d9;
            --bg-dark: #090714;
            --card-bg: rgba(23, 20, 38, 0.6);
            --border-color: rgba(255, 255, 255, 0.08);
            --input-bg: rgba(255, 255, 255, 0.04);
            --input-focus: rgba(124, 58, 237, 0.4);
            --text-main: #f3f4f6;
            --text-muted: #9ca3af;
        }

        * { box-sizing: border-box; }

        body { 
            background-color: var(--bg-dark); 
            color: var(--text-main); 
            font-family: 'Plus Jakarta Sans', sans-serif; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            min-height: 100vh; 
            margin: 0; 
            padding: 20px; 
            position: relative;
            overflow-x: hidden;
        }

        /* Arka Plan Ambient Glow (Ortalanmış Işık Küreleri) */
        .glow-1 {
            position: absolute;
            width: 450px;
            height: 450px;
            background: radial-gradient(circle, rgba(124, 58, 237, 0.3) 0%, rgba(0,0,0,0) 70%);
            top: 45%;
            left: 50%;
            transform: translate(-80%, -50%);
            z-index: 0;
            pointer-events: none;
            filter: blur(40px);
        }

        .glow-2 {
            position: absolute;
            width: 400px;
            height: 400px;
            background: radial-gradient(circle, rgba(99, 102, 241, 0.22) 0%, rgba(0,0,0,0) 70%);
            top: 55%;
            left: 50%;
            transform: translate(-20%, -40%);
            z-index: 0;
            pointer-events: none;
            filter: blur(40px);
        }

        /* Glassmorphism Kart Yapısı */
        .card { 
            position: relative;
            z-index: 1;
            background: var(--card-bg); 
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: 24px; 
            padding: 36px 32px; 
            width: 100%; 
            max-width: 420px; 
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5), inset 0 1px 0 rgba(255, 255, 255, 0.1); 
            border: 1px solid var(--border-color); 
            overflow: hidden;
        }

        /* Kartın Üstüne İnce Parlayan Çizgi (Accent Line) */
        .card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
            background: linear-gradient(90deg, #7c3aed, #6366f1, #3b82f6);
        }

        .logo { 
            width: 54px; 
            height: 54px; 
            background: linear-gradient(135deg, #8b5cf6, #6366f1); 
            border-radius: 16px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            font-size: 26px; 
            font-weight: 700; 
            margin: 0 auto 16px; 
            box-shadow: 0 8px 20px rgba(124, 58, 237, 0.35);
        }

        h2 { text-align: center; margin: 0 0 6px; font-size: 22px; font-weight: 700; letter-spacing: -0.5px; }
        p.subtitle { text-align: center; color: var(--text-muted); font-size: 13px; margin-bottom: 24px; font-weight: 400; }
        
        .form-group { margin-bottom: 16px; }
        label { font-size: 12px; color: #d1d5db; display: block; margin-bottom: 8px; font-weight: 500; }
        
        /* Input Konteyner Yapısı (İkon Yerleşimi İçin) */
        .input-wrapper {
            position: relative;
            display: flex;
            align-items: center;
        }

        /* Modern Input ve Select Stilleri */
        input, select { 
            width: 100%; 
            padding: 13px 16px; 
            background: var(--input-bg); 
            border: 1px solid var(--border-color); 
            border-radius: 12px; 
            color: #fff; 
            font-size: 14px; 
            outline: none; 
            transition: all 0.25s ease;
            font-family: inherit;
        }

        .input-wrapper input {
            padding-right: 42px;
        }

        /* İkon İçi Butonlar (Paste & Password Eye) */
        .input-icon-btn {
            position: absolute;
            right: 12px;
            background: none;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            padding: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: color 0.2s;
            box-shadow: none !important;
            margin: 0 !important;
            width: auto !important;
        }

        .input-icon-btn:hover {
            color: #fff;
            background: none !important;
            transform: none !important;
        }

        select option {
            background-color: #141122;
            color: #fff;
        }

        input:focus, select:focus { 
            border-color: var(--primary); 
            background: rgba(255, 255, 255, 0.07);
            box-shadow: 0 0 0 4px var(--input-focus);
        }

        /* Tarayıcı Otomatik Doldurma (Autofill) Beyazlığını Engelleme */
        input:-webkit-autofill,
        input:-webkit-autofill:hover, 
        input:-webkit-autofill:focus, 
        input:-webkit-autofill:active {
            -webkit-background-clip: text;
            -webkit-text-fill-color: #ffffff !important;
            transition: background-color 5000s ease-in-out 0s;
            box-shadow: inset 0 0 20px 20px rgba(255, 255, 255, 0.05) !important;
        }

        .row { display: flex; gap: 12px; }

        /* Ana Gönder Butonu Tasarımı */
        button#btnSubmit { 
            width: 100%; 
            padding: 15px; 
            background: linear-gradient(135deg, #7c3aed, #6366f1); 
            border: none; 
            border-radius: 12px; 
            color: #fff; 
            font-weight: 600; 
            font-size: 14px; 
            cursor: pointer; 
            margin-top: 10px; 
            transition: all 0.25s ease; 
            box-shadow: 0 6px 20px rgba(124, 58, 237, 0.3);
            letter-spacing: 0.5px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        button#btnSubmit:hover { 
            transform: translateY(-1px);
            box-shadow: 0 8px 25px rgba(124, 58, 237, 0.45);
            background: linear-gradient(135deg, #8b5cf6, #4f46e5);
        }

        button#btnSubmit:active {
            transform: translateY(0);
        }

        button#btnSubmit:disabled {
            opacity: 0.75;
            cursor: not-allowed;
            transform: none;
        }

        /* Yükleniyor (Spinner) Animasyonu */
        .spinner {
            width: 18px;
            height: 18px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 0.8s linear infinite;
            display: none;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        #message { margin-top: 18px; text-align: center; font-size: 13px; font-weight: 500; }
    </style>
</head>
<body>

<!-- Ambient Arka Plan Işıkları -->
<div class="glow-1"></div>
<div class="glow-2"></div>

<div class="card">
    <div class="logo">L</div>
    <h2>LEGENDS ULTIMATE</h2>
    <p class="subtitle">Activate your playlist in seconds</p>

    <form id="playlistForm" autocomplete="off">
        <div class="form-group">
            <label>Device MAC Address</label>
            <div class="input-wrapper">
                <input type="text" id="mac" value="<?= htmlspecialchars($macInput, ENT_QUOTES, 'UTF-8') ?>" placeholder="D0:E5:52:D6:0C:5B" required>
                <button type="button" class="input-icon-btn" id="btnPaste" title="Paste MAC">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"></path><rect x="8" y="2" width="8" height="4" rx="1" ry="1"></rect></svg>
                </button>
            </div>
        </div>
        
        <div class="form-group">
            <label>Playlist name</label>
            <input type="text" id="name" placeholder="My playlist" value="My playlist" required>
        </div>

        <div class="form-group">
            <label>Playlist type</label>
            <select id="type">
                <option value="xtream">Xtream Codes</option>
                <option value="m3u">M3U URL</option>
            </select>
        </div>

        <!-- Maskelenmiş Sunucu Seçimi -->
        <div class="form-group">
            <label>Server Location / Line</label>
            <select id="dns_id">
                <?php if (!empty($dnsList)): ?>
                    <?php foreach ($dnsList as $dns): ?>
                        <?php $dnsTitle = !empty($dns['title']) ? $dns['title'] : ('Server ' . $dns['id']); ?>
                        <option value="<?= (int)$dns['id'] ?>">
                            <?= htmlspecialchars((string)$dnsTitle, ENT_QUOTES, 'UTF-8') ?>
                        </option>
                    <?php endforeach; ?>
                <?php else: ?>
                    <option value="">No Server Available</option>
                <?php endif; ?>
            </select>
        </div>

        <!-- Xtream Codes Alanları -->
        <div id="xtreamFields">
            <div class="row">
                <div class="form-group" style="flex:1;">
                    <label>Username</label>
                    <input type="text" id="username" placeholder="admin" autocomplete="new-password">
                </div>
                <div class="form-group" style="flex:1;">
                    <label>Password</label>
                    <div class="input-wrapper">
                        <input type="password" id="password" placeholder="••••••••" autocomplete="new-password">
                        <button type="button" class="input-icon-btn" id="btnTogglePass" title="Toggle Password">
                            <svg id="eyeIcon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></svg>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- M3U Playlist URL Alanı -->
        <div id="m3uFields" style="display: none;">
            <div class="form-group">
                <label>M3U Playlist URL (Optional if server selected)</label>
                <input type="text" id="m3u_url" placeholder="http://example.com/playlist.m3u">
            </div>
        </div>

        <button type="submit" id="btnSubmit">
            <div class="spinner" id="btnSpinner"></div>
            <span id="btnText">ACTIVATE PLAYLIST</span>
        </button>
    </form>
    
    <div id="message"></div>
</div>

<script>
const typeSelect = document.getElementById('type');
const xtreamFields = document.getElementById('xtreamFields');
const m3uFields = document.getElementById('m3uFields');

typeSelect.addEventListener('change', function() {
    if (this.value === 'm3u') {
        xtreamFields.style.display = 'none';
        m3uFields.style.display = 'block';
    } else {
        xtreamFields.style.display = 'block';
        m3uFields.style.display = 'none';
    }
});

// MAC Yapıştırma Fonksiyonu
document.getElementById('btnPaste').addEventListener('click', async function() {
    try {
        const text = await navigator.clipboard.readText();
        if (text) {
            document.getElementById('mac').value = text.trim();
        }
    } catch (err) {
        alert('Please allow clipboard permission or paste manually.');
    }
});

// Şifre Göster / Gizle Fonksiyonu
const passInput = document.getElementById('password');
const btnTogglePass = document.getElementById('btnTogglePass');
const eyeIcon = document.getElementById('eyeIcon');

btnTogglePass.addEventListener('click', function() {
    if (passInput.type === 'password') {
        passInput.type = 'text';
        eyeIcon.innerHTML = '<path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" y1="1" x2="23" y2="23"></line>';
    } else {
        passInput.type = 'password';
        eyeIcon.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle>';
    }
});

// Form Gönderim Dinamiği
document.getElementById('playlistForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const msg = document.getElementById('message');
    const btn = document.getElementById('btnSubmit');
    const spinner = document.getElementById('btnSpinner');
    const btnText = document.getElementById('btnText');
    
    msg.style.color = '#9ca3af';
    msg.innerText = '';
    
    // UI Yükleniyor Durumu
    btn.disabled = true;
    spinner.style.display = 'block';
    btnText.innerText = 'PROCESSING...';

    const playlistType = typeSelect.value;
    const playlistName = document.getElementById('name').value.trim() || 'My playlist';
    const selectedDnsId = document.getElementById('dns_id').value;

    let targetUrlOrId = '';
    let userVal = '';
    let passVal = '';

    if (playlistType === 'm3u') {
        const inputM3u = document.getElementById('m3u_url').value.trim();
        if (inputM3u.startsWith('http://') || inputM3u.startsWith('https://')) {
            targetUrlOrId = inputM3u;
        } else if (inputM3u !== '') {
            targetUrlOrId = selectedDnsId + '|' + inputM3u;
        } else {
            targetUrlOrId = selectedDnsId;
        }
    } else {
        targetUrlOrId = selectedDnsId;
        userVal = document.getElementById('username').value.trim();
        passVal = document.getElementById('password').value.trim();
    }

    const payload = {
        mac: document.getElementById('mac').value.trim(),
        name: playlistName,
        type: playlistType,
        url: targetUrlOrId,
        username: userVal,
        password: passVal,
        playlist_id: 0
    };

    try {
        const response = await fetch('/nxsglass/api/device/playlist_add.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(payload)
        });

        const result = await response.json();

        if (result.ok) {
            msg.style.color = '#4ade80';
            msg.innerText = '✓ Playlist loaded successfully! You can return to your app.';
        } else {
            msg.style.color = '#f87171';
            msg.innerText = 'Error: ' + (result.error || 'Operation failed');
        }
    } catch (err) {
        msg.style.color = '#f87171';
        msg.innerText = 'An error occurred while connecting to the server.';
    } finally {
        btn.disabled = false;
        spinner.style.display = 'none';
        btnText.innerText = 'ACTIVATE PLAYLIST';
    }
});
</script>

</body>
</html>