<?php
// app/Controllers/SuperAdminController.php
// Handles: Profile update, Add Admin, Subscriptions management

class SuperAdminController {
    private function requireSuperAdmin() {
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'superadmin') {
            header('Location: /restpo/login'); exit;
        }
    }

    // ── Profile Update ────────────────────────────────────────────
    public function updateProfile() {
        $this->requireSuperAdmin();
        $db = getDB();

        $redirect = trim($_POST['redirect_url'] ?? '/restpo/superadmin/dashboard');
        $redirectBase = strtok($redirect, '?');
        if (empty($redirectBase)) {
            $redirectBase = '/restpo/superadmin/dashboard';
        }

        $name     = trim($_POST['name'] ?? '');
        $email    = trim($_POST['email'] ?? '');
        $phone    = trim($_POST['phone'] ?? '');
        $currency = trim($_POST['currency'] ?? '$');
        $newPw    = $_POST['new_password'] ?? '';
        $confPw   = $_POST['confirm_password'] ?? '';

        if (!$name || !$email) {
            header('Location: ' . $redirectBase . '?error=' . urlencode('Name and email are required') . '&profile=1'); exit;
        }

        $check = $db->prepare('SELECT id FROM users WHERE email = ? AND id != ?');
        $check->execute([$email, $_SESSION['user_id']]);
        if ($check->fetch()) {
            header('Location: ' . $redirectBase . '?error=' . urlencode('Email already in use') . '&profile=1'); exit;
        }

        if ($newPw) {
            if ($newPw !== $confPw) {
                header('Location: ' . $redirectBase . '?error=' . urlencode('Passwords do not match') . '&profile=1'); exit;
            }
            $hashed = password_hash($newPw, PASSWORD_BCRYPT);
            $db->prepare('UPDATE users SET name=?, email=?, phone=?, password=?, currency=? WHERE id=?')
               ->execute([$name, $email, $phone, $hashed, $currency, $_SESSION['user_id']]);
        } else {
            $db->prepare('UPDATE users SET name=?, email=?, phone=?, currency=? WHERE id=?')
               ->execute([$name, $email, $phone, $currency, $_SESSION['user_id']]);
        }

        // Handle logo upload (updates both website logo and super admin profile photo)
        if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
            if (in_array($ext, $allowed)) {
                $filename = 'logo_' . uniqid() . '.' . $ext;
                $destination = 'public/uploads/logos/' . $filename;
                if (!is_dir('public/uploads/logos')) {
                    mkdir('public/uploads/logos', 0755, true);
                }
                if (move_uploaded_file($_FILES['logo']['tmp_name'], $destination)) {
                    $logoPath = '/restpo/public/uploads/logos/' . $filename;
                    
                    // 1. Update site setting website_logo
                    $stmt = $db->prepare('INSERT INTO site_settings (setting_key, setting_value) VALUES ("website_logo", ?) ON DUPLICATE KEY UPDATE setting_value = ?');
                    $stmt->execute([$logoPath, $logoPath]);
                    
                    // 2. Update user's logo (super admin)
                    $db->prepare('UPDATE users SET logo = ? WHERE id = ?')
                       ->execute([$logoPath, $_SESSION['user_id']]);
                    
                    // 3. Update session logo
                    $_SESSION['logo'] = $logoPath;
                }
            }
        }

        // Handle hero video URL update
        if (isset($_POST['hero_video_url'])) {
            $heroUrl = trim($_POST['hero_video_url']);
            if (!empty($heroUrl)) {
                if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i', $heroUrl, $match)) {
                    $heroUrl = 'https://www.youtube.com/embed/' . $match[1];
                }
            }
            $stmt = $db->prepare('INSERT INTO site_settings (setting_key, setting_value) VALUES ("hero_video_url", ?) ON DUPLICATE KEY UPDATE setting_value = ?');
            $stmt->execute([$heroUrl, $heroUrl]);
        }

        // Update session vars
        $_SESSION['name']     = $name;
        $_SESSION['email']    = $email;
        $_SESSION['phone']    = $phone;
        $_SESSION['currency'] = $currency;

        header('Location: ' . $redirectBase . '?msg=' . urlencode('Profile updated successfully')); exit;
    }

    // ── Admin Users Management ───────────────────────────────────
    public function admins() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'System Admins';

        $admins = $db->query('SELECT * FROM users WHERE role="superadmin" ORDER BY created_at DESC')->fetchAll();

        ob_start(); ?>
<div class="space-y-6">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Add Admin Form -->
        <div class="rounded-2xl p-5" style="background:rgba(139,92,246,0.08); border:1px solid rgba(139,92,246,0.2)">
            <h3 class="text-base font-bold text-white mb-4"><i class="fas fa-user-plus text-purple-400 mr-2"></i>Add Super Admin</h3>
            <form action="/restpo/superadmin/admins/store" method="POST" class="space-y-3">
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Full Name</label>
                    <input type="text" name="name" required class="form-input" placeholder="Admin Name">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Email</label>
                    <input type="email" name="email" required class="form-input" placeholder="admin@example.com">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Phone</label>
                    <input type="text" name="phone" class="form-input" placeholder="+1 234 567 890">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Password</label>
                    <input type="password" name="password" required class="form-input" placeholder="••••••••">
                </div>
                <button type="submit" class="btn-primary w-full mt-2">Create Admin Account</button>
            </form>
        </div>

        <!-- Admins List -->
        <div class="lg:col-span-2 rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
            <div class="px-5 py-4 border-b border-white/5">
                <h3 class="font-semibold text-white">All Super Admins</h3>
            </div>
            <table class="w-full text-sm">
                <thead><tr class="border-b border-white/5">
                    <th class="text-left px-5 py-3 text-slate-500 font-medium">Admin</th>
                    <th class="text-left px-5 py-3 text-slate-500 font-medium">Email</th>
                    <th class="text-left px-5 py-3 text-slate-500 font-medium">Phone</th>
                    <th class="text-left px-5 py-3 text-slate-500 font-medium">Joined</th>
                </tr></thead>
                <tbody>
                <?php foreach($admins as $a): ?>
                <tr class="border-b border-white/5 hover:bg-white/4 transition">
                    <td class="px-5 py-3">
                        <div class="flex items-center gap-2.5">
                            <img class="h-8 w-8 rounded-full" src="https://ui-avatars.com/api/?name=<?php echo urlencode($a['name']); ?>&background=7c3aed&color=fff&size=64" alt="">
                            <span class="font-medium text-white"><?php echo htmlspecialchars($a['name']); ?>
                                <?php if($a['id'] == $_SESSION['user_id']): ?><span class="ml-1 text-xs text-purple-400">(You)</span><?php endif; ?>
                            </span>
                        </div>
                    </td>
                    <td class="px-5 py-3 text-slate-400"><?php echo htmlspecialchars($a['email']); ?></td>
                    <td class="px-5 py-3 text-slate-400"><?php echo $a['phone'] ?? '—'; ?></td>
                    <td class="px-5 py-3 text-slate-500 text-xs"><?php echo date('M d, Y', strtotime($a['created_at'])); ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function storeAdmin() {
        $this->requireSuperAdmin();
        $db = getDB();

        $check = $db->prepare('SELECT id FROM users WHERE email = ?');
        $check->execute([$_POST['email']]);
        if ($check->fetch()) {
            header('Location: /restpo/superadmin/admins?error=Email+already+exists'); exit;
        }

        $hashed = password_hash($_POST['password'], PASSWORD_BCRYPT);
        $db->prepare('INSERT INTO users (restaurant_id, name, email, phone, password, role) VALUES (NULL, ?, ?, ?, ?, "superadmin")')
           ->execute([$_POST['name'], $_POST['email'], $_POST['phone'] ?? null, $hashed]);

        header('Location: /restpo/superadmin/admins?msg=Admin+created+successfully'); exit;
    }

    // ── Subscriptions Management ─────────────────────────────────
    public function subscriptions() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Subscriptions';

        $packages = $db->query('SELECT * FROM packages WHERE status="active"')->fetchAll();

        $subs = $db->query('
            SELECT s.*, 
                   r.name as restaurant_name, 
                   r.email as restaurant_email, 
                   r.phone as restaurant_phone, 
                   r.currency as restaurant_currency, 
                   p.name as package_name, 
                   p.duration_days,
                   p.features as package_features,
                   p.price as package_price
            FROM subscriptions s
            JOIN restaurants r ON r.id = s.restaurant_id
            JOIN packages p ON p.id = s.package_id
            WHERE s.id IN (
                SELECT MAX(id) 
                FROM subscriptions 
                GROUP BY restaurant_id
            )
            ORDER BY s.id DESC
        ')->fetchAll();

        // Restaurants without a subscription
        $noSub = $db->query('
            SELECT r.* FROM restaurants r
            LEFT JOIN subscriptions s ON s.restaurant_id = r.id AND s.status = "active"
            WHERE s.id IS NULL ORDER BY r.name
        ')->fetchAll();

        $pendingSubs = $db->query('
            SELECT s.*, 
                   r.name as restaurant_name, 
                   r.email as restaurant_email, 
                   r.phone as restaurant_phone, 
                   r.currency as restaurant_currency,
                   p.name as package_name, 
                   p.duration_days,
                   p.features as package_features,
                   p.price as package_price
            FROM subscriptions s
            JOIN restaurants r ON r.id = s.restaurant_id
            JOIN packages p ON p.id = s.package_id
            WHERE s.status = "pending"
            ORDER BY s.id ASC
        ')->fetchAll();

        ob_start(); ?>
<div 
    x-data="{ 
        selectedSub: null,
        search: '',
        statusFilter: 'all',
        openModal(sub) {
            this.selectedSub = sub;
        },
        closeModal() {
            this.selectedSub = null;
        }
    }"
    class="space-y-6"
>
    <!-- Header Summary & Search/Filters -->
    <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
        <div>
            <h2 class="text-xl font-bold text-white">Subscription Billing &amp; History</h2>
            <p class="text-slate-400 text-sm mt-1">Review full subscription history and manage plans across all restaurants.</p>
        </div>
        <div class="flex flex-col sm:flex-row items-center gap-3 w-full lg:w-auto">
            <div class="relative w-full sm:w-64">
                <span class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-slate-500">
                    <i class="fas fa-search text-xs"></i>
                </span>
                <input 
                    type="text" 
                    x-model="search" 
                    placeholder="Search restaurant or package..." 
                    class="form-input text-xs w-full pl-9 py-2 bg-white/5 border-white/10 rounded-xl text-white placeholder-slate-500 focus:border-purple-500/50" 
                />
            </div>
            <select 
                x-model="statusFilter" 
                class="form-input text-xs w-full sm:w-36 py-2 bg-white/5 border-white/10 rounded-xl text-slate-300 focus:border-purple-500/50"
            >
                <option value="all">All Statuses</option>
                <option value="active">Active</option>
                <option value="expired">Expired</option>
                <option value="cancelled">Cancelled</option>
            </select>
        </div>
    </div>

    <!-- Pending Subscription Approvals -->
    <?php if(!empty($pendingSubs)): ?>
    <div class="rounded-2xl overflow-hidden border border-yellow-500/20 bg-yellow-500/[0.03] p-5">
        <h3 class="font-bold text-sm flex items-center gap-2 text-yellow-400 mb-4"><i class="fas fa-clock"></i> Pending Subscription Approvals (<?php echo count($pendingSubs); ?>)</h3>
        <div class="space-y-3">
            <?php foreach($pendingSubs as $pSub): 
                $payDetails = json_decode($pSub['payment_details'] ?? '{}', true) ?: [];
                $payMethodName = ucfirst($pSub['payment_method'] ?? 'N/A');
                $methodColor = match(strtolower($pSub['payment_method'] ?? '')) {
                    'bkash' => 'bg-pink-500/10 text-pink-400 border-pink-500/20',
                    'nagad' => 'bg-orange-500/10 text-orange-400 border-orange-500/20',
                    'bank' => 'bg-blue-500/10 text-blue-400 border-blue-500/20',
                    default => 'bg-slate-500/10 text-slate-400 border-slate-500/20',
                };
            ?>
            <div class="flex flex-col lg:flex-row lg:items-center justify-between p-5 rounded-xl border border-white/5 bg-[#161825]/50 gap-4">
                <div class="space-y-3 flex-1">
                    <div>
                        <div class="flex items-center gap-2">
                            <span class="text-white font-bold text-sm"><?php echo htmlspecialchars($pSub['restaurant_name']); ?></span>
                            <span class="px-2 py-0.5 rounded text-3xs font-extrabold uppercase bg-purple-500/10 border border-purple-500/20 text-purple-400">
                                Requested Plan: <?php echo htmlspecialchars($pSub['package_name']); ?>
                            </span>
                        </div>
                        <div class="text-xs text-slate-400 mt-1 flex flex-wrap gap-x-4 gap-y-1">
                            <span><i class="fas fa-envelope text-slate-600 mr-1"></i> <?php echo htmlspecialchars($pSub['restaurant_email']); ?></span>
                            <span><i class="fas fa-phone text-slate-600 mr-1"></i> <?php echo htmlspecialchars($pSub['restaurant_phone'] ?: 'N/A'); ?></span>
                            <span><i class="fas fa-tag text-slate-600 mr-1"></i> Price: <?php echo ($pSub['restaurant_currency'] ?? '$') . number_format($pSub['amount'], 2); ?>
                                <?php if (!empty($pSub['coupon_code'])): ?>
                                    <span class="text-emerald-400 font-bold ml-1">
                                        (Coupon: <?php echo htmlspecialchars($pSub['coupon_code']); ?> - <?php echo ($pSub['restaurant_currency'] ?? '$') . number_format($pSub['package_price'] - $pSub['amount'], 2); ?> off, Original: <?php echo ($pSub['restaurant_currency'] ?? '$') . number_format($pSub['package_price'], 2); ?>)
                                    </span>
                                <?php endif; ?>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Payment Details Grid -->
                    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-4 p-3.5 rounded-xl bg-white/[0.02] border border-white/5 text-xs">
                        <div>
                            <span class="text-slate-500 block text-3xs uppercase font-semibold tracking-wider mb-1">Payment Method</span>
                            <span class="px-2 py-0.5 rounded text-3xs font-extrabold uppercase border <?php echo $methodColor; ?>">
                                <?php echo htmlspecialchars($payMethodName); ?>
                            </span>
                        </div>
                        <div>
                            <span class="text-slate-500 block text-3xs uppercase font-semibold tracking-wider mb-1">Transaction ID / Ref</span>
                            <span class="font-mono font-bold text-white"><?php echo htmlspecialchars($payDetails['transaction_ref'] ?? 'N/A'); ?></span>
                        </div>
                        <?php if(!empty($payDetails['sender_number'])): ?>
                        <div>
                            <span class="text-slate-500 block text-3xs uppercase font-semibold tracking-wider mb-1">Sender Number</span>
                            <span class="font-bold text-white"><?php echo htmlspecialchars($payDetails['sender_number']); ?></span>
                        </div>
                        <?php endif; ?>
                        <?php if(!empty($payDetails['account_name'])): ?>
                        <div>
                            <span class="text-slate-500 block text-3xs uppercase font-semibold tracking-wider mb-1">Account/Bank Name</span>
                            <span class="font-bold text-white"><?php echo htmlspecialchars($payDetails['account_name']); ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="flex items-center gap-2 lg:self-center">
                    <form action="/restpo/superadmin/subscriptions/approve" method="POST" class="inline">
                        <input type="hidden" name="subscription_id" value="<?php echo $pSub['id']; ?>">
                        <button type="submit" class="text-xs font-semibold py-2 px-4 rounded-xl text-white bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] transition flex items-center gap-1.5 shadow-lg shadow-emerald-600/20">
                            <i class="fas fa-check"></i> Approve
                        </button>
                    </form>
                    <form action="/restpo/superadmin/subscriptions/reject" method="POST" class="inline">
                        <input type="hidden" name="subscription_id" value="<?php echo $pSub['id']; ?>">
                        <button type="submit" class="text-xs font-semibold py-2 px-4 rounded-xl text-red-400 bg-red-500/10 hover:bg-red-500/20 active:scale-[0.98] border border-red-500/35 transition flex items-center gap-1.5">
                            <i class="fas fa-times"></i> Reject
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Subscription Table -->
    <div class="rounded-2xl overflow-hidden border border-white/5 bg-white/[0.02]">
        <div class="px-5 py-4 border-b border-white/5 flex justify-between items-center bg-white/[0.01]">
            <h3 class="font-semibold text-white text-sm flex items-center gap-2"><i class="fas fa-history text-purple-400"></i> Full Subscription Logs</h3>
            <span class="text-xs text-slate-500"><?php echo count($subs); ?> transactions recorded</span>
        </div>
        <div class="overflow-x-auto">
        <table class="w-full text-xs">
            <thead>
                <tr class="border-b border-white/5 bg-white/[0.01] text-left">
                    <th class="px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Restaurant</th>
                    <th class="px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Package</th>
                    <th class="px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Start Date</th>
                    <th class="px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Expires On</th>
                    <th class="px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Amount</th>
                    <th class="px-5 py-3.5 text-slate-400 font-bold uppercase tracking-wider">Status</th>
                    <th class="px-5 py-3.5 text-right text-slate-400 font-bold uppercase tracking-wider">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-white/5">
            <?php if(empty($subs)): ?>
            <tr><td colspan="7" class="px-5 py-12 text-center text-slate-500 font-medium">No subscription transaction records found in system.</td></tr>
            <?php endif; ?>
            <?php foreach($subs as $sub):
                $expiry = strtotime($sub['end_date']);
                $today  = time();
                $daysLeft = ceil(($expiry - $today) / 86400);
                $expired  = $daysLeft < 0;
                $warning  = $daysLeft >= 0 && $daysLeft <= 7;

                $subFeatures = json_decode($sub['package_features'], true) ?: [];
                $defaults = [
                    'max_floors' => 1,
                    'max_tables' => 5,
                    'max_cashiers' => 1,
                    'max_waiters' => 2,
                    'qr_ordering' => false,
                    'kitchen_display' => false,
                    'is_trial' => false
                ];
                $mergedFeatures = array_merge($defaults, $subFeatures);

                // If trial, make features advanced as per business requirement
                $isTrial = !empty($mergedFeatures['is_trial']) || (stripos($sub['package_name'], 'trial') !== false) || (stripos($sub['package_name'], 'free') !== false);
                if ($isTrial) {
                    $mergedFeatures['max_floors'] = null;
                    $mergedFeatures['max_tables'] = null;
                    $mergedFeatures['max_cashiers'] = null;
                    $mergedFeatures['max_waiters'] = null;
                    $mergedFeatures['qr_ordering'] = true;
                    $mergedFeatures['kitchen_display'] = true;
                    $mergedFeatures['is_trial'] = true;
                }

                $subDataJson = json_encode([
                    'id' => $sub['id'],
                    'restaurant_name' => $sub['restaurant_name'],
                    'restaurant_email' => $sub['restaurant_email'] ?? 'N/A',
                    'restaurant_phone' => $sub['restaurant_phone'] ?? 'N/A',
                    'restaurant_currency' => $sub['restaurant_currency'] ?? '$',
                    'package_name' => $sub['package_name'],
                    'amount' => $sub['amount'],
                    'package_price' => $sub['package_price'],
                    'coupon_code' => $sub['coupon_code'] ?? '',
                    'start_date' => date('M d, Y', strtotime($sub['start_date'])),
                    'end_date' => date('M d, Y', strtotime($sub['end_date'])),
                    'payment_status' => $sub['payment_status'],
                    'status' => $sub['status'],
                    'created_at' => date('M d, Y H:i', strtotime($sub['created_at'])),
                    'features' => $mergedFeatures,
                ]);

                // Determine display color class
                if ($sub['status'] === 'active') {
                    $statusBg = 'rgba(16,185,129,0.15)';
                    $statusColor = '#6ee7b7';
                } elseif ($sub['status'] === 'expired') {
                    $statusBg = 'rgba(239,68,68,0.15)';
                    $statusColor = '#fca5a5';
                } else {
                    $statusBg = 'rgba(255,255,255,0.06)';
                    $statusColor = '#94a3b8';
                }
            ?>
            <tr 
                x-show="(search === '' || <?php echo json_encode(strtolower($sub['restaurant_name'])); ?>.includes(search.toLowerCase()) || <?php echo json_encode(strtolower($sub['package_name'])); ?>.includes(search.toLowerCase())) && (statusFilter === 'all' || <?php echo json_encode($sub['status']); ?> === statusFilter)"
                class="hover:bg-white/[0.015] transition"
            >
                <td class="px-5 py-4 font-semibold text-white text-xs">
                    <?php echo htmlspecialchars($sub['restaurant_name']); ?>
                </td>
                <td class="px-5 py-4">
                    <span class="px-2 py-0.5 rounded bg-purple-500/10 border border-purple-500/20 text-purple-400 font-medium">
                        <?php echo htmlspecialchars($sub['package_name']); ?>
                    </span>
                </td>
                <td class="px-5 py-4 text-slate-300">
                    <?php echo date('M d, Y', strtotime($sub['start_date'])); ?>
                </td>
                <td class="px-5 py-4">
                    <span class="font-medium <?php echo $expired?'text-red-400':($warning?'text-yellow-400':'text-slate-300'); ?>">
                        <?php echo date('M d, Y', $expiry); ?>
                    </span>
                    <span class="ml-1 text-3xs <?php echo $expired?'text-red-500/80':($warning?'text-yellow-500/80':'text-slate-500'); ?>">
                        (<?php echo $expired ? 'Expired '.abs($daysLeft).'d ago' : $daysLeft.'d left'; ?>)
                    </span>
                </td>
                <td class="px-5 py-4 font-extrabold text-white text-xs">
                    <?php echo htmlspecialchars($sub['restaurant_currency'] ?? '$') . number_format($sub['amount'], 2); ?>
                </td>
                <td class="px-5 py-4">
                    <span class="px-2 py-0.5 rounded-full text-3xs font-extrabold uppercase border" style="background:<?php echo $statusBg; ?>; color:<?php echo $statusColor; ?>; border-color: currentColor;">
                        <?php echo htmlspecialchars($sub['status']); ?>
                    </span>
                </td>
                <td class="px-5 py-4 text-right">
                    <div class="flex items-center justify-end gap-1.5" x-data="{ expand: false }">
                        <!-- View Details -->
                        <button 
                            @click="openModal(<?php echo htmlspecialchars($subDataJson); ?>)" 
                            class="text-xs px-2.5 py-1.5 rounded-lg font-medium transition hover:brightness-110 flex items-center gap-1 bg-white/5 border border-white/10 text-white"
                        >
                            <i class="fas fa-eye text-2xs text-purple-400"></i> Details
                        </button>

                        <!-- Quick management (Renew / Extend) -->
                        <button 
                            @click="expand = !expand" 
                            class="text-xs px-2.5 py-1.5 rounded-lg font-medium transition hover:brightness-110 flex items-center gap-1" 
                            style="background:rgba(139,92,246,0.15); color:#c4b5fd; border:1px solid rgba(139,92,246,0.3)"
                        >
                            <i class="fas fa-sliders text-2xs"></i> Adjust
                        </button>

                        <!-- Absolute positioned overlay settings -->
                        <div 
                            x-show="expand" 
                            x-transition 
                            @click.away="expand = false"
                            class="absolute right-5 mt-8 z-10 p-4 rounded-xl text-left space-y-3 shadow-2xl border border-purple-500/20 bg-[#161825]" 
                            style="display:none; width: 280px;"
                        >
                            <p class="text-xs font-bold text-white border-b border-white/5 pb-1"><i class="fas fa-wrench text-purple-400 mr-1"></i> Subscription Adjustments</p>
                            <!-- Renew with new package -->
                            <form action="/restpo/superadmin/subscriptions/renew" method="POST" class="space-y-1.5">
                                <input type="hidden" name="subscription_id" value="<?php echo $sub['id']; ?>">
                                <input type="hidden" name="restaurant_id" value="<?php echo $sub['restaurant_id']; ?>">
                                <label class="block text-3xs uppercase tracking-wider text-slate-500 font-bold">Renew / Change Package</label>
                                <div class="flex gap-1.5">
                                    <select name="package_id" class="form-input text-xs py-1 px-2 rounded-lg bg-white/5 border-white/10 flex-1 text-slate-300">
                                        <?php foreach($packages as $pkg): ?>
                                        <option value="<?php echo $pkg['id']; ?>" <?php echo $pkg['id']==$sub['package_id']?'selected':''; ?>><?php echo htmlspecialchars($pkg['name']); ?> (<?php echo $pkg['duration_days']; ?>d)</option>
                                        <?php endforeach; ?>
                                    </select>
                                    <button type="submit" class="btn-primary text-xs py-1 px-3 rounded-lg">Renew</button>
                                </div>
                            </form>
                            
                            <!-- Extend by N days -->
                            <form action="/restpo/superadmin/subscriptions/extend" method="POST" class="space-y-1.5 pt-1.5 border-t border-white/5">
                                <input type="hidden" name="subscription_id" value="<?php echo $sub['id']; ?>">
                                <input type="hidden" name="restaurant_id" value="<?php echo $sub['restaurant_id']; ?>">
                                <label class="block text-3xs uppercase tracking-wider text-slate-500 font-bold">Extend duration by days</label>
                                <div class="flex gap-1.5">
                                    <input type="number" name="days" min="1" value="30" class="form-input text-xs py-1 px-2 rounded-lg bg-white/5 border-white/10 w-20 text-white">
                                    <button type="submit" class="text-xs px-3 py-1 rounded-lg font-medium transition flex-1 text-center" style="background:rgba(16,185,129,0.2); color:#6ee7b7; border:1px solid rgba(16,185,129,0.3)">Extend</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    </div>

    <!-- Details Modal -->
    <div 
        x-show="selectedSub !== null" 
        class="fixed inset-0 z-50 overflow-y-auto flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm"
        x-transition
        style="display: none;"
    >
        <div 
            @click.away="closeModal()" 
            class="relative w-full max-w-2xl rounded-3xl border border-white/10 p-6 overflow-hidden shadow-2xl"
            style="background: #0f111a; box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.6);"
        >
            <!-- Modal Glow Accents -->
            <div class="absolute -top-24 -right-24 w-48 h-48 rounded-full bg-purple-500/10 blur-3xl"></div>
            <div class="absolute -bottom-24 -left-24 w-48 h-48 rounded-full bg-blue-500/10 blur-3xl"></div>

            <!-- Header -->
            <div class="flex justify-between items-start pb-4 border-b border-white/5">
                <div>
                    <span class="text-3xs text-purple-400 font-extrabold tracking-widest uppercase">Transaction History Details</span>
                    <h3 class="text-lg font-bold text-white mt-1" x-text="selectedSub ? selectedSub.restaurant_name : ''"></h3>
                </div>
                <button @click="closeModal()" class="text-slate-400 hover:text-white transition">
                    <i class="fas fa-times text-base"></i>
                </button>
            </div>

            <!-- Content -->
            <div class="mt-6 space-y-5" x-show="selectedSub">
                <!-- Row 1: Profile & Core Invoicing -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Restaurant Contact Profile -->
                    <div class="p-4 rounded-2xl bg-white/[0.02] border border-white/5 space-y-2">
                        <p class="text-2xs font-extrabold uppercase tracking-wider text-purple-400"><i class="fas fa-address-card mr-1"></i> Restaurant Profile</p>
                        <div class="text-xs space-y-2 text-slate-300">
                            <div class="flex justify-between items-center">
                                <span class="text-slate-500">Contact Email:</span>
                                <span class="font-bold text-white" x-text="selectedSub.restaurant_email"></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-slate-500">Contact Phone:</span>
                                <span class="font-bold text-white" x-text="selectedSub.restaurant_phone"></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-slate-500">Config Currency:</span>
                                <span class="font-bold text-white" x-text="selectedSub.restaurant_currency"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Subscription Core Details -->
                    <div class="p-4 rounded-2xl bg-white/[0.02] border border-white/5 space-y-2">
                        <p class="text-2xs font-extrabold uppercase tracking-wider text-blue-400"><i class="fas fa-file-invoice mr-1"></i> Billing &amp; Invoice</p>
                        <div class="text-xs space-y-2 text-slate-300">
                            <div class="flex justify-between items-center">
                                <span class="text-slate-500">Plan Purchased:</span>
                                <span class="font-bold text-white" x-text="selectedSub.package_name"></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-slate-500">Amount Paid:</span>
                                <span class="font-extrabold text-white text-sm" x-text="selectedSub.restaurant_currency + parseFloat(selectedSub.amount).toFixed(2)"></span>
                            </div>
                            <template x-if="selectedSub.coupon_code">
                                <div class="flex justify-between items-center text-xs text-emerald-400 border-t border-white/5 pt-2 mt-2">
                                    <span class="text-slate-500">Coupon Used:</span>
                                    <span class="font-bold" x-text="selectedSub.coupon_code + ' (-' + selectedSub.restaurant_currency + (parseFloat(selectedSub.package_price) - parseFloat(selectedSub.amount)).toFixed(2) + ')'"></span>
                                </div>
                            </template>
                            <div class="flex justify-between items-center">
                                <span class="text-slate-500">Payment Status:</span>
                                <span class="font-extrabold text-emerald-400 uppercase text-3xs px-2 py-0.5 rounded-full bg-emerald-500/10 border border-emerald-500/20" x-text="selectedSub.payment_status"></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Row 2: Duration / Timestamps -->
                <div class="p-4 rounded-2xl bg-white/[0.02] border border-white/5 space-y-3">
                    <p class="text-2xs font-extrabold uppercase tracking-wider text-emerald-400"><i class="fas fa-calendar-days mr-1"></i> Duration &amp; Active Dates</p>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-xs">
                        <div>
                            <p class="text-slate-500 text-3xs uppercase tracking-wider">Start Date</p>
                            <p class="font-bold text-white mt-1" x-text="selectedSub.start_date"></p>
                        </div>
                        <div>
                            <p class="text-slate-500 text-3xs uppercase tracking-wider">End Date</p>
                            <p class="font-bold text-white mt-1" x-text="selectedSub.end_date"></p>
                        </div>
                        <div>
                            <p class="text-slate-500 text-3xs uppercase tracking-wider">Purchased At</p>
                            <p class="font-bold text-slate-300 mt-1" x-text="selectedSub.created_at"></p>
                        </div>
                        <div>
                            <p class="text-slate-500 text-3xs uppercase tracking-wider">Current Status</p>
                            <span class="inline-block mt-1 font-bold text-3xs uppercase px-2 py-0.5 rounded-full border"
                                  :style="selectedSub.status === 'active' ? 'background: rgba(16,185,129,0.15); color: #6ee7b7; border-color: rgba(16,185,129,0.25);' : 'background: rgba(239,68,68,0.15); color: #fca5a5; border-color: rgba(239,68,68,0.25);'"
                                  x-text="selectedSub.status"></span>
                        </div>
                    </div>
                </div>

                <!-- Row 3: Package Limits -->
                <div class="p-4 rounded-2xl bg-white/[0.02] border border-white/5 space-y-3">
                    <p class="text-2xs font-extrabold uppercase tracking-wider text-amber-400"><i class="fas fa-chart-pie mr-1"></i> Package Quota Limits</p>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-xs">
                        <div>
                            <p class="text-slate-500 text-3xs uppercase tracking-wider">Max Floors</p>
                            <p class="font-bold text-white mt-1" x-text="selectedSub.features.max_floors === null ? 'Unlimited' : selectedSub.features.max_floors"></p>
                        </div>
                        <div>
                            <p class="text-slate-500 text-3xs uppercase tracking-wider">Max Tables</p>
                            <p class="font-bold text-white mt-1" x-text="selectedSub.features.max_tables === null ? 'Unlimited' : selectedSub.features.max_tables"></p>
                        </div>
                        <div>
                            <p class="text-slate-500 text-3xs uppercase tracking-wider">Max Cashiers</p>
                            <p class="font-bold text-white mt-1" x-text="selectedSub.features.max_cashiers === null ? 'Unlimited' : selectedSub.features.max_cashiers"></p>
                        </div>
                        <div>
                            <p class="text-slate-500 text-3xs uppercase tracking-wider">Max Waiters</p>
                            <p class="font-bold text-white mt-1" x-text="selectedSub.features.max_waiters === null ? 'Unlimited' : selectedSub.features.max_waiters"></p>
                        </div>
                    </div>
                    <div class="grid grid-cols-2 gap-4 text-xs border-t border-white/5 pt-3">
                        <div class="flex items-center justify-between">
                            <span class="text-slate-500">QR Table Ordering:</span>
                            <span class="font-bold" :class="selectedSub.features.qr_ordering ? 'text-emerald-400' : 'text-red-500/50'" x-text="selectedSub.features.qr_ordering ? '✓ Supported' : '✗ Unsupported'"></span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="text-slate-500">Kitchen Display System:</span>
                            <span class="font-bold" :class="selectedSub.features.kitchen_display ? 'text-emerald-400' : 'text-red-500/50'" x-text="selectedSub.features.kitchen_display ? '✓ Supported' : '✗ Unsupported'"></span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Footer -->
            <div class="mt-6 pt-4 border-t border-white/5 flex justify-end">
                <button @click="closeModal()" class="py-2 px-5 text-xs font-semibold text-white rounded-xl bg-white/5 hover:bg-white/10 active:scale-[0.98] transition">
                    Close Details
                </button>
            </div>
        </div>
    </div>

    <!-- Assign Subscription to Restaurant without one -->
    <?php if(!empty($noSub)): ?>
    <div class="rounded-2xl p-5 border border-yellow-500/20 bg-yellow-500/[0.03]">
        <h3 class="font-semibold text-white mb-4 flex items-center gap-2"><i class="fas fa-exclamation-triangle text-yellow-400"></i> Restaurants Without Subscription (<?php echo count($noSub); ?>)</h3>
        <div class="space-y-2.5">
        <?php foreach($noSub as $r): ?>
        <div class="flex items-center justify-between p-3.5 rounded-xl border border-white/5 bg-white/[0.015]">
            <span class="text-white font-medium text-xs"><?php echo htmlspecialchars($r['name']); ?></span>
            <div x-data="{show:false}">
                <button @click="show=!show" class="text-xs px-3 py-1.5 rounded-lg font-medium" style="background:rgba(245,158,11,0.2); color:#fcd34d; border:1px solid rgba(245,158,11,0.3)">Assign Package</button>
                <form x-show="show" action="/restpo/superadmin/subscriptions/assign" method="POST" class="mt-3 flex gap-2" style="display:none">
                    <input type="hidden" name="restaurant_id" value="<?php echo $r['id']; ?>">
                    <select name="package_id" class="form-input text-xs py-1.5 px-3 rounded-xl bg-white/5 border-white/10 flex-1 text-slate-300">
                        <?php foreach($packages as $pkg): ?><option value="<?php echo $pkg['id']; ?>"><?php echo htmlspecialchars($pkg['name']); ?></option><?php endforeach; ?>
                    </select>
                    <button type="submit" class="btn-primary text-xs py-1.5 px-3.5 rounded-xl">Assign</button>
                </form>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
</div>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function renewSubscription() {
        $this->requireSuperAdmin();
        $db = getDB();

        $sub_id    = $_POST['subscription_id'];
        $rest_id   = $_POST['restaurant_id'];
        $pkg_id    = $_POST['package_id'];

        $pkg = $db->prepare('SELECT * FROM packages WHERE id = ?');
        $pkg->execute([$pkg_id]);
        $pkg = $pkg->fetch();
        if (!$pkg) { header('Location: /restpo/superadmin/subscriptions?error=Package+not+found'); exit; }

        $new_end = date('Y-m-d', strtotime('+' . $pkg['duration_days'] . ' days'));

        // Deactivate old subscription
        $db->prepare('UPDATE subscriptions SET status="inactive" WHERE id=?')->execute([$sub_id]);

        // Insert new subscription
        $db->prepare('INSERT INTO subscriptions (restaurant_id, package_id, start_date, end_date, amount, payment_status, status) VALUES (?,?,CURDATE(),?,?,"paid","active")')
           ->execute([$rest_id, $pkg_id, $new_end, $pkg['price']]);

        $db->prepare('UPDATE restaurants SET subscription_ends_at=?, package_id=? WHERE id=?')
           ->execute([$new_end . ' 23:59:59', $pkg_id, $rest_id]);

        header('Location: /restpo/superadmin/subscriptions?msg=Subscription+renewed+successfully'); exit;
    }

    public function extendSubscription() {
        $this->requireSuperAdmin();
        $db = getDB();

        $sub_id  = $_POST['subscription_id'];
        $rest_id = $_POST['restaurant_id'];
        $days    = max(1, intval($_POST['days']));

        // Get current end_date
        $cur = $db->prepare('SELECT end_date FROM subscriptions WHERE id = ?');
        $cur->execute([$sub_id]);
        $row = $cur->fetch();
        $base = max(time(), strtotime($row['end_date'])); // extend from today if already expired
        $new_end = date('Y-m-d', strtotime("+{$days} days", $base));

        $db->prepare('UPDATE subscriptions SET end_date=?, status="active" WHERE id=?')
           ->execute([$new_end, $sub_id]);
        $db->prepare('UPDATE restaurants SET subscription_ends_at=? WHERE id=?')
           ->execute([$new_end . ' 23:59:59', $rest_id]);

        header('Location: /restpo/superadmin/subscriptions?msg=' . urlencode("Extended by {$days} days successfully")); exit;
    }

    public function assignSubscription() {
        $this->requireSuperAdmin();
        $db = getDB();

        $rest_id = $_POST['restaurant_id'];
        $pkg_id  = $_POST['package_id'];

        $pkg = $db->prepare('SELECT * FROM packages WHERE id = ?');
        $pkg->execute([$pkg_id]);
        $pkg = $pkg->fetch();
        if (!$pkg) { header('Location: /restpo/superadmin/subscriptions?error=Package+not+found'); exit; }

        $new_end = date('Y-m-d', strtotime('+' . $pkg['duration_days'] . ' days'));

        // Deactivate old
        $db->prepare('UPDATE subscriptions SET status="inactive" WHERE restaurant_id=?')->execute([$rest_id]);
        // Insert new
        $db->prepare('INSERT INTO subscriptions (restaurant_id, package_id, start_date, end_date, amount, payment_status, status) VALUES (?,?,CURDATE(),?,?,"paid","active")')
           ->execute([$rest_id, $pkg_id, $new_end, $pkg['price']]);
        $db->prepare('UPDATE restaurants SET subscription_ends_at=? WHERE id=?')
           ->execute([$new_end . ' 23:59:59', $rest_id]);

        header('Location: /restpo/superadmin/subscriptions?msg=Subscription+assigned+successfully'); exit;
    }

    public function approveSubscription() {
        $this->requireSuperAdmin();
        $db = getDB();
        
        $sub_id = $_POST['subscription_id'] ?? null;
        if (!$sub_id) {
            header('Location: /restpo/superadmin/subscriptions?error=Invalid+subscription+ID'); exit;
        }
        
        // Fetch subscription details
        $stmt = $db->prepare('
            SELECT s.*, p.name AS package_name, p.duration_days, p.features AS package_features, p.price,
                   r.id AS rest_id, r.name AS rest_name, r.email AS rest_email, r.subscription_ends_at
            FROM subscriptions s
            JOIN packages p ON p.id = s.package_id
            JOIN restaurants r ON r.id = s.restaurant_id
            WHERE s.id = ? AND s.status = "pending"
        ');
        $stmt->execute([$sub_id]);
        $sub = $stmt->fetch();
        
        if (!$sub) {
            header('Location: /restpo/superadmin/subscriptions?error=Subscription+request+not+found+or+already+processed'); exit;
        }
        
        $db->beginTransaction();
        try {
            $rest_id = $sub['rest_id'];
            
            // Deactivate all previous active subscriptions for this restaurant
            $db->prepare('UPDATE subscriptions SET status = "cancelled" WHERE restaurant_id = ? AND status = "active"')->execute([$rest_id]);
            
            // Calculate new end date based on package duration and current ends_at (if not expired)
            $remainingDays = 0;
            $ends_at = $sub['subscription_ends_at'];
            if ($ends_at) {
                $expiry = strtotime($ends_at);
                $now = time();
                if ($expiry > $now) {
                    $todayDate = date('Y-m-d');
                    $endDateStr = date('Y-m-d', $expiry);
                    if ($endDateStr >= $todayDate) {
                        $remainingDays = (int)((strtotime($endDateStr) - strtotime($todayDate)) / 86400);
                    }
                }
            }
            
            $features = json_decode($sub['package_features'] ?? '{}', true) ?: [];
            // Fetch restaurant details to check for overrides
            $rOverride = $db->prepare('SELECT extra_features FROM restaurants WHERE id = ?');
            $rOverride->execute([$rest_id]);
            $overrides = json_decode($rOverride->fetchColumn() ?? '{}', true) ?: [];
            
            $isLifetime = !empty($features['is_lifetime']) || !empty($overrides['is_lifetime']);
            
            $total_duration = $isLifetime ? 36500 : ($sub['duration_days'] + $remainingDays);
            $new_end = $isLifetime ? '2099-12-31' : date('Y-m-d', strtotime('+' . $total_duration . ' days'));
            
            // Update subscription to active and paid
            $db->prepare('UPDATE subscriptions SET payment_status = "paid", status = "active", end_date = ? WHERE id = ?')
               ->execute([$new_end, $sub_id]);
            
            // Update restaurant package_id and ends_at
            $db->prepare('UPDATE restaurants SET package_id = ?, subscription_ends_at = ? WHERE id = ?')
               ->execute([$sub['package_id'], $new_end . ' 23:59:59', $rest_id]);

            // Increment coupon usage count if used
            if (!empty($sub['coupon_code'])) {
                $db->prepare('UPDATE coupons SET used_count = used_count + 1 WHERE code = ?')->execute([$sub['coupon_code']]);
            }
               
            // Fetch restaurant admin email to send notice
            $adminUser = $db->prepare('SELECT name, email FROM users WHERE restaurant_id = ? AND role = "admin" LIMIT 1');
            $adminUser->execute([$rest_id]);
            $admin = $adminUser->fetch();
            
            if ($admin && !empty($admin['email'])) {
                try {
                    MailHelper::sendSubscriptionApprovedEmail($admin['email'], $admin['name'], $sub['package_name'], $isLifetime ? 'Lifetime' : $new_end);
                } catch (\Exception $mailEx) {
                    // Do not block transaction
                }
            }
            
            $db->commit();
            header('Location: /restpo/superadmin/subscriptions?msg=Subscription+request+approved+successfully'); exit;
        } catch (\Exception $e) {
            $db->rollBack();
            header('Location: /restpo/superadmin/subscriptions?error=' . urlencode($e->getMessage())); exit;
        }
    }
    
    public function rejectSubscription() {
        $this->requireSuperAdmin();
        $db = getDB();
        
        $sub_id = $_POST['subscription_id'] ?? null;
        if (!$sub_id) {
            header('Location: /restpo/superadmin/subscriptions?error=Invalid+subscription+ID'); exit;
        }
        
        // Fetch subscription
        $stmt = $db->prepare('SELECT * FROM subscriptions WHERE id = ? AND status = "pending"');
        $stmt->execute([$sub_id]);
        $sub = $stmt->fetch();
        
        if (!$sub) {
            header('Location: /restpo/superadmin/subscriptions?error=Subscription+request+not+found+or+already+processed'); exit;
        }
        
        // Update subscription to cancelled/failed
        $db->prepare('UPDATE subscriptions SET payment_status = "failed", status = "cancelled" WHERE id = ?')
           ->execute([$sub_id]);
           
        // Fetch restaurant admin email
        $adminUser = $db->prepare('SELECT name, email FROM users WHERE restaurant_id = ? AND role = "admin" LIMIT 1');
        $adminUser->execute([$sub['restaurant_id']]);
        $admin = $adminUser->fetch();
        
        if ($admin && !empty($admin['email'])) {
            try {
                $subject = "Subscription Request Rejected - RestPO";
                $body = "
                <p>Hello " . htmlspecialchars($admin['name']) . ",</p>
                <p>We regret to inform you that your request for a subscription renewal/purchase has been rejected by the System Administrator.</p>
                <p>Please double-check your billing details or contact support for help.</p>
                ";
                MailHelper::send($admin['email'], $subject, $body);
            } catch (\Exception $ex) {
                // Ignore
            }
        }
        
        header('Location: /restpo/superadmin/subscriptions?msg=Subscription+request+rejected+successfully'); exit;
    }

    // ── Platform Analytics ───────────────────────────────────────
    public function analytics() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Platform Analytics';

        // ── KPI Summary ──
        $kpi = [
            'total_restaurants' => $db->query('SELECT COUNT(*) FROM restaurants')->fetchColumn(),
            'active_subs'       => $db->query('SELECT COUNT(*) FROM subscriptions WHERE status="active" AND end_date >= CURDATE()')->fetchColumn(),
            'total_revenue'     => (float)$db->query('SELECT COALESCE(SUM(amount),0) FROM subscriptions WHERE payment_status="paid"')->fetchColumn(),
            'total_orders'      => $db->query('SELECT COUNT(*) FROM orders WHERE payment_status="paid"')->fetchColumn(),
            'total_users'       => $db->query('SELECT COUNT(*) FROM users WHERE role != "superadmin"')->fetchColumn(),
            'expiring_soon'     => $db->query('SELECT COUNT(*) FROM subscriptions WHERE status="active" AND DATEDIFF(end_date, CURDATE()) BETWEEN 0 AND 7')->fetchColumn(),
        ];

        // ── Last 12 months subscription revenue ──
        $revenueRows = $db->query("
            SELECT DATE_FORMAT(created_at, '%Y-%m') AS month,
                   COALESCE(SUM(amount),0) AS revenue
            FROM subscriptions
            WHERE payment_status='paid'
              AND created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
            GROUP BY month ORDER BY month ASC
        ")->fetchAll();

        // ── Orders per day last 30 days ──
        $ordersRows = $db->query("
            SELECT DATE(created_at) AS day, COUNT(*) AS cnt
            FROM orders
            WHERE payment_status='paid'
              AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
            GROUP BY day ORDER BY day ASC
        ")->fetchAll();

        // ── Top restaurants by revenue ──
        $topRestaurants = $db->query("
            SELECT r.name, COALESCE(SUM(o.total),0) AS revenue, COUNT(o.id) AS orders
            FROM restaurants r
            LEFT JOIN orders o ON o.restaurant_id = r.id AND o.payment_status='paid'
            GROUP BY r.id, r.name
            ORDER BY revenue DESC LIMIT 8
        ")->fetchAll();

        // ── Package distribution ──
        $packageDist = $db->query("
            SELECT p.name, COUNT(s.id) AS cnt
            FROM subscriptions s
            JOIN packages p ON p.id = s.package_id
            WHERE s.status='active'
            GROUP BY p.id, p.name
        ")->fetchAll();

        // ── Monthly new restaurants ──
        $newRestaurants = $db->query("
            SELECT DATE_FORMAT(created_at,'%Y-%m') AS month, COUNT(*) AS cnt
            FROM restaurants
            WHERE created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
            GROUP BY month ORDER BY month ASC
        ")->fetchAll();

        ob_start(); ?>
<div class="space-y-6">

    <!-- KPI Cards -->
    <div class="grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4">
        <?php
        $kpiCards = [
            ['icon'=>'fa-store',        'label'=>'Restaurants',     'value'=>number_format($kpi['total_restaurants']), 'color'=>'#a78bfa','bg'=>'rgba(139,92,246,0.15)'],
            ['icon'=>'fa-credit-card',  'label'=>'Active Subs',     'value'=>number_format($kpi['active_subs']),       'color'=>'#6ee7b7','bg'=>'rgba(16,185,129,0.15)'],
            ['icon'=>'fa-dollar-sign',  'label'=>'Total Revenue',   'value'=>($_SESSION['currency'] ?? '$').number_format($kpi['total_revenue'],0),'color'=>'#fcd34d','bg'=>'rgba(245,158,11,0.15)'],
            ['icon'=>'fa-receipt',      'label'=>'Total Orders',    'value'=>number_format($kpi['total_orders']),      'color'=>'#93c5fd','bg'=>'rgba(59,130,246,0.15)'],
            ['icon'=>'fa-users',        'label'=>'Total Users',     'value'=>number_format($kpi['total_users']),       'color'=>'#f9a8d4','bg'=>'rgba(236,72,153,0.15)'],
            ['icon'=>'fa-exclamation-triangle','label'=>'Expiring Soon','value'=>number_format($kpi['expiring_soon']), 'color'=>'#fca5a5','bg'=>'rgba(239,68,68,0.15)'],
        ];
        foreach($kpiCards as $c): ?>
        <div class="rounded-2xl p-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
            <div class="flex justify-between items-start mb-3">
                <p class="text-slate-500 text-xs font-medium leading-tight"><?php echo $c['label']; ?></p>
                <div class="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0" style="background:<?php echo $c['bg']; ?>">
                    <i class="fas <?php echo $c['icon']; ?> text-xs" style="color:<?php echo $c['color']; ?>"></i>
                </div>
            </div>
            <p class="text-2xl font-bold text-white"><?php echo $c['value']; ?></p>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Charts Row 1 -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-5">
        <!-- Revenue Chart -->
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
            <div class="flex justify-between items-center mb-4">
                <div>
                    <h3 class="font-semibold text-white">Subscription Revenue</h3>
                    <p class="text-xs text-slate-500 mt-0.5">Last 12 months</p>
                </div>
                <div class="text-xs text-purple-400 font-semibold px-2 py-1 rounded-lg" style="background:rgba(139,92,246,0.15)">Monthly</div>
            </div>
            <div id="revenueChart"></div>
        </div>

        <!-- Orders Volume -->
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
            <div class="flex justify-between items-center mb-4">
                <div>
                    <h3 class="font-semibold text-white">Order Volume</h3>
                    <p class="text-xs text-slate-500 mt-0.5">Last 30 days (all restaurants)</p>
                </div>
                <div class="text-xs text-blue-400 font-semibold px-2 py-1 rounded-lg" style="background:rgba(59,130,246,0.15)">Daily</div>
            </div>
            <div id="ordersChart"></div>
        </div>
    </div>

    <!-- Charts Row 2 -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-5">
        <!-- New Restaurants -->
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
            <h3 class="font-semibold text-white mb-1">New Restaurants</h3>
            <p class="text-xs text-slate-500 mb-4">Monthly growth</p>
            <div id="growthChart"></div>
        </div>

        <!-- Package Distribution -->
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
            <h3 class="font-semibold text-white mb-1">Package Distribution</h3>
            <p class="text-xs text-slate-500 mb-4">Active subscriptions</p>
            <div id="packageChart"></div>
        </div>

        <!-- Top Restaurants Table -->
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
            <h3 class="font-semibold text-white mb-4">Top Restaurants by Revenue</h3>
            <div class="space-y-3">
                <?php foreach(array_slice($topRestaurants, 0, 6) as $i => $r):
                    $maxRev = $topRestaurants[0]['revenue'] ?: 1;
                    $pct    = round($r['revenue'] / $maxRev * 100);
                ?>
                <div>
                    <div class="flex justify-between text-xs mb-1">
                        <span class="text-slate-300 font-medium truncate pr-2"><?php echo htmlspecialchars($r['name']); ?></span>
                        <span class="text-slate-400 flex-shrink-0"><?php echo $_SESSION['currency'] ?? '$'; ?><?php echo number_format($r['revenue'],0); ?></span>
                    </div>
                    <div class="h-1.5 rounded-full" style="background:rgba(255,255,255,0.07)">
                        <div class="h-1.5 rounded-full transition-all" style="width:<?php echo $pct; ?>%; background:linear-gradient(90deg,#8b5cf6,#3b82f6)"></div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php if(empty($topRestaurants)): ?>
                <p class="text-slate-500 text-sm text-center py-6">No order data yet.</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
const chartDefaults = {
    chart: { background: 'transparent', toolbar: { show: false }, fontFamily: 'Inter,sans-serif' },
    theme: { mode: 'dark' },
    grid: { borderColor: 'rgba(255,255,255,0.06)', strokeDashArray: 3 },
    tooltip: { theme: 'dark' },
};

// Revenue Chart
const revenueData = <?php echo json_encode(array_values($revenueRows)); ?>;
new ApexCharts(document.getElementById('revenueChart'), {
    ...chartDefaults,
    chart: { ...chartDefaults.chart, type: 'area', height: 220 },
    series: [{ name: 'Revenue (<?php echo $_SESSION['currency'] ?? '$'; ?>)', data: revenueData.map(r => parseFloat(r.revenue)) }],
    xaxis: { categories: revenueData.map(r => r.month), labels: { style: { colors: '#64748b', fontSize: '11px' } } },
    yaxis: { labels: { style: { colors: '#64748b', fontSize: '11px' }, formatter: v => '<?php echo $_SESSION['currency'] ?? '$'; ?>'+v.toLocaleString() } },
    colors: ['#8b5cf6'],
    fill: { type: 'gradient', gradient: { shadeIntensity: 1, opacityFrom: 0.4, opacityTo: 0.0 } },
    stroke: { curve: 'smooth', width: 2 },
    dataLabels: { enabled: false },
}).render();

// Orders Chart
const ordersData = <?php echo json_encode(array_values($ordersRows)); ?>;
new ApexCharts(document.getElementById('ordersChart'), {
    ...chartDefaults,
    chart: { ...chartDefaults.chart, type: 'bar', height: 220 },
    series: [{ name: 'Orders', data: ordersData.map(r => parseInt(r.cnt)) }],
    xaxis: { categories: ordersData.map(r => r.day.substr(5)), labels: { style: { colors: '#64748b', fontSize: '10px' }, rotate: -45 } },
    yaxis: { labels: { style: { colors: '#64748b', fontSize: '11px' } } },
    colors: ['#3b82f6'],
    plotOptions: { bar: { borderRadius: 4, columnWidth: '60%' } },
    dataLabels: { enabled: false },
}).render();

// Growth Chart
const growthData = <?php echo json_encode(array_values($newRestaurants)); ?>;
new ApexCharts(document.getElementById('growthChart'), {
    ...chartDefaults,
    chart: { ...chartDefaults.chart, type: 'line', height: 200 },
    series: [{ name: 'New Restaurants', data: growthData.map(r => parseInt(r.cnt)) }],
    xaxis: { categories: growthData.map(r => r.month), labels: { style: { colors: '#64748b', fontSize: '10px' } } },
    yaxis: { labels: { style: { colors: '#64748b' }, formatter: v => Math.round(v) } },
    colors: ['#10b981'],
    stroke: { curve: 'smooth', width: 2 },
    markers: { size: 4, colors: ['#10b981'] },
    dataLabels: { enabled: false },
}).render();

// Package Donut
const pkgData = <?php echo json_encode(array_values($packageDist)); ?>;
if (pkgData.length > 0) {
    new ApexCharts(document.getElementById('packageChart'), {
        ...chartDefaults,
        chart: { ...chartDefaults.chart, type: 'donut', height: 200 },
        series: pkgData.map(p => parseInt(p.cnt)),
        labels: pkgData.map(p => p.name),
        colors: ['#8b5cf6','#3b82f6','#10b981','#f59e0b','#ef4444'],
        legend: { position: 'bottom', labels: { colors: '#94a3b8' }, fontSize: '11px' },
        plotOptions: { pie: { donut: { size: '60%' } } },
        dataLabels: { style: { fontSize: '11px' } },
    }).render();
} else {
    document.getElementById('packageChart').innerHTML = '<p class="text-slate-500 text-sm text-center py-10">No active subscriptions</p>';
}
</script>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function analyticsApi() {
        $this->requireSuperAdmin();
        header('Content-Type: application/json');
        $db  = getDB();
        $type = $_GET['type'] ?? 'revenue';

        if ($type === 'revenue') {
            $rows = $db->query("
                SELECT DATE_FORMAT(created_at,'%Y-%m') AS month, COALESCE(SUM(amount),0) AS revenue
                FROM subscriptions WHERE payment_status='paid'
                  AND created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
                GROUP BY month ORDER BY month
            ")->fetchAll();
            echo json_encode($rows);
        } elseif ($type === 'orders') {
            $rows = $db->query("
                SELECT DATE(created_at) AS day, COUNT(*) AS cnt
                FROM orders WHERE payment_status='paid'
                  AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
                GROUP BY day ORDER BY day
            ")->fetchAll();
            echo json_encode($rows);
        } else {
            echo json_encode([]);
        }
        exit;
    }

    public function sms() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Communication Center';
        
        $customersList = [];

        // Fetch Restaurant Admins
        $restaurantAdmins = [];
        try {
            $stmt = $db->query('
                SELECT u.name, u.email, u.phone, r.name as restaurant_name 
                FROM users u 
                JOIN restaurants r ON u.restaurant_id = r.id 
                WHERE u.role = "admin"
                ORDER BY r.name ASC
            ');
            $restaurantAdmins = $stmt->fetchAll();
        } catch (\Exception $e) {}

        ob_start();
        require 'app/Views/superadmin/sms.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function sendPromotionalSMS() {
        $this->requireSuperAdmin();
        $db = getDB();
        
        $channel = $_POST['channel'] ?? 'sms'; // 'sms' or 'email'
        $recipient_category = $_POST['recipient_category'] ?? 'admins'; // 'customers' or 'admins'
        $subject = trim($_POST['subject'] ?? 'Notification from RestPO');
        $message = trim($_POST['message'] ?? '');
        $targets = $_POST['targets'] ?? 'custom';
        
        if (empty($message)) {
            header('Location: /restpo/superadmin/sms?error=Message+body+cannot+be+empty'); exit;
        }
        
        $recipients = []; // list of phone numbers OR email addresses
        
        if ($recipient_category === 'customers') {
            // Customers are SMS only
            $channel = 'sms';
            $customNumbers = trim($_POST['custom_numbers'] ?? '');
            $selectedPhones = $_POST['selected_phones'] ?? [];
            
            if ($targets === 'custom' && !empty($customNumbers)) {
                $numbers = explode(',', $customNumbers);
                foreach ($numbers as $num) {
                    $num = trim($num);
                    if ($num !== '') $recipients[] = $num;
                }
            } elseif ($targets === 'selected' && !empty($selectedPhones)) {
                $recipients = $selectedPhones;
            } elseif ($targets === 'all') {
                $phones = [];
                try {
                    $stmt = $db->query('SELECT DISTINCT phone FROM feedbacks WHERE phone IS NOT NULL AND phone != ""');
                    while ($p = $stmt->fetchColumn()) { $phones[trim($p)] = true; }
                } catch (\Exception $e) {}
                try {
                    $checkCol = $db->query("SHOW COLUMNS FROM orders LIKE 'delivery_customer_phone'")->fetch();
                    if ($checkCol) {
                        $stmt = $db->query('SELECT DISTINCT delivery_customer_phone FROM orders WHERE delivery_customer_phone IS NOT NULL AND delivery_customer_phone != ""');
                        while ($p = $stmt->fetchColumn()) { $phones[trim($p)] = true; }
                    }
                } catch (\Exception $e) {}
                $recipients = array_keys($phones);
            }
        } else {
            // Restaurant Admins can receive Email or SMS
            if ($channel === 'email') {
                $customEmails = trim($_POST['custom_emails'] ?? '');
                $selectedEmails = $_POST['selected_emails'] ?? [];
                
                if ($targets === 'custom' && !empty($customEmails)) {
                    $emails = explode(',', $customEmails);
                    foreach ($emails as $em) {
                        $em = trim($em);
                        if (filter_var($em, FILTER_VALIDATE_EMAIL)) $recipients[] = $em;
                    }
                } elseif ($targets === 'selected' && !empty($selectedEmails)) {
                    $recipients = $selectedEmails;
                } elseif ($targets === 'all') {
                    try {
                        $stmt = $db->query('SELECT email FROM users WHERE role = "admin" AND email IS NOT NULL AND email != ""');
                        $recipients = $stmt->fetchAll(PDO::FETCH_COLUMN);
                    } catch (\Exception $e) {}
                }
            } else {
                // SMS for admins
                $customNumbers = trim($_POST['custom_numbers'] ?? '');
                $selectedPhones = $_POST['selected_phones'] ?? [];
                
                if ($targets === 'custom' && !empty($customNumbers)) {
                    $numbers = explode(',', $customNumbers);
                    foreach ($numbers as $num) {
                        $num = trim($num);
                        if ($num !== '') $recipients[] = $num;
                    }
                } elseif ($targets === 'selected' && !empty($selectedPhones)) {
                    $recipients = $selectedPhones;
                } elseif ($targets === 'all') {
                    try {
                        $stmt = $db->query('SELECT phone FROM users WHERE role = "admin" AND phone IS NOT NULL AND phone != ""');
                        $recipients = $stmt->fetchAll(PDO::FETCH_COLUMN);
                    } catch (\Exception $e) {}
                }
            }
        }
        
        if (empty($recipients)) {
            header('Location: /restpo/superadmin/sms?error=No+valid+recipients+found'); exit;
        }
        
        $sentCount = 0;
        foreach ($recipients as $recipient) {
            if ($channel === 'email') {
                if (MailHelper::send($recipient, $subject, $message)) {
                    $sentCount++;
                }
            } else {
                if (SMSHelper::send($recipient, $message)) {
                    $sentCount++;
                }
            }
        }
        
        $typeLabel = ($channel === 'email') ? 'emails' : 'SMS messages';
        header('Location: /restpo/superadmin/sms?msg=' . urlencode("Successfully sent {$sentCount} of " . count($recipients) . " {$typeLabel}")); exit;
    }

    public function settings() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'SMTP & SMS Settings';
        
        // Fetch all system settings
        $settings = [];
        try {
            $rows = $db->query('SELECT * FROM system_settings')->fetchAll();
            foreach ($rows as $row) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
        } catch (\Exception $e) {}

        $siteSettings = [];
        try {
            $rows = $db->query('SELECT * FROM site_settings')->fetchAll();
            foreach ($rows as $row) {
                $siteSettings[$row['setting_key']] = $row['setting_value'];
            }
        } catch (\Exception $e) {}
        
        ob_start();
        require 'app/Views/superadmin/settings.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }
    
    public function updateSettings() {
        $this->requireSuperAdmin();
        $db = getDB();
        
        $fields = [
            'smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_encryption', 'smtp_from_email', 'smtp_from_name',
            'sms_gateway', 'sms_twilio_sid', 'sms_twilio_token', 'sms_twilio_from', 'sms_generic_url'
        ];
        
        $db->beginTransaction();
        try {
            $stmt = $db->prepare('INSERT INTO system_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?');
            foreach ($fields as $field) {
                $val = $_POST[$field] ?? '';
                $stmt->execute([$field, $val, $val]);
            }
            $db->commit();
            header('Location: /restpo/superadmin/settings?msg=System+settings+updated+successfully'); exit;
        } catch (\Exception $e) {
            $db->rollBack();
            header('Location: /restpo/superadmin/settings?error=' . urlencode($e->getMessage())); exit;
        }
    }

    public function updateLandingSettings() {
        $this->requireSuperAdmin();
        $db = getDB();
        
        $stmt = $db->prepare('INSERT INTO site_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?');
        
        for ($i = 0; $i < 6; $i++) {
            $key = 'feature_video_' . $i;
            $url = trim($_POST[$key] ?? '');
            
            // Auto-convert standard YouTube URLs to embed links
            if (!empty($url)) {
                if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i', $url, $match)) {
                    $url = 'https://www.youtube.com/embed/' . $match[1];
                }
            }
            
            $stmt->execute([$key, $url, $url]);
        }

        // ── Footer Text & Social Links ──
        $footerFields = ['footer_text', 'footer_facebook', 'footer_twitter', 'footer_instagram', 'footer_linkedin'];
        foreach ($footerFields as $field) {
            if (isset($_POST[$field])) {
                $val = trim($_POST[$field]);
                $stmt->execute([$field, $val, $val]);
            }
        }

        // ── Footer Logo Upload ──
        if (!empty($_FILES['footer_logo']['name'])) {
            $targetDir = 'public/uploads/logos/';
            if (!is_dir($targetDir)) mkdir($targetDir, 0777, true);
            $fileName = time() . '_footer_' . preg_replace('/[^a-zA-Z0-9.\-_]/', '', basename($_FILES['footer_logo']['name']));
            $targetPath = $targetDir . $fileName;
            if (move_uploaded_file($_FILES['footer_logo']['tmp_name'], $targetPath)) {
                $stmt->execute(['footer_logo', $fileName, $fileName]);
            }
        }
        
        header('Location: /restpo/superadmin/settings?msg=' . urlencode('Landing page settings updated successfully')); exit;
    }

    // ── Pending Registrations Management ─────────────────────────
    public function registrations() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Pending Registrations';

        $restaurants = $db->query("
            SELECT r.* FROM restaurants r
            WHERE r.approval_status IN ('pending','callback')
            ORDER BY r.created_at DESC
        ")->fetchAll();

        // Fetch admin user for each restaurant
        $adminStmt = $db->prepare('SELECT * FROM users WHERE restaurant_id = ? AND role = "admin" LIMIT 1');
        foreach ($restaurants as &$r) {
            $adminStmt->execute([$r['id']]);
            $r['admin_user'] = $adminStmt->fetch() ?: null;
        }
        unset($r);

        ob_start();
        require 'app/Views/superadmin/registrations/index.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function approveRegistration() {
        $this->requireSuperAdmin();
        $db = getDB();

        $restaurant_id = $_POST['restaurant_id'] ?? null;
        if (!$restaurant_id) {
            header('Location: /restpo/superadmin/registrations?error=Invalid+restaurant+ID'); exit;
        }

        // Activate restaurant
        $db->prepare('UPDATE restaurants SET status = "active", approval_status = "approved" WHERE id = ?')
           ->execute([$restaurant_id]);

        // Activate admin user
        $db->prepare('UPDATE users SET status = "active" WHERE restaurant_id = ? AND role = "admin"')
           ->execute([$restaurant_id]);

        // Get restaurant and admin info
        $rest = $db->prepare('SELECT * FROM restaurants WHERE id = ?');
        $rest->execute([$restaurant_id]);
        $restaurant = $rest->fetch();

        $adminStmt = $db->prepare('SELECT * FROM users WHERE restaurant_id = ? AND role = "admin" LIMIT 1');
        $adminStmt->execute([$restaurant_id]);
        $admin = $adminStmt->fetch();

        if ($admin) {
            // Try sending welcome email
            try {
                MailHelper::sendWelcomeEmail(
                    $admin['email'],
                    $admin['name'],
                    $restaurant['name']
                );
            } catch (\Exception $e) {
                // Do not block approval
            }
        }

        header('Location: /restpo/superadmin/registrations?msg=Registration+approved+successfully'); exit;
    }

    public function callbackRegistration() {
        $this->requireSuperAdmin();
        $db = getDB();

        $restaurant_id = $_POST['restaurant_id'] ?? null;
        $admin_notes = trim($_POST['admin_notes'] ?? '');

        if (!$restaurant_id) {
            header('Location: /restpo/superadmin/registrations?error=Invalid+restaurant+ID'); exit;
        }

        $db->prepare('UPDATE restaurants SET approval_status = "callback", admin_notes = ? WHERE id = ?')
           ->execute([$admin_notes, $restaurant_id]);

        header('Location: /restpo/superadmin/registrations?msg=Registration+marked+for+callback'); exit;
    }

    public function deleteRegistration() {
        $this->requireSuperAdmin();
        $db = getDB();

        $restaurant_id = $_POST['restaurant_id'] ?? null;
        if (!$restaurant_id) {
            header('Location: /restpo/superadmin/registrations?error=Invalid+restaurant+ID'); exit;
        }

        $db->prepare('DELETE FROM restaurants WHERE id = ?')->execute([$restaurant_id]);

        header('Location: /restpo/superadmin/registrations?msg=Registration+deleted+successfully'); exit;
    }

    // ── Contact Messages Management ─────────────────────────────
    public function contacts() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Contact Messages';

        $messages = $db->query('SELECT * FROM contact_messages ORDER BY created_at DESC')->fetchAll();

        // Mark all unread as read
        $db->exec('UPDATE contact_messages SET is_read = 1 WHERE is_read = 0');

        ob_start();
        require 'app/Views/superadmin/contacts/index.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function deleteContact() {
        $this->requireSuperAdmin();
        $db = getDB();

        $id = $_POST['id'] ?? null;
        if ($id) {
            $db->prepare('DELETE FROM contact_messages WHERE id = ?')->execute([$id]);
        }

        header('Location: /restpo/superadmin/contacts?msg=Message+deleted+successfully'); exit;
    }

    // ── Video Reviews Management ─────────────────────────────────
    public function reviews() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Video Reviews';

        $reviews = $db->query('SELECT * FROM video_reviews ORDER BY created_at DESC')->fetchAll();

        ob_start();
        require 'app/Views/superadmin/reviews/index.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

    public function storeReview() {
        $this->requireSuperAdmin();
        $db = getDB();

        $restaurant_name = trim($_POST['restaurant_name'] ?? '');
        $location = trim($_POST['location'] ?? '');
        $youtube_url = trim($_POST['youtube_url'] ?? '');
        $logo = null;

        if (!$restaurant_name || !$youtube_url) {
            header('Location: /restpo/superadmin/reviews?error=Restaurant+name+and+YouTube+URL+are+required'); exit;
        }

        // Auto-convert standard YouTube URLs to embed links
        if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i', $youtube_url, $match)) {
            $youtube_url = 'https://www.youtube.com/embed/' . $match[1];
        }

        // Handle logo upload
        if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            if (in_array($ext, $allowed)) {
                $filename = 'review_' . uniqid() . '.' . $ext;
                $destination = 'public/uploads/logos/' . $filename;
                if (!is_dir('public/uploads/logos')) {
                    mkdir('public/uploads/logos', 0755, true);
                }
                move_uploaded_file($_FILES['logo']['tmp_name'], $destination);
                $logo = $filename;
            }
        }

        $db->prepare('INSERT INTO video_reviews (restaurant_name, location, logo, youtube_url) VALUES (?, ?, ?, ?)')
           ->execute([$restaurant_name, $location, $logo, $youtube_url]);

        header('Location: /restpo/superadmin/reviews?msg=Video+review+added+successfully'); exit;
    }

    public function updateReview() {
        $this->requireSuperAdmin();
        $db = getDB();

        $id = $_POST['id'] ?? null;
        $restaurant_name = trim($_POST['restaurant_name'] ?? '');
        $location = trim($_POST['location'] ?? '');
        $youtube_url = trim($_POST['youtube_url'] ?? '');
        
        if (!$id || !$restaurant_name || !$youtube_url) {
            header('Location: /restpo/superadmin/reviews?error=Missing+required+fields'); exit;
        }

        // Auto-convert standard YouTube URLs to embed links
        if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i', $youtube_url, $match)) {
            $youtube_url = 'https://www.youtube.com/embed/' . $match[1];
        }

        $review = $db->prepare('SELECT * FROM video_reviews WHERE id = ?');
        $review->execute([$id]);
        $review = $review->fetch();

        if (!$review) {
            header('Location: /restpo/superadmin/reviews?error=Review+not+found'); exit;
        }

        $logo = $review['logo'];

        // Handle logo upload
        if (!empty($_FILES['logo']['name']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            if (in_array($ext, $allowed)) {
                $filename = 'review_' . uniqid() . '.' . $ext;
                $destination = 'public/uploads/logos/' . $filename;
                if (!is_dir('public/uploads/logos')) {
                    mkdir('public/uploads/logos', 0755, true);
                }
                move_uploaded_file($_FILES['logo']['tmp_name'], $destination);
                
                // Optionally delete old logo here if it exists
                if ($logo && file_exists('public/uploads/logos/' . $logo)) {
                    unlink('public/uploads/logos/' . $logo);
                }
                
                $logo = $filename;
            }
        }

        $db->prepare('UPDATE video_reviews SET restaurant_name = ?, location = ?, logo = ?, youtube_url = ? WHERE id = ?')
           ->execute([$restaurant_name, $location, $logo, $youtube_url, $id]);

        header('Location: /restpo/superadmin/reviews?msg=Video+review+updated+successfully'); exit;
    }

    public function deleteReview() {
        $this->requireSuperAdmin();
        $db = getDB();

        $id = $_POST['id'] ?? null;
        if ($id) {
            $db->prepare('DELETE FROM video_reviews WHERE id = ?')->execute([$id]);
        }

        header('Location: /restpo/superadmin/reviews?msg=Review+deleted+successfully'); exit;
    }
}
