<?php
require __DIR__ . '/lib/bootstrap.php';
$mac = normalize_mac($_GET['mac'] ?? '');
$device = $mac ? get_or_create_device($mac) : null;
$playlists = $device ? get_device_playlists((int) $device['id']) : [];
$access = $device ? device_access($device) : ['allowed' => false, 'reason' => 'missing'];
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>لوحة الجهاز | IPTV Player</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <main class="dashboard">
        <section class="panel wide">
            <h1>لوحة الجهاز</h1>
            <?php if (!$device): ?>
                <p>ادخل بعنوان MAC من صفحة تسجيل الدخول.</p>
            <?php else: ?>
                <p class="mac"><?= htmlspecialchars($device['mac'], ENT_QUOTES, 'UTF-8') ?></p>
                <div class="status-grid">
                    <span>حالة التجربة: <?= htmlspecialchars($access['reason'], ENT_QUOTES, 'UTF-8') ?></span>
                    <span>نهاية التجربة: <?= htmlspecialchars($device['trial_ends_at'], ENT_QUOTES, 'UTF-8') ?></span>
                    <span>التفعيل المدفوع: <?= htmlspecialchars($device['active_until'] ?: 'غير مفعل', ENT_QUOTES, 'UTF-8') ?></span>
                </div>

                <section class="playlist-list">
                    <h2>قوائم IPTV</h2>
                    <?php if (!$playlists): ?>
                        <p>لا توجد قوائم محفوظة.</p>
                    <?php endif; ?>
                    <?php foreach ($playlists as $savedPlaylist): ?>
                        <div class="playlist-item">
                            <label>
                                <input class="playlist-enabled" name="active_playlist" type="radio" data-id="<?= (int) $savedPlaylist['id'] ?>" <?= !empty($savedPlaylist['enabled']) ? 'checked' : '' ?>>
                                <?= htmlspecialchars($savedPlaylist['playlist_name'] ?? 'Main IPTV', ENT_QUOTES, 'UTF-8') ?>
                            </label>
                            <small class="ltr"><?= htmlspecialchars(generated_playlist_url($savedPlaylist), ENT_QUOTES, 'UTF-8') ?></small>
                            <button class="playlist-delete" type="button" data-id="<?= (int) $savedPlaylist['id'] ?>">حذف</button>
                        </div>
                    <?php endforeach; ?>
                </section>

                <form id="playlistForm" class="playlist-form">
                    <input type="hidden" name="mac" value="<?= htmlspecialchars($device['mac'], ENT_QUOTES, 'UTF-8') ?>">
                    <label>اسم القائمة</label>
                    <input name="name" placeholder="Main IPTV">
                    <label>نوع القائمة</label>
                    <select name="type" id="playlistType">
                        <option value="m3u">M3U URL</option>
                        <option value="xtream">Xtream Codes</option>
                    </select>
                    <label>M3U URL</label>
                    <input name="playlist_url" placeholder="https://example.com/list.m3u">
                    <label>Server URL</label>
                    <input name="server_url" placeholder="http://example.com:8080">
                    <label>Username</label>
                    <input name="username">
                    <label>Password</label>
                    <input name="password" type="password">
                    <label hidden>
                        <input name="enabled" type="hidden" value="1">
                        تفعيل هذه القائمة
                    </label>
                    <button type="submit">حفظ قائمة التشغيل</button>
                    <p id="playlistMessage"></p>
                </form>

                <button id="payButton" class="pay-button" type="button">تفعيل بواسطة Stripe</button>
            <?php endif; ?>
        </section>
    </main>
    <?php if ($device): ?>
    <script>
    function submitPlaylistPayload(payload) {
        return fetch("api/playlist.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(payload)
        }).then(function (response) {
            return response.json();
        });
    }

    document.getElementById("playlistForm").addEventListener("submit", function (event) {
        event.preventDefault();
        var form = event.currentTarget;
        var data = {
            mac: form.mac.value,
            name: form.name.value,
            type: form.type.value,
            playlist_url: form.playlist_url.value,
            server_url: form.server_url.value,
            username: form.username.value,
            password: form.password.value,
            enabled: true
        };
        submitPlaylistPayload(data).then(function (json) {
            document.getElementById("playlistMessage").textContent = json.ok ? "تم الحفظ" : (json.error || "حدث خطأ");
            if (json.ok) {
                window.location.reload();
            }
        }).catch(function () {
            document.getElementById("playlistMessage").textContent = "تعذر الاتصال بالسيرفر";
        });
    });
    Array.prototype.slice.call(document.querySelectorAll(".playlist-enabled")).forEach(function (checkbox) {
        checkbox.addEventListener("change", function () {
            var playlists = <?= json_encode(public_playlists_payload($playlists), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
            playlists.forEach(function (playlist) {
                playlist.enabled = String(playlist.id) === String(checkbox.getAttribute("data-id"));
            });
            submitPlaylistPayload({ mac: <?= json_encode($device['mac']) ?>, action: "save_many", playlists: playlists })
                .then(function () { window.location.reload(); });
        });
    });

    Array.prototype.slice.call(document.querySelectorAll(".playlist-delete")).forEach(function (button) {
        button.addEventListener("click", function () {
            submitPlaylistPayload({ mac: <?= json_encode($device['mac']) ?>, action: "delete", id: button.getAttribute("data-id") })
                .then(function () { window.location.reload(); });
        });
    });

    document.getElementById("payButton").addEventListener("click", function () {
        fetch("api/create_checkout.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ mac: <?= json_encode($device['mac']) ?> })
        }).then(function (response) {
            return response.json();
        }).then(function (json) {
            if (json.ok && json.checkout_url) {
                window.location.href = json.checkout_url;
            } else {
                alert(json.error || "تعذر فتح صفحة الدفع");
            }
        });
    });
    </script>
    <?php endif; ?>
</body>
</html>
