<?php
/**
 * activate.php — Activation by MAC with Nxs Panel dynamic light/dark style.
 */

declare(strict_types=1);

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

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/device.php';
require_once __DIR__ . '/lib/settings.php';
require_once __DIR__ . '/lib/i18n.php'; // Çoklu dil desteği

require_login();

$pdo       = db();
$flash     = '';
$flashType = 'ok';
$doneId    = 0;
$doneKey   = '';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    csrf_check();

    $mac       = normalize_mac((string) ($_POST['mac'] ?? ''));
    $name      = trim((string) ($_POST['name'] ?? '')) ?: 'Playlist 1';
    $type      = ($_POST['type'] ?? 'xtream') === 'm3u' ? 'm3u' : 'xtream';
    $dnsId     = (int) ($_POST['dns'] ?? 0);
    $username  = trim((string) ($_POST['username'] ?? ''));
    $password  = trim((string) ($_POST['password'] ?? ''));
    $m3u       = trim((string) ($_POST['m3u'] ?? ''));
    
    $protected = isset($_POST['protected']) ? 1 : 0;

    // Validation
    if ($mac === null) {
        $flash = __('invalid_mac', 'Invalid MAC address. Use the format AA:BB:CC:DD:EE:FF (as shown in the app).');
        $flashType = 'err';
    } else {
        $url = '';
        if ($type === 'm3u') {
            if ($m3u === '') {
                $flash = __('m3u_missing', 'M3U URL is missing.');
                $flashType = 'err';
            } else {
                $url = $m3u;
                $username = '';
                $password = '';
            }
        } else {
            $dnsUrl = '';
            $st = $pdo->prepare('SELECT url FROM dns WHERE id = ?');
            $st->execute([$dnsId]);
            $dnsUrl = (string) ($st->fetchColumn() ?: '');
            if ($dnsUrl === '' || $username === '' || $password === '') {
                $flash = __('dns_credentials_missing', 'Select a DNS and fill in both username and password.');
                $flashType = 'err';
            } else {
                $url = $dnsUrl;
            }
        }

        if ($flash === '') {
            try {
                $pdo->beginTransaction();

                $dev = device_find_by_mac($mac);
                if ($dev === null) {
                    $dev = device_create($mac, $name, null, null);
                }
                $devId = (int) $dev['id'];

                $pdo->prepare('UPDATE devices SET registered = 1, locked = 0, sub_trial = 0, account_name = ? WHERE id = ?')
                    ->execute([$name, $devId]);

                $dup = $pdo->prepare('SELECT id FROM playlists WHERE device_id = ? AND url = ? AND username = ?');
                $dup->execute([$devId, $url, $username]);
                if ($dup->fetchColumn() === false) {
                    $sort = (int) $pdo->query('SELECT COALESCE(MAX(sort),-1)+1 FROM playlists WHERE device_id = ' . $devId)->fetchColumn();
                    $pdo->prepare(
                        'INSERT INTO playlists (device_id, name, type, url, username, password, protected, sort)
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
                    )->execute([$devId, $name, $type, $url, $username, $password, $protected, $sort]);
                }

                $pdo->commit();
                $doneId  = $devId;
                $doneKey = (string) ($dev['device_key'] ?? '');
                $flash   = __('activation_success', 'Device activated and playlist assigned. Reopen the app (or Sports/Home section) to receive the list.');
            } catch (Throwable $ex) {
                if ($pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                $flash = __('activation_error', 'Activation error: ') . $ex->getMessage();
                $flashType = 'err';
            }
        }
    }
}

$dnsList = $pdo->query('SELECT id, title, url FROM dns ORDER BY title ASC, id ASC')->fetchAll();

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

<!-- APPVISION Panel Dynamic Theme Stilleri (Light & Dark Uyumlu) -->
<style>
    .glass-card {
        background: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02);
        margin-bottom: 24px;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header {
        padding: 16px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f8fafc;
        transition: background 0.3s ease, border-color 0.3s ease;
    }

    .glass-card-header h2 {
        margin: 0;
        font-size: 15px;
        font-weight: 700;
        color: #111827;
    }

    .glass-card-body {
        padding: 24px;
    }

    .glass-input, .glass-select {
        background: #f9fafb !important;
        border: 1px solid #d1d5db !important;
        color: #111827 !important;
        border-radius: 10px !important;
        padding: 11px 16px !important;
        font-size: 14px !important;
        transition: all 0.25s ease !important;
    }

    .glass-input:focus, .glass-select:focus {
        border-color: #7c3aed !important;
        box-shadow: 0 0 10px rgba(124, 58, 237, 0.2) !important;
        background: #ffffff !important;
    }

    .btn-activate {
        background: #7c3aed;
        border: none;
        color: #fff;
        padding: 12px 30px;
        border-radius: 10px;
        font-weight: 600;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s ease;
        box-shadow: 0 4px 12px rgba(124, 58, 237, 0.25);
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-activate:hover {
        background: #6d28d9;
        color: #fff;
        transform: translateY(-1px);
    }

    .glass-alert-success {
        background: #ecfdf5;
        border: 1px solid #a7f3d0;
        color: #059669;
        border-radius: 12px;
        padding: 14px 20px;
    }

    .glass-alert-danger {
        background: #fef2f2;
        border: 1px solid #fecaca;
        color: #dc2626;
        border-radius: 12px;
        padding: 14px 20px;
    }

    .mono-input {
        font-family: monospace;
        letter-spacing: 0.5px;
        color: #7c3aed !important;
        font-weight: 600;
    }

    /* --- Dark Mode (Koyu Tema) Uyarlamaları --- */
    [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"] .glass-card-header {
        background: #141122 !important;
        border-bottom-color: rgba(255, 255, 255, 0.08) !important;
    }

    [data-bs-theme="dark"] .glass-card-header h2 {
        color: #f3f4f6 !important;
    }

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

    [data-bs-theme="dark"] .glass-input:focus, 
    [data-bs-theme="dark"] .glass-select:focus {
        background: #171426 !important;
        border-color: #7c3aed !important;
    }

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

    [data-bs-theme="dark"] .mono-input {
        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"><?= __('activate_mac', 'Activate by MAC') ?></h1>
    <a class="btn btn-sm btn-outline-secondary" href="devices.php">
        <i class="la la-tv"></i> <?= __('devices', 'Devices') ?>
    </a>
</div>

<?php if ($flash !== ''): ?>
    <div class="mb-4 <?= $flashType === 'ok' ? 'glass-alert-success' : 'glass-alert-danger' ?>" role="alert">
        <?= e($flash) ?>
        <?php if ($doneId > 0): ?>
            · <a href="device_edit.php?id=<?= $doneId ?>" class="text-decoration-underline fw-bold" style="color: inherit;"><?= __('view_device', 'View device') ?></a><?= $doneKey !== '' ? ' (' . e($doneKey) . ')' : '' ?>
        <?php endif; ?>
    </div>
<?php endif; ?>

<form method="post" autocomplete="off">
    <?= csrf_field() ?>
    
    <!-- Client Card -->
    <div class="glass-card">
        <div class="glass-card-header">
            <h2><?= __('client', 'Client') ?></h2>
        </div>
        <div class="glass-card-body">
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('client_mac', 'Client MAC') ?></label>
                    <input type="text" name="mac" class="form-control glass-input mono-input" placeholder="AA:BB:CC:DD:EE:FF"
                           value="<?= e((string) ($_POST['mac'] ?? '')) ?>" required>
                    <div class="form-text text-muted fs-7 mt-1"><?= __('mac_hint', 'As displayed on the app screen.') ?></div>
                </div>
                <div class="col-md-6">
                    <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('playlist_name', 'Playlist Name / Device Name') ?></label>
                    <input type="text" name="name" class="form-control glass-input" placeholder="e.g. Living Room TV"
                           value="<?= e((string) ($_POST['name'] ?? '')) ?>">
                </div>
            </div>
        </div>
    </div>

    <!-- Playlist Card -->
    <div class="glass-card">
        <div class="glass-card-header">
            <h2><?= __('playlist', 'Playlist') ?></h2>
        </div>
        <div class="glass-card-body">
            <div class="mb-3">
                <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('type', 'Type') ?></label>
                <select name="type" class="form-select glass-select" id="type">
                    <option value="xtream"><?= __('xtream_desc', 'Xtream (DNS + username/password)') ?></option>
                    <option value="m3u"><?= __('m3u_desc', 'M3U (Direct URL)') ?></option>
                </select>
            </div>

            <div id="xtream-fields">
                <div class="mb-3">
                    <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('dns_server', 'DNS / Server') ?></label>
                    <select name="dns" class="form-select glass-select">
                        <option value="0">— <?= __('choose_dns', 'Choose DNS') ?> —</option>
                        <?php foreach ($dnsList as $d): ?>
                            <option value="<?= (int) $d['id'] ?>"><?= e($d['title']) ?> · <?= e($d['url']) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php if (!$dnsList): ?>
                        <div class="form-text text-warning mt-1"><?= __('no_dns_found', 'No DNS entries found. Add one in') ?> <a href="dns.php" class="text-warning text-decoration-underline">DNS</a>.</div>
                    <?php endif; ?>
                </div>
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('username', 'Username') ?></label>
                        <input type="text" name="username" class="form-control glass-input" value="<?= e((string) ($_POST['username'] ?? '')) ?>">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('password', 'Password') ?></label>
                        <input type="text" name="password" class="form-control glass-input" value="<?= e((string) ($_POST['password'] ?? '')) ?>">
                    </div>
                </div>
            </div>

            <div id="m3u-fields" style="display:none">
                <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('m3u_url', 'M3U URL') ?></label>
                <input type="text" name="m3u" class="form-control glass-input mono-input" placeholder="http://host/playlist.m3u"
                       value="<?= e((string) ($_POST['m3u'] ?? '')) ?>">
            </div>

            <div class="form-check mt-3 pt-2">
                <input class="form-check-input" type="checkbox" name="protected" value="1" id="prot">
                <label class="form-check-label text-muted fs-7 ms-1" for="prot">
                    <?= __('protect_playlist', 'Protect playlist (hides credentials from client)') ?>
                </label>
            </div>
        </div>
    </div>

    <button type="submit" class="btn-activate mb-4">
        <i class="la la-bolt"></i> <?= __('activate', 'Activate') ?>
    </button>
</form>

<script>
(function () {
    var t = document.getElementById('type'), 
        x = document.getElementById('xtream-fields'), 
        m = document.getElementById('m3u-fields');

    function upd() { 
        var isM3u = t.value === 'm3u'; 
        x.style.display = isM3u ? 'none' : ''; 
        m.style.display = isM3u ? '' : 'none'; 
    }
    t.addEventListener('change', upd); 
    upd();

    var macInput = document.querySelector('input[name="mac"]');
    if (macInput) {
        macInput.addEventListener('input', function (e) {
            var val = e.target.value.replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
            if (val.length > 12) {
                val = val.substring(0, 12);
            }
            var parts = val.match(/.{1,2}/g);
            e.target.value = parts ? parts.join(':') : '';
        });
    }
})();
</script>

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