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

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

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

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && ($_POST['form'] ?? '') === 'login') {
    verify_csrf();
    rate_limit('admin-login', 10, 900);
    $username = trim((string) ($_POST['username'] ?? ''));
    $password = (string) ($_POST['password'] ?? '');
    $hash = (string) config('admin.password_hash', '');
    if ($hash !== '' && hash_equals((string) config('admin.username', 'admin'), $username) && password_verify($password, $hash)) {
        session_regenerate_id(true);
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_username'] = $username;
        audit_log('admin.login');
        header('Location: admin.php');
        exit;
    }
    $message = $hash === '' ? 'يجب ضبط ADMIN_PASSWORD_HASH أولًا.' : 'بيانات الدخول غير صحيحة.';
}

if ($loggedIn && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    verify_csrf();
    $form = (string) ($_POST['form'] ?? '');
    if ($form === 'logout') {
        audit_log('admin.logout');
        $_SESSION = [];
        session_destroy();
        header('Location: admin.php');
        exit;
    }

    $deviceId = max(0, (int) ($_POST['device_id'] ?? 0));
    if ($form === 'device' && $deviceId > 0) {
        $action = (string) ($_POST['action'] ?? '');
        $auditAction = '';
        if ($action === 'activate') {
            $days = min(3650, max(1, (int) ($_POST['days'] ?? config('app.paid_days', 30))));
            db()->prepare('UPDATE devices SET status = ?, active_until = DATE_ADD(IF(active_until IS NULL OR active_until < NOW(), NOW(), active_until), INTERVAL ? DAY) WHERE id = ?')
                ->execute(['active', $days, $deviceId]);
            $message = 'تم تمديد التفعيل.';
            $auditAction = 'activate';
        } elseif ($action === 'trial') {
            $days = min(365, max(1, (int) config('app.trial_days', 7)));
            db()->prepare('UPDATE devices SET status = ?, trial_started_at = NOW(), trial_ends_at = DATE_ADD(NOW(), INTERVAL ? DAY) WHERE id = ?')
                ->execute(['trial', $days, $deviceId]);
            $message = 'تمت إعادة التجربة.';
            $auditAction = 'trial';
        } elseif ($action === 'disable') {
            db()->prepare('UPDATE devices SET status = ? WHERE id = ?')->execute(['disabled', $deviceId]);
            $message = 'تم إيقاف الجهاز.';
            $auditAction = 'disable';
        } elseif ($action === 'delete') {
            audit_log('admin.device_delete', $deviceId);
            db()->prepare('DELETE FROM devices WHERE id = ?')->execute([$deviceId]);
            $message = 'تم حذف الجهاز وبياناته.';
        }
        if ($auditAction !== '') {
            audit_log('admin.device_' . $auditAction, $deviceId, ['days' => $_POST['days'] ?? null]);
        }
    }
}

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 25;
$query = trim((string) ($_GET['q'] ?? ''));
$statusFilter = trim((string) ($_GET['status'] ?? ''));
$devices = [];
$totalDevices = 0;
$payments = [];
$auditLogs = [];
$stats = ['total' => 0, 'active' => 0, 'trial' => 0, 'disabled' => 0, 'expired' => 0];

if ($loggedIn) {
    $stats['total'] = (int) db()->query('SELECT COUNT(*) FROM devices')->fetchColumn();
    $allStatusRows = db()->query('SELECT status, trial_ends_at, active_until FROM devices')->fetchAll();
    foreach ($allStatusRows as $row) {
        if ($row['status'] === 'disabled') {
            $stats['disabled']++;
        } else {
            $reason = device_access($row)['reason'];
            $stats[$reason === 'paid' ? 'active' : $reason]++;
        }
    }

    $where = [];
    $params = [];
    if ($query !== '') {
        $where[] = 'mac LIKE ?';
        $params[] = '%' . normalize_mac($query) . '%';
    }
    if (in_array($statusFilter, ['trial', 'active', 'disabled'], true)) {
        $where[] = 'status = ?';
        $params[] = $statusFilter;
    }
    $whereSql = $where ? ' WHERE ' . implode(' AND ', $where) : '';
    $countStmt = db()->prepare('SELECT COUNT(*) FROM devices' . $whereSql);
    $countStmt->execute($params);
    $totalDevices = (int) $countStmt->fetchColumn();
    $offset = ($page - 1) * $perPage;
    $listStmt = db()->prepare('SELECT * FROM devices' . $whereSql . ' ORDER BY created_at DESC LIMIT ' . $perPage . ' OFFSET ' . $offset);
    $listStmt->execute($params);
    $devices = $listStmt->fetchAll();

    $payments = db()->query('SELECT p.*, d.mac FROM payments p LEFT JOIN devices d ON d.id = p.device_id ORDER BY p.created_at DESC LIMIT 50')->fetchAll();
    $auditLogs = db()->query('SELECT a.*, d.mac FROM audit_logs a LEFT JOIN devices d ON d.id = a.device_id ORDER BY a.created_at DESC LIMIT 50')->fetchAll();
}
?>
<!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?v=20260613"></head>
<body>
<?php if (!$loggedIn): ?>
<main class="auth-page"><form class="panel" method="post">
    <input type="hidden" name="form" value="login"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>">
    <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>
        <form method="post"><input type="hidden" name="form" value="logout"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><button type="submit">خروج</button></form>
    </header>
    <?php if ($message): ?><p class="notice"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
    <section class="stats-row">
        <?php foreach (['total' => 'الكل', 'active' => 'مفعل', 'trial' => 'تجربة', 'expired' => 'منتهي', 'disabled' => 'متوقف'] as $key => $label): ?>
            <div><strong><?= (int) $stats[$key] ?></strong><span><?= $label ?></span></div>
        <?php endforeach; ?>
    </section>

    <section class="admin-card">
        <div class="admin-card-header"><h2>الأجهزة</h2><form class="admin-search" method="get">
            <input name="q" class="ltr" value="<?= htmlspecialchars($query, ENT_QUOTES, 'UTF-8') ?>" placeholder="MAC">
            <select name="status"><option value="">كل الحالات</option><?php foreach (['trial','active','disabled'] as $option): ?><option value="<?= $option ?>" <?= $statusFilter === $option ? 'selected' : '' ?>><?= $option ?></option><?php endforeach; ?></select>
            <button type="submit">بحث</button></form></div>
        <div class="table-wrap"><table><thead><tr><th>MAC</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="ltr"><?= htmlspecialchars($device['mac'], ENT_QUOTES, 'UTF-8') ?></td><td><?= htmlspecialchars($access['reason'], 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 $playlist): ?><div><strong><?= !empty($playlist['enabled']) ? 'ON ' : 'OFF ' ?><?= htmlspecialchars($playlist['playlist_name'], ENT_QUOTES, 'UTF-8') ?></strong><small class="ltr"><?= htmlspecialchars($playlist['server_url'] ?: $playlist['playlist_url'], ENT_QUOTES, 'UTF-8') ?></small></div><?php endforeach; ?></td>
                <td><form class="inline-actions" method="post" onsubmit="return !(event.submitter && event.submitter.value === 'delete') || confirm('حذف الجهاز نهائيًا؟');">
                    <input type="hidden" name="form" value="device"><input type="hidden" name="device_id" value="<?= (int) $device['id'] ?>"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>">
                    <input name="days" type="number" min="1" max="3650" value="<?= (int) config('app.paid_days', 30) ?>">
                    <button name="action" value="activate">تمديد</button><button name="action" value="trial">تجربة</button><button name="action" value="disable">إيقاف</button><button name="action" value="delete" class="danger">حذف</button>
                </form></td></tr>
        <?php endforeach; ?>
        </tbody></table></div>
        <nav class="pagination"><?php $pages = max(1, (int) ceil($totalDevices / $perPage)); for ($i = 1; $i <= $pages; $i++): ?><a class="<?= $i === $page ? 'is-active' : '' ?>" href="?page=<?= $i ?>&q=<?= rawurlencode($query) ?>&status=<?= rawurlencode($statusFilter) ?>"><?= $i ?></a><?php endfor; ?></nav>
    </section>

    <section class="admin-card"><h2>آخر المدفوعات</h2><div class="table-wrap"><table><thead><tr><th>MAC</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><?= (int) $payment['amount_total'] ?> <?= 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>

    <section class="admin-card"><h2>سجل العمليات</h2><div class="table-wrap"><table><thead><tr><th>الفاعل</th><th>العملية</th><th>MAC</th><th>IP</th><th>التاريخ</th></tr></thead><tbody>
        <?php foreach ($auditLogs as $log): ?><tr><td><?= htmlspecialchars($log['actor'], ENT_QUOTES, 'UTF-8') ?></td><td><?= htmlspecialchars($log['action'], ENT_QUOTES, 'UTF-8') ?></td><td class="ltr"><?= htmlspecialchars($log['mac'] ?: '-', ENT_QUOTES, 'UTF-8') ?></td><td class="ltr"><?= htmlspecialchars($log['ip_address'] ?: '-', ENT_QUOTES, 'UTF-8') ?></td><td><?= htmlspecialchars($log['created_at'], ENT_QUOTES, 'UTF-8') ?></td></tr><?php endforeach; ?>
    </tbody></table></div></section>
</main>
<?php endif; ?>
</body></html>
