<?php
declare(strict_types=1);
require __DIR__ . '/lib/bootstrap.php';

session_set_cookie_params(['httponly' => true, 'secure' => is_https(), 'samesite' => 'Strict', 'path' => '/']);
session_start();

$token = trim((string) ($_GET['token'] ?? $_POST['token'] ?? ''));
$verified = verify_signed_token($token, 'portal');
if (!$verified) {
    http_response_code(401);
    exit('This customer link is invalid or expired. Open My Account from the TV app again.');
}
$stmt = db()->prepare('SELECT * FROM devices WHERE id = ? LIMIT 1');
$stmt->execute([$verified['device_id']]);
$device = $stmt->fetch();
if (!$device) {
    http_response_code(404);
    exit('Device not found.');
}

$message = '';
$maxPlaylists = max(1, (int) config('app.max_playlists', 10));
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    verify_csrf();
    $action = (string) ($_POST['action'] ?? '');
    if ($action === 'delete') {
        $playlistId = max(0, (int) ($_POST['playlist_id'] ?? 0));
        $pdo = db();
        $lookup = $pdo->prepare('SELECT enabled FROM playlists WHERE id = ? AND device_id = ?');
        $lookup->execute([$playlistId, (int) $device['id']]);
        $existing = $lookup->fetch();
        if (!$existing) {
            $message = 'القائمة غير موجودة.';
        } else {
            $pdo->beginTransaction();
            try {
                $pdo->prepare('DELETE FROM playlists WHERE id = ? AND device_id = ?')->execute([$playlistId, (int) $device['id']]);
                if (!empty($existing['enabled'])) {
                    $pdo->prepare('UPDATE playlists SET enabled = 1 WHERE device_id = ? ORDER BY id ASC LIMIT 1')->execute([(int) $device['id']]);
                }
                $pdo->commit();
            } catch (Throwable $error) {
                $pdo->rollBack();
                throw $error;
            }
            audit_log('portal.playlist_deleted', (int) $device['id'], ['playlist_id' => $playlistId]);
            $message = 'تم حذف القائمة.';
        }
    } elseif ($action === 'activate') {
        $playlistId = max(0, (int) ($_POST['playlist_id'] ?? 0));
        $pdo = db();
        $lookup = $pdo->prepare('SELECT 1 FROM playlists WHERE id = ? AND device_id = ?');
        $lookup->execute([$playlistId, (int) $device['id']]);
        if (!$lookup->fetchColumn()) {
            $message = 'القائمة غير موجودة.';
        } else {
            $pdo->beginTransaction();
            try {
                $pdo->prepare('UPDATE playlists SET enabled = 0 WHERE device_id = ?')->execute([(int) $device['id']]);
                $pdo->prepare('UPDATE playlists SET enabled = 1 WHERE id = ? AND device_id = ?')->execute([$playlistId, (int) $device['id']]);
                $pdo->commit();
            } catch (Throwable $error) {
                $pdo->rollBack();
                throw $error;
            }
            audit_log('portal.playlist_activated', (int) $device['id'], ['playlist_id' => $playlistId]);
            $message = 'تم تفعيل القائمة.';
        }
    } elseif ($action === 'save') {
        $type = strtolower(trim((string) ($_POST['type'] ?? 'm3u')));
        $name = truncate_text(trim((string) ($_POST['name'] ?? 'Main IPTV')), 255) ?: 'Main IPTV';
        $playlistUrl = trim((string) ($_POST['playlist_url'] ?? ''));
        $serverUrl = rtrim(trim((string) ($_POST['server_url'] ?? '')), '/');
        $epgUrl = trim((string) ($_POST['epg_url'] ?? ''));
        $countStmt = db()->prepare('SELECT COUNT(*) FROM playlists WHERE device_id = ?');
        $countStmt->execute([(int) $device['id']]);
        if ((int) $countStmt->fetchColumn() >= $maxPlaylists) {
            $message = 'وصلت إلى الحد الأقصى للقوائم.';
        } elseif (!in_array($type, ['m3u', 'xtream'], true) || ($type === 'm3u' && !filter_var($playlistUrl, FILTER_VALIDATE_URL)) ||
            ($type === 'xtream' && (!filter_var($serverUrl, FILTER_VALIDATE_URL) || trim((string) ($_POST['username'] ?? '')) === '' || trim((string) ($_POST['password'] ?? '')) === '')) ||
            ($epgUrl !== '' && !filter_var($epgUrl, FILTER_VALIDATE_URL))) {
            $message = 'تحقق من بيانات القائمة والروابط.';
        } else {
            $pdo = db();
            $pdo->beginTransaction();
            try {
                $pdo->prepare('UPDATE playlists SET enabled = 0 WHERE device_id = ?')->execute([(int) $device['id']]);
                $pdo->prepare(
                    'INSERT INTO playlists (device_id, playlist_name, playlist_type, playlist_url, server_url, username, password, output_format, epg_url, catchup_mode, enabled)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)'
                )->execute([(int) $device['id'], $name, $type, $type === 'm3u' ? $playlistUrl : null, $type === 'xtream' ? $serverUrl : null,
                    $type === 'xtream' ? trim((string) $_POST['username']) : null,
                    $type === 'xtream' ? encrypt_secret(trim((string) $_POST['password'])) : null,
                    in_array($_POST['output'] ?? '', ['m3u8', 'ts'], true) ? $_POST['output'] : 'm3u8',
                    $epgUrl ?: null, truncate_text(trim((string) ($_POST['catchup_mode'] ?? '')), 30) ?: null]);
                $pdo->commit();
                audit_log('portal.playlist_saved', (int) $device['id'], ['type' => $type]);
                $message = 'تم حفظ القائمة.';
            } catch (Throwable $error) {
                $pdo->rollBack();
                throw $error;
            }
        }
    }
}

$playlists = get_device_playlists((int) $device['id']);
$access = device_access($device);
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>لوحة الجهاز | Nexo Player</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<main class="dashboard">
    <section class="panel wide">
        <h1>لوحة الجهاز</h1>
        <p class="mac"><?= htmlspecialchars($device['mac'], ENT_QUOTES, 'UTF-8') ?></p>
        <?php if ($message): ?><p class="notice"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
        <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 $saved): ?>
                <div class="playlist-item">
                    <strong><?= !empty($saved['enabled']) ? 'نشطة: ' : '' ?><?= htmlspecialchars($saved['playlist_name'], ENT_QUOTES, 'UTF-8') ?></strong>
                    <small class="ltr"><?= htmlspecialchars($saved['server_url'] ?: $saved['playlist_url'], ENT_QUOTES, 'UTF-8') ?></small>
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="token" value="<?= htmlspecialchars($token, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="playlist_id" value="<?= (int) $saved['id'] ?>">
                        <?php if (empty($saved['enabled'])): ?><button name="action" value="activate">تفعيل</button><?php endif; ?>
                        <button name="action" value="delete" class="danger">حذف</button>
                    </form>
                </div>
            <?php endforeach; ?>
        </section>

        <form class="playlist-form" method="post">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="token" value="<?= htmlspecialchars($token, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="action" value="save">
            <h2>إضافة قائمة</h2>
            <label>اسم القائمة</label><input name="name" maxlength="255" placeholder="Main IPTV">
            <label>النوع</label><select name="type"><option value="m3u">M3U URL</option><option value="xtream">Xtream</option></select>
            <label>M3U URL</label><input name="playlist_url" type="url" placeholder="https://example.com/list.m3u">
            <label>Server URL</label><input name="server_url" type="url" placeholder="https://example.com:8080">
            <label>Username</label><input name="username" autocomplete="off">
            <label>Password</label><input name="password" type="password" autocomplete="new-password">
            <label>صيغة البث</label><select name="output"><option value="m3u8">HLS (m3u8)</option><option value="ts">MPEG-TS</option></select>
            <label>EPG XMLTV URL</label><input name="epg_url" type="url" placeholder="https://example.com/epg.xml">
            <label>Catch-up mode</label><input name="catchup_mode" maxlength="30" placeholder="append / shift">
            <button type="submit">حفظ القائمة</button>
        </form>

        <button id="payButton" class="pay-button" type="button">تجديد الاشتراك بواسطة Stripe</button>
        <p id="payMessage"></p>
    </section>
</main>
<script>
document.getElementById('payButton').addEventListener('click', function () {
    var button = this;
    button.disabled = true;
    fetch('api/create_checkout.php', {
        method: 'POST', headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({portal_token: <?= json_encode($token) ?>})
    }).then(function (response) { return response.json(); }).then(function (json) {
        if (json.ok && json.checkout_url) { window.location.href = json.checkout_url; return; }
        throw new Error(json.error || 'تعذر فتح الدفع');
    }).catch(function (error) {
        document.getElementById('payMessage').textContent = error.message;
        button.disabled = false;
    });
});
</script>
</body>
</html>
