<?php
require __DIR__ . '/lib/bootstrap.php';
session_start();

global $config;
$message = '';
$admin = $config['admin'];

function admin_id_list($value): array
{
    if (is_array($value)) {
        $source = $value;
    } else {
        $source = preg_split('/[,\s]+/', (string) $value);
    }

    return array_values(array_unique(array_filter(array_map('intval', $source), function ($id) {
        return $id > 0;
    })));
}

if (isset($_GET['logout'])) {
    $_SESSION = [];
    session_destroy();
    header('Location: admin.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form'] ?? '') === 'login') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if ($username === $admin['username'] && hash_equals((string) $admin['password'], $password)) {
        $_SESSION['admin_logged_in'] = true;
        header('Location: admin.php');
        exit;
    }

    $message = 'بيانات الدخول غير صحيحة';
}

$loggedIn = !empty($_SESSION['admin_logged_in']);

if ($loggedIn && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form'] ?? '') === 'bulk_devices') {
    $deviceIds = admin_id_list($_POST['device_ids'] ?? '');
    $action = $_POST['action'] ?? '';

    if ($action === 'delete' && $deviceIds) {
        $placeholders = implode(',', array_fill(0, count($deviceIds), '?'));
        $pdo = db();
        $pdo->beginTransaction();
        try {
            $pdo->prepare("DELETE FROM playlists WHERE device_id IN ($placeholders)")->execute($deviceIds);
            $pdo->prepare("DELETE FROM payments WHERE device_id IN ($placeholders)")->execute($deviceIds);
            $pdo->prepare("DELETE FROM devices WHERE id IN ($placeholders)")->execute($deviceIds);
            $pdo->commit();
            $message = 'تم حذف الأجهزة والحسابات المحددة من قاعدة البيانات';
        } catch (Throwable $error) {
            $pdo->rollBack();
            $message = 'تعذر حذف الأجهزة المحددة: ' . $error->getMessage();
        }
    } else {
        $message = 'اختر جهازًا واحدًا على الأقل للحذف';
    }
}

if ($loggedIn && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form'] ?? '') === 'device') {
    $deviceId = (int) ($_POST['device_id'] ?? 0);
    $action = $_POST['action'] ?? '';

    if ($deviceId > 0) {
        if ($action === 'activate') {
            $days = max(1, (int) ($_POST['days'] ?? $config['app']['paid_days']));
            db()->prepare('UPDATE devices SET status = ?, active_until = DATE_ADD(NOW(), INTERVAL ? DAY) WHERE id = ?')
                ->execute(['active', $days, $deviceId]);
            $message = 'تم تفعيل الحساب';
        } elseif ($action === 'disable') {
            db()->prepare('UPDATE devices SET status = ? WHERE id = ?')->execute(['disabled', $deviceId]);
            $message = 'تم إيقاف الحساب';
        } elseif ($action === 'enable_trial') {
            db()->prepare('UPDATE devices SET status = ?, trial_ends_at = DATE_ADD(NOW(), INTERVAL ? DAY) WHERE id = ?')
                ->execute(['trial', (int) $config['app']['trial_days'], $deviceId]);
            $message = 'تم إعادة التجربة';
        }
    }
}

if ($loggedIn && $_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['form'] ?? '') === 'playlist') {
    $deviceId = (int) ($_POST['device_id'] ?? 0);
    $action = $_POST['action'] ?? 'save';

    if ($deviceId > 0) {
        if ($action === 'delete') {
            db()->prepare('DELETE FROM playlists WHERE device_id = ? AND id = ?')
                ->execute([$deviceId, (int) ($_POST['playlist_id'] ?? 0)]);
            $message = 'تم حذف القائمة';
        } elseif ($action === 'toggle') {
            if (!empty($_POST['enabled'])) {
                db()->prepare('UPDATE playlists SET enabled = 0 WHERE device_id = ?')->execute([$deviceId]);
            }
            db()->prepare('UPDATE playlists SET enabled = ? WHERE device_id = ? AND id = ?')
                ->execute([!empty($_POST['enabled']) ? 1 : 0, $deviceId, (int) ($_POST['playlist_id'] ?? 0)]);
            $message = 'تم تحديث اختيار القائمة';
        } else {
            $type = strtolower(trim($_POST['type'] ?? 'm3u'));
            $name = trim($_POST['name'] ?? 'Main IPTV') ?: 'Main IPTV';
            $enabled = !empty($_POST['enabled']) ? 1 : 0;

            if ($enabled) {
                db()->prepare('UPDATE playlists SET enabled = 0 WHERE device_id = ?')->execute([$deviceId]);
            }

            if ($type === 'xtream') {
                db()->prepare(
                    'INSERT INTO playlists (device_id, playlist_name, playlist_type, server_url, username, password, output_format, enabled)
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
                )->execute([
                    $deviceId,
                    $name,
                    'xtream',
                    rtrim(trim($_POST['server_url'] ?? ''), '/'),
                    trim($_POST['username'] ?? ''),
                    trim($_POST['password'] ?? ''),
                    trim($_POST['output'] ?? 'm3u8') ?: 'm3u8',
                    $enabled,
                ]);
            } else {
                db()->prepare(
                    'INSERT INTO playlists (device_id, playlist_name, playlist_type, playlist_url, enabled)
                     VALUES (?, ?, ?, ?, ?)'
                )->execute([
                    $deviceId,
                    $name,
                    'm3u',
                    trim($_POST['playlist_url'] ?? ''),
                    $enabled,
                ]);
            }
            $message = 'تم حفظ القائمة';
        }
    }
}

$devices = [];
$payments = [];
$stats = ['total' => 0, 'active' => 0, 'trial' => 0, 'disabled' => 0, 'expired' => 0];
$macSearch = normalize_mac($_GET['mac'] ?? '');

if ($loggedIn) {
    if ($macSearch !== '') {
        $stmt = db()->prepare(
            'SELECT d.*
             FROM devices d
             WHERE d.mac LIKE ?
             ORDER BY d.created_at DESC'
        );
        $stmt->execute(['%' . $macSearch . '%']);
        $devices = $stmt->fetchAll();
    } else {
        $devices = db()->query(
            'SELECT d.*
             FROM devices d
             ORDER BY d.created_at DESC'
        )->fetchAll();
    }

    $payments = db()->query(
        'SELECT pay.*, d.mac
         FROM payments pay
         LEFT JOIN devices d ON d.id = pay.device_id
         ORDER BY pay.created_at DESC
         LIMIT 100'
    )->fetchAll();

    foreach ($devices as $device) {
        $stats['total'] += 1;
        $access = device_access($device);
        if (($device['status'] ?? '') === 'disabled') {
            $stats['disabled'] += 1;
        } elseif ($access['reason'] === 'paid') {
            $stats['active'] += 1;
        } elseif ($access['reason'] === 'trial') {
            $stats['trial'] += 1;
        } else {
            $stats['expired'] += 1;
        }
    }
}
?>
<!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?v=20260601-3">
</head>
<body>
<?php if (!$loggedIn): ?>
    <main class="auth-page">
        <form class="panel" method="post">
            <input type="hidden" name="form" value="login">
            <h1>لوحة الأدمن</h1>
            <?php if ($message): ?><p class="notice"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
            <label>اسم المستخدم</label>
            <input name="username" autocomplete="username" required>
            <label>كلمة المرور</label>
            <input name="password" type="password" autocomplete="current-password" required>
            <button type="submit">دخول</button>
        </form>
    </main>
<?php else: ?>
    <main class="admin-page">
        <header class="admin-header">
            <div>
                <h1>لوحة الأدمن</h1>
                <p>متابعة الأجهزة، التفعيل، التجارب، والمدفوعات</p>
            </div>
            <a class="logout-link" href="admin.php?logout=1">خروج</a>
        </header>

        <?php if ($message): ?><p class="notice"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>

        <section class="stats-row">
            <div><strong><?= $stats['total'] ?></strong><span>كل الأجهزة</span></div>
            <div><strong><?= $stats['active'] ?></strong><span>مفعّل</span></div>
            <div><strong><?= $stats['trial'] ?></strong><span>تجربة</span></div>
            <div><strong><?= $stats['expired'] ?></strong><span>منتهي</span></div>
            <div><strong><?= $stats['disabled'] ?></strong><span>متوقف</span></div>
        </section>

        <section class="admin-card">
            <div class="admin-card-header">
                <h2>الأجهزة والحسابات</h2>
                <form class="admin-search" method="get">
                    <input class="ltr" name="mac" value="<?= htmlspecialchars($macSearch, ENT_QUOTES, 'UTF-8') ?>" placeholder="بحث حسب MAC">
                    <button type="submit">بحث</button>
                    <?php if ($macSearch !== ''): ?><a href="admin.php">مسح</a><?php endif; ?>
                </form>
            </div>
            <form id="bulkDeviceForm" class="bulk-actions" method="post">
                <input type="hidden" name="form" value="bulk_devices">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" id="bulkDeviceIds" name="device_ids">
                <span id="bulkDeviceCount">0 محدد</span>
                <button type="submit" class="danger">حذف الأجهزة والحسابات المحددة</button>
            </form>
            <div class="table-wrap">
                <table class="admin-devices-table">
                    <thead>
                        <tr>
                            <th class="select-col"><input id="selectAllDevices" type="checkbox" aria-label="تحديد الكل"></th>
                            <th>MAC</th>
                            <th>الحالة</th>
                            <th>بداية التجربة</th>
                            <th>نهاية التجربة</th>
                            <th>نهاية التفعيل</th>
                            <th>آخر دخول</th>
                            <th>قائمة التشغيل</th>
                            <th>تحكم</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($devices as $device): $access = device_access($device); $devicePlaylists = get_device_playlists((int) $device['id']); ?>
                        <tr>
                            <td class="select-col"><input class="device-select" type="checkbox" value="<?= (int) $device['id'] ?>" aria-label="تحديد الجهاز"></td>
                            <td class="ltr"><?= htmlspecialchars($device['mac'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars(($device['status'] === 'disabled' ? 'disabled' : $access['reason']), ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($device['trial_started_at'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($device['trial_ends_at'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($device['active_until'] ?: '-', ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($device['last_seen_at'] ?: '-', ENT_QUOTES, 'UTF-8') ?></td>
                            <td>
                                <?php foreach ($devicePlaylists as $savedPlaylist): ?>
                                    <div class="playlist-admin-row">
                                        <strong><?= htmlspecialchars(($savedPlaylist['enabled'] ? 'ON ' : 'OFF ') . ($savedPlaylist['playlist_name'] ?? 'Main IPTV'), ENT_QUOTES, 'UTF-8') ?></strong>
                                        <small class="ltr"><?= htmlspecialchars(generated_playlist_url($savedPlaylist), ENT_QUOTES, 'UTF-8') ?></small>
                                        <form method="post">
                                            <input type="hidden" name="form" value="playlist">
                                            <input type="hidden" name="device_id" value="<?= (int) $device['id'] ?>">
                                            <input type="hidden" name="playlist_id" value="<?= (int) $savedPlaylist['id'] ?>">
                                            <label><input name="enabled" type="checkbox" value="1" <?= !empty($savedPlaylist['enabled']) ? 'checked' : '' ?>> مفعل</label>
                                            <button name="action" value="toggle">تحديث</button>
                                            <button name="action" value="delete" class="danger">حذف</button>
                                        </form>
                                    </div>
                                <?php endforeach; ?>
                            </td>
                            <td>
                                <form class="inline-actions" method="post">
                                    <input type="hidden" name="form" value="device">
                                    <input type="hidden" name="device_id" value="<?= (int) $device['id'] ?>">
                                    <input name="days" type="number" min="1" value="<?= (int) $config['app']['paid_days'] ?>" aria-label="days">
                                    <button name="action" value="activate">تفعيل</button>
                                    <button name="action" value="enable_trial">تجربة</button>
                                    <button name="action" value="disable" class="danger">إيقاف</button>
                                </form>
                            </td>
                        </tr>
                        <tr class="playlist-form-row">
                            <td class="select-col"></td>
                            <td colspan="8">
                                <form class="playlist-admin-form playlist-admin-form-wide" method="post">
                                    <input type="hidden" name="form" value="playlist">
                                    <input type="hidden" name="device_id" value="<?= (int) $device['id'] ?>">
                                    <input name="name" placeholder="اسم القائمة">
                                    <select name="type">
                                        <option value="m3u">M3U</option>
                                        <option value="xtream">Xtream</option>
                                    </select>
                                    <input name="playlist_url" placeholder="M3U URL">
                                    <input name="server_url" placeholder="Server URL">
                                    <input name="username" placeholder="Username">
                                    <input name="password" placeholder="Password">
                                    <label><input name="enabled" type="checkbox" value="1" checked> مفعل</label>
                                    <button type="submit">إضافة</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <section class="admin-card">
            <h2>سجل الدفع</h2>
            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>MAC</th>
                            <th>Stripe Session</th>
                            <th>المبلغ</th>
                            <th>العملة</th>
                            <th>الحالة</th>
                            <th>التاريخ</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($payments as $payment): ?>
                        <tr>
                            <td class="ltr"><?= htmlspecialchars($payment['mac'] ?: '-', ENT_QUOTES, 'UTF-8') ?></td>
                            <td class="ltr"><?= htmlspecialchars($payment['stripe_session_id'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars((string) $payment['amount_total'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($payment['currency'] ?: '-', ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($payment['status'], ENT_QUOTES, 'UTF-8') ?></td>
                            <td><?= htmlspecialchars($payment['created_at'], ENT_QUOTES, 'UTF-8') ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </main>
<?php endif; ?>
<script>
document.addEventListener("DOMContentLoaded", function () {
    var selectAll = document.getElementById("selectAllDevices");
    var bulkForm = document.getElementById("bulkDeviceForm");
    var bulkIds = document.getElementById("bulkDeviceIds");
    var bulkCount = document.getElementById("bulkDeviceCount");
    var checkboxes = Array.prototype.slice.call(document.querySelectorAll(".device-select"));

    function selectedIds() {
        return checkboxes.filter(function (checkbox) {
            return checkbox.checked;
        }).map(function (checkbox) {
            return checkbox.value;
        });
    }

    function updateBulkState() {
        var ids = selectedIds();

        if (bulkIds) {
            bulkIds.value = ids.join(",");
        }
        if (bulkCount) {
            bulkCount.textContent = ids.length + " محدد";
        }
        if (selectAll) {
            selectAll.checked = checkboxes.length > 0 && ids.length === checkboxes.length;
            selectAll.indeterminate = ids.length > 0 && ids.length < checkboxes.length;
        }
    }

    if (selectAll) {
        selectAll.addEventListener("change", function () {
            checkboxes.forEach(function (checkbox) {
                checkbox.checked = selectAll.checked;
            });
            updateBulkState();
        });
    }

    checkboxes.forEach(function (checkbox) {
        checkbox.addEventListener("change", updateBulkState);
    });

    if (bulkForm) {
        bulkForm.addEventListener("submit", function (event) {
            updateBulkState();
            if (!bulkIds.value) {
                event.preventDefault();
                alert("اختر جهازًا واحدًا على الأقل.");
                return;
            }
            if (!confirm("سيتم حذف الأجهزة المحددة وحساباتها وقوائمها من قاعدة البيانات. هل تريد المتابعة؟")) {
                event.preventDefault();
            }
        });
    }

    updateBulkState();
});
</script>
</body>
</html>
