<?php
// app/Controllers/CouponController.php

class CouponController {

    private function requireSuperAdmin() {
        if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'superadmin') {
            header('Location: ' . BASE_URL . '/lsign'); exit;
        }
    }

    public function index() {
        $this->requireSuperAdmin();
        $db = getDB();
        $pageTitle = 'Coupons';

        $coupons = $db->query('SELECT * FROM coupons ORDER BY id DESC')->fetchAll();

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

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Create Coupon 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-ticket-alt text-purple-400 mr-2"></i>Create Coupon</h3>
            <?php if(isset($_GET['error'])): ?>
            <div class="mb-3 p-3 rounded-lg text-xs" style="background:rgba(239,68,68,0.15); color:#f87171; border:1px solid rgba(239,68,68,0.3)">
                <i class="fas fa-exclamation-circle mr-1"></i> <?php echo htmlspecialchars($_GET['error']); ?>
            </div>
            <?php endif; ?>
            <form action="<?= BASE_URL ?>/superadmin/coupons/store" method="POST" class="space-y-3">
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Coupon Code</label>
                    <div class="flex gap-2">
                        <input type="text" name="code" id="couponCode" required maxlength="30"
                               class="form-input flex-1 uppercase" placeholder="e.g. SAVE20"
                               style="text-transform:uppercase">
                        <button type="button" onclick="document.getElementById('couponCode').value=randomCode()"
                                class="px-3 py-2 rounded-lg text-xs font-medium text-slate-300 hover:text-white transition" style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                            <i class="fas fa-dice"></i>
                        </button>
                    </div>
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Discount Type</label>
                    <select name="type" class="form-input" style="background:#150d2e">
                        <option value="percentage">Percentage (%)</option>
                        <option value="fixed">Fixed Amount (<?php echo $_SESSION['currency'] ?? '$'; ?>)</option>
                    </select>
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Value</label>
                    <input type="number" step="0.01" name="value" required min="0.01" class="form-input" placeholder="e.g. 10">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Expiry Date</label>
                    <input type="date" name="expiry_date" required class="form-input" min="<?php echo date('Y-m-d'); ?>"
                           value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Usage Limit <span class="text-slate-600">(blank = unlimited)</span></label>
                    <input type="number" name="usage_limit" min="1" class="form-input" placeholder="e.g. 100">
                </div>
                <button type="submit" class="btn-primary w-full mt-1">
                    <i class="fas fa-plus mr-2"></i>Create Coupon
                </button>
            </form>
        </div>

        <!-- Coupon List -->
        <div class="lg:col-span-2 space-y-3">
            <!-- Summary Cards -->
            <div class="grid grid-cols-3 gap-3 mb-2">
                <?php
                $total   = count($coupons);
                $active  = count(array_filter($coupons, fn($c) => $c['status']==='active' && $c['expiry_date'] >= date('Y-m-d')));
                $expired = count(array_filter($coupons, fn($c) => $c['expiry_date'] < date('Y-m-d')));
                $totalUsed = array_sum(array_column($coupons, 'used_count'));
                $cards = [
                    ['label'=>'Active','val'=>$active,'color'=>'#6ee7b7','bg'=>'rgba(16,185,129,0.12)'],
                    ['label'=>'Expired','val'=>$expired,'color'=>'#f87171','bg'=>'rgba(239,68,68,0.12)'],
                    ['label'=>'Total Used','val'=>$totalUsed,'color'=>'#c4b5fd','bg'=>'rgba(139,92,246,0.12)'],
                ];
                foreach($cards as $c): ?>
                <div class="rounded-xl p-3 text-center" style="background:<?php echo $c['bg']; ?>; border:1px solid <?php echo $c['bg']; ?>">
                    <div class="text-2xl font-bold" style="color:<?php echo $c['color']; ?>"><?php echo $c['val']; ?></div>
                    <div class="text-xs text-slate-400 mt-0.5"><?php echo $c['label']; ?></div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- Table -->
            <div class="rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
                <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">Code</th>
                        <th class="text-left px-5 py-3 text-slate-500 font-medium">Discount</th>
                        <th class="text-left px-5 py-3 text-slate-500 font-medium">Usage</th>
                        <th class="text-left px-5 py-3 text-slate-500 font-medium">Expires</th>
                        <th class="text-left px-5 py-3 text-slate-500 font-medium">Status</th>
                        <th class="text-right px-5 py-3 text-slate-500 font-medium">Actions</th>
                    </tr></thead>
                    <tbody>
                        <?php if(empty($coupons)): ?>
                        <tr><td colspan="6" class="px-5 py-10 text-center text-slate-500">No coupons yet. Create your first one.</td></tr>
                        <?php endif; ?>
                        <?php foreach($coupons as $coupon):
                            $isExpired = $coupon['expiry_date'] < date('Y-m-d');
                            $statusActive = $coupon['status'] === 'active' && !$isExpired;
                            $limitReached = $coupon['usage_limit'] && $coupon['used_count'] >= $coupon['usage_limit'];
                        ?>
                        <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">
                                    <code class="font-mono font-bold text-purple-300 tracking-wider bg-purple-500/10 px-2 py-0.5 rounded text-xs"><?php echo htmlspecialchars($coupon['code']); ?></code>
                                </div>
                            </td>
                            <td class="px-5 py-3 font-semibold text-white">
                                <?php if($coupon['type'] === 'percentage'): ?>
                                    <span class="text-yellow-400"><?php echo $coupon['value']; ?>% OFF</span>
                                <?php else: ?>
                                    <span class="text-green-400"><?php echo $_SESSION['currency'] ?? '$'; ?><?php echo number_format($coupon['value'],2); ?> OFF</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-5 py-3">
                                <div class="text-slate-300 text-xs">
                                    <?php echo $coupon['used_count']; ?> used
                                    <?php if($coupon['usage_limit']): ?>
                                    / <?php echo $coupon['usage_limit']; ?>
                                    <div class="w-full bg-white/10 rounded-full h-1 mt-1">
                                        <div class="h-1 rounded-full" style="width:<?php echo min(100, round($coupon['used_count']/$coupon['usage_limit']*100)); ?>%; background:<?php echo $limitReached?'#ef4444':'#8b5cf6'; ?>"></div>
                                    </div>
                                    <?php else: ?>
                                    / ∞
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="px-5 py-3 text-xs <?php echo $isExpired?'text-red-400':'text-slate-400'; ?>">
                                <?php echo date('M d, Y', strtotime($coupon['expiry_date'])); ?>
                                <?php if($isExpired): ?><br><span class="text-red-500">Expired</span><?php endif; ?>
                            </td>
                            <td class="px-5 py-3">
                                <?php
                                if($isExpired) { $sc='rgba(239,68,68,0.15)'; $tc='#f87171'; $label='Expired'; }
                                elseif($limitReached) { $sc='rgba(245,158,11,0.15)'; $tc='#fcd34d'; $label='Limit Hit'; }
                                elseif($coupon['status']==='inactive') { $sc='rgba(100,116,139,0.2)'; $tc='#94a3b8'; $label='Inactive'; }
                                else { $sc='rgba(16,185,129,0.15)'; $tc='#6ee7b7'; $label='Active'; }
                                ?>
                                <span class="px-2 py-1 rounded-full text-xs font-semibold" style="background:<?php echo $sc; ?>; color:<?php echo $tc; ?>"><?php echo $label; ?></span>
                            </td>
                            <td class="px-5 py-3 text-right">
                                <form action="<?= BASE_URL ?>/superadmin/coupons/toggle" method="POST" class="inline">
                                    <input type="hidden" name="id" value="<?php echo $coupon['id']; ?>">
                                    <input type="hidden" name="status" value="<?php echo $coupon['status']==='active'?'inactive':'active'; ?>">
                                    <button type="submit" class="text-xs px-2.5 py-1 rounded-lg mr-1 transition" style="background:rgba(255,255,255,0.06); color:#94a3b8; border:1px solid rgba(255,255,255,0.08)">
                                        <?php echo $coupon['status']==='active' ? 'Disable' : 'Enable'; ?>
                                    </button>
                                </form>
                                <form action="<?= BASE_URL ?>/superadmin/coupons/delete" method="POST" class="inline" onsubmit="return confirm('Delete this coupon?')">
                                    <input type="hidden" name="id" value="<?php echo $coupon['id']; ?>">
                                    <button type="submit" class="text-xs px-2.5 py-1 rounded-lg transition" style="background:rgba(239,68,68,0.1); color:#f87171; border:1px solid rgba(239,68,68,0.2)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
function randomCode() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let result = '';
    for(let i=0; i<8; i++) result += chars[Math.floor(Math.random()*chars.length)];
    return result;
}
</script>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/superadmin.php';
    }

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

        $code = strtoupper(trim($_POST['code'] ?? ''));
        if (!$code) { header('Location: ' . BASE_URL . '/superadmin/coupons?error=Code+required'); exit; }

        // Check uniqueness
        $check = $db->prepare('SELECT id FROM coupons WHERE code = ?');
        $check->execute([$code]);
        if ($check->fetch()) { header('Location: ' . BASE_URL . '/superadmin/coupons?error=Coupon+code+already+exists'); exit; }

        $limit = ($_POST['usage_limit'] ?? '') !== '' ? intval($_POST['usage_limit']) : null;

        $db->prepare('INSERT INTO coupons (code, type, value, expiry_date, usage_limit, status) VALUES (?, ?, ?, ?, ?, "active")')
           ->execute([$code, $_POST['type'], $_POST['value'], $_POST['expiry_date'], $limit]);

        header('Location: ' . BASE_URL . '/superadmin/coupons?msg=Coupon+created+successfully'); exit;
    }

    public function toggle() {
        $this->requireSuperAdmin();
        $db = getDB();
        $db->prepare('UPDATE coupons SET status=? WHERE id=?')
           ->execute([$_POST['status'], $_POST['id']]);
        header('Location: ' . BASE_URL . '/superadmin/coupons?msg=Coupon+updated'); exit;
    }

    public function delete() {
        $this->requireSuperAdmin();
        $db = getDB();
        $db->prepare('DELETE FROM coupons WHERE id=?')->execute([$_POST['id']]);
        header('Location: ' . BASE_URL . '/superadmin/coupons?msg=Coupon+deleted'); exit;
    }

    // ── Restaurant Admin Coupon Actions ────────────────
    private function requireAdmin() {
        if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role'], ['admin', 'superadmin'])) {
            header('Location: ' . BASE_URL . '/lsign'); exit;
        }
    }

    public function adminIndex() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pageTitle = 'Restaurant Coupons';

        $floors = $db->prepare('SELECT * FROM floors WHERE restaurant_id = ? ORDER BY name');
        $floors->execute([$rest_id]);
        $floors = $floors->fetchAll();

        $categories = $db->prepare('SELECT * FROM categories WHERE restaurant_id = ? AND status="active" ORDER BY name');
        $categories->execute([$rest_id]);
        $categories = $categories->fetchAll();

        $products = $db->prepare('SELECT * FROM products WHERE restaurant_id = ? AND status="active" ORDER BY name');
        $products->execute([$rest_id]);
        $products = $products->fetchAll();

        $coupons = $db->prepare('
            SELECT rc.*, f.name as floor_name, c.name as category_name, p.name as product_name 
            FROM restaurant_coupons rc 
            LEFT JOIN floors f ON f.id = rc.floor_id 
            LEFT JOIN categories c ON c.id = rc.category_id
            LEFT JOIN products p ON p.id = rc.product_id
            WHERE rc.restaurant_id = ? 
            ORDER BY rc.id DESC
        ');
        $coupons->execute([$rest_id]);
        $coupons = $coupons->fetchAll();

        $currency = FeatureGate::currency($rest_id);

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

    public function adminStore() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];

        $code = strtoupper(trim($_POST['code'] ?? ''));
        if (!$code) {
            header('Location: ' . BASE_URL . '/admin/coupons?error=Code+is+required'); exit;
        }

        // Check uniqueness for this restaurant
        $check = $db->prepare('SELECT COUNT(*) FROM restaurant_coupons WHERE restaurant_id = ? AND code = ?');
        $check->execute([$rest_id, $code]);
        if ($check->fetchColumn() > 0) {
            header('Location: ' . BASE_URL . '/admin/coupons?error=Coupon+code+already+exists+for+your+restaurant'); exit;
        }

        $floor_id = !empty($_POST['floor_id']) ? intval($_POST['floor_id']) : null;
        $category_id = !empty($_POST['category_id']) ? intval($_POST['category_id']) : null;
        $product_id = !empty($_POST['product_id']) ? intval($_POST['product_id']) : null;
        $type = $_POST['type'] ?? 'percentage';
        $value = floatval($_POST['value'] ?? 0);
        $min_order_amount = floatval($_POST['min_order_amount'] ?? 0);
        $expiry_date = $_POST['expiry_date'] ?? date('Y-m-d', strtotime('+30 days'));

        // Get applicable days from checkbox array
        $days = $_POST['applicable_days'] ?? [];
        $applicable_days = !empty($days) ? implode(',', $days) : null;

        $stmt = $db->prepare('INSERT INTO restaurant_coupons (restaurant_id, floor_id, category_id, product_id, code, type, value, min_order_amount, applicable_days, expiry_date, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "active")');
        $stmt->execute([$rest_id, $floor_id, $category_id, $product_id, $code, $type, $value, $min_order_amount, $applicable_days, $expiry_date]);

        header('Location: ' . BASE_URL . '/admin/coupons?msg=Coupon+created+successfully'); exit;
    }

    public function adminToggle() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $db->prepare('UPDATE restaurant_coupons SET status=? WHERE id=? AND restaurant_id=?')
           ->execute([$_POST['status'], $_POST['id'], $rest_id]);
         header('Location: ' . BASE_URL . '/admin/coupons?msg=Coupon+updated'); exit;
    }

    public function adminDelete() {
        $this->requireAdmin();
        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $db->prepare('DELETE FROM restaurant_coupons WHERE id=? AND restaurant_id=?')->execute([$_POST['id'], $rest_id]);
        header('Location: ' . BASE_URL . '/admin/coupons?msg=Coupon+deleted'); exit;
    }
}
