<?php
// app/Controllers/FloorController.php

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

    public function index() {
        $this->requireAdmin();
        $db      = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pageTitle = 'Floors & Tables';

        // Load active cashiers
        $cashStmt = $db->prepare('SELECT id, name FROM users WHERE restaurant_id = ? AND role = "cashier" AND status = "active" ORDER BY name ASC');
        $cashStmt->execute([$rest_id]);
        $cashiers = $cashStmt->fetchAll();

        $floorStmt = $db->prepare('
            SELECT f.*, u.name as cashier_name 
            FROM floors f 
            LEFT JOIN users u ON f.cashier_id = u.id 
            WHERE f.restaurant_id = ? 
            ORDER BY f.id ASC
        ');
        $floorStmt->execute([$rest_id]);
        $floors = $floorStmt->fetchAll();

        // Filter floors by subscription limits
        $allowedFloorIds = FeatureGate::getAllowedFloorIds($rest_id);
        $floors = array_filter($floors, fn($f) => in_array($f['id'], $allowedFloorIds));

        // Tables grouped by floor
        $tableStmt = $db->prepare('
            SELECT t.*, f.name as floor_name
            FROM tables t
            JOIN floors f ON f.id = t.floor_id
            WHERE t.restaurant_id = ?
            ORDER BY f.id ASC, t.name ASC
        ');
        $tableStmt->execute([$rest_id]);
        $allTables = $tableStmt->fetchAll();

        // Filter tables by subscription limits
        $allowedTableIds = FeatureGate::getAllowedTableIds($rest_id);
        $allTables = array_filter($allTables, fn($t) => in_array($t['id'], $allowedTableIds));

        // Group by floor_id
        $tablesByFloor = [];
        foreach ($allTables as $t) {
            $tablesByFloor[$t['floor_id']][] = $t;
        }

        // Stats
        $totalTables    = count($allTables);
        $occupiedTables = count(array_filter($allTables, fn($t) => $t['status'] === 'occupied'));
        $availTables    = $totalTables - $occupiedTables;

        $floorCheck = FeatureGate::canAddFloor($rest_id);
        $tableCheck = FeatureGate::canAddTable($rest_id, 1);

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

    <?php if (!empty($_GET['error'])): ?>
    <div class="rounded-xl px-4 py-3 text-sm font-medium text-red-300 flex items-center gap-2" style="background:rgba(239,68,68,0.12); border:1px solid rgba(239,68,68,0.25)">
        <i class="fas fa-exclamation-circle"></i>
        <?php echo htmlspecialchars($_GET['error']); ?>
    </div>
    <?php endif; ?>

    <!-- Top stats -->
    <div class="grid grid-cols-3 md:grid-cols-5 gap-4">
        <?php
        $sc = [
            ['label'=>'Total Tables',    'val'=>$totalTables,    'color'=>'#a78bfa','bg'=>'rgba(139,92,246,0.12)','icon'=>'fa-chair'],
            ['label'=>'Available',       'val'=>$availTables,    'color'=>'#6ee7b7','bg'=>'rgba(16,185,129,0.12)','icon'=>'fa-check-circle'],
            ['label'=>'Occupied',        'val'=>$occupiedTables, 'color'=>'#fca5a5','bg'=>'rgba(239,68,68,0.12)', 'icon'=>'fa-user-clock'],
        ];
        foreach($sc as $s): ?>
        <div class="rounded-2xl p-4 flex items-center gap-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
            <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style="background:<?php echo $s['bg']; ?>">
                <i class="fas <?php echo $s['icon']; ?>" style="color:<?php echo $s['color']; ?>"></i>
            </div>
            <div>
                <div class="text-2xl font-bold text-white"><?php echo $s['val']; ?></div>
                <div class="text-xs text-slate-500"><?php echo $s['label']; ?></div>
            </div>
        </div>
        <?php endforeach; ?>
        <!-- Floor Quota Badge -->
        <div class="rounded-2xl p-4 flex items-center gap-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
            <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style="background:rgba(16,185,129,0.12)">
                <i class="fas fa-layer-group" style="color:#6ee7b7"></i>
            </div>
            <div>
                <div class="text-2xl font-bold text-white"><?php echo $floorCheck['current']; ?><span class="text-sm text-slate-500">/<?php echo $floorCheck['max'] ?? '∞'; ?></span></div>
                <div class="text-xs text-slate-500">Floors</div>
            </div>
        </div>
        <!-- Table Quota Badge -->
        <div class="rounded-2xl p-4 flex items-center gap-4" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
            <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0" style="background:rgba(59,130,246,0.12)">
                <i class="fas fa-chair" style="color:#93c5fd"></i>
            </div>
            <div>
                <div class="text-2xl font-bold text-white"><?php echo $tableCheck['current']; ?><span class="text-sm text-slate-500">/<?php echo $tableCheck['max'] ?? '∞'; ?></span></div>
                <div class="text-xs text-slate-500">Table Limit</div>
            </div>
        </div>
    </div>

    <!-- Forms Row -->
    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">

        <!-- Add Floor -->
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
            <h3 class="text-sm font-semibold text-white mb-3 flex items-center gap-2">
                <i class="fas fa-layer-group text-emerald-400"></i> Add Floor
            </h3>
            <form action="/restpo/admin/floors/store" method="POST" class="space-y-3">
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5">Floor Name</label>
                    <input type="text" name="name" required placeholder="e.g. Ground Floor, Rooftop…"
                           class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500"
                           style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5">Cashier (Branch)</label>
                    <select name="cashier_id" class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500" style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.1)">
                        <option value="">General Pool / Unassigned</option>
                        <?php foreach($cashiers as $c): ?>
                        <option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="w-full py-2.5 rounded-xl text-white font-semibold text-sm whitespace-nowrap"
                        style="background:linear-gradient(135deg,#10b981,#059669)">Add Floor</button>
            </form>

            <?php if(!empty($floors)): ?>
            <div class="mt-4 space-y-2">
                <?php foreach($floors as $f):
                    $floorCount = count($tablesByFloor[$f['id']] ?? []);
                ?>
                <div class="flex justify-between items-center px-4 py-2.5 rounded-xl"
                     style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.07)">
                    <div class="flex items-center gap-2">
                        <i class="fas fa-layer-group text-xs text-emerald-400"></i>
                        <div class="flex flex-col">
                            <span class="text-white font-medium text-sm"><?php echo htmlspecialchars($f['name']); ?></span>
                            <span class="text-[10px] text-slate-500 font-medium">
                                <i class="fas fa-store text-[9px] text-blue-400 mr-0.5"></i>
                                <?php echo !empty($f['cashier_name']) ? 'Branch: ' . htmlspecialchars($f['cashier_name']) : 'General Pool'; ?>
                            </span>
                        </div>
                    </div>
                    <div class="flex items-center gap-3">
                        <span class="text-xs text-slate-500"><?php echo $floorCount; ?> table<?php echo $floorCount!=1?'s':''; ?></span>
                        <form action="/restpo/admin/floors/delete" method="POST" onsubmit="return confirm('Delete this floor and all its tables?')">
                            <input type="hidden" name="floor_id" value="<?php echo $f['id']; ?>">
                            <button type="submit" class="text-red-400 hover:text-red-300 text-xs transition">
                                <i class="fas fa-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Bulk Add Tables -->
        <div class="rounded-2xl p-5" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
            <h3 class="text-sm font-semibold text-white mb-1 flex items-center gap-2">
                <i class="fas fa-chair text-blue-400"></i> Add Tables
            </h3>
            <p class="text-xs text-slate-500 mb-3">
                Set a count to bulk-create numbered tables (e.g. "T" × 10 → T-01, T-02 … T-10).<br>
                Or set count to 1 to add a single custom-named table.
            </p>
            <form action="/restpo/admin/tables/store" method="POST" class="space-y-3">
                <div>
                    <label class="block text-xs text-slate-400 mb-1.5">Floor</label>
                    <select name="floor_id" required
                            class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-blue-500"
                            style="background:rgba(13,33,55,1); border:1px solid rgba(255,255,255,0.1)">
                        <option value="">Select floor…</option>
                        <?php foreach($floors as $f): ?>
                        <option value="<?php echo $f['id']; ?>"><?php echo htmlspecialchars($f['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5">
                            Table Name / Prefix
                            <span class="text-slate-600 ml-1">(e.g. T or VIP)</span>
                        </label>
                        <input type="text" name="prefix" required placeholder="T"
                               class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-blue-500"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                    </div>
                    <div>
                        <label class="block text-xs text-slate-400 mb-1.5">
                            Table Count
                            <span class="text-slate-600 ml-1">(1 = single table)</span>
                        </label>
                        <input type="number" name="count" min="1" max="200" value="1" required
                               class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-blue-500"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                    </div>
                </div>

                <div>
                    <label class="block text-xs text-slate-400 mb-1.5">
                        Seats per Table
                        <span class="text-slate-600 ml-1">(seating capacity)</span>
                    </label>
                    <div class="flex gap-2">
                        <?php foreach([2,4,6,8,10] as $n): ?>
                        <label class="flex-1 text-center py-2 rounded-lg text-xs font-semibold cursor-pointer transition"
                               style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.1); color:#94a3b8"
                               x-bind:style="">
                            <input type="radio" name="seats" value="<?php echo $n; ?>" class="hidden" <?php echo $n==4?'checked':''; ?>>
                            <span><?php echo $n; ?></span>
                        </label>
                        <?php endforeach; ?>
                        <input type="number" name="seats_custom" min="1" placeholder="Other"
                               class="w-20 px-3 py-2 rounded-lg text-white text-xs outline-none"
                               style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
                    </div>
                </div>

                <!-- Live preview -->
                <div id="preview" class="px-4 py-3 rounded-xl text-xs text-slate-400 hidden"
                     style="background:rgba(59,130,246,0.08); border:1px solid rgba(59,130,246,0.2)">
                    Preview: <span id="previewText" class="text-blue-300 font-medium"></span>
                </div>

                <button type="submit" class="w-full py-2.5 rounded-xl text-white font-semibold text-sm transition"
                        style="background:linear-gradient(135deg,#3b82f6,#1d4ed8)">
                    <i class="fas fa-plus mr-2"></i>Create Tables
                </button>
            </form>
        </div>
    </div>

    <!-- Tables by Floor -->
    <?php if(!empty($floors)): ?>
    <div class="space-y-4">
        <?php foreach($floors as $floor):
            $floorTables = $tablesByFloor[$floor['id']] ?? [];
            if(empty($floorTables)) continue;
        ?>
        <div class="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-3 border-b border-white/5 flex justify-between items-center">
                <div class="flex items-center gap-2">
                    <i class="fas fa-layer-group text-emerald-400 text-sm"></i>
                    <h4 class="font-semibold text-white"><?php echo htmlspecialchars($floor['name']); ?></h4>
                    <span class="text-xs text-slate-500 ml-1"><?php echo count($floorTables); ?> tables</span>
                </div>
                <div class="flex items-center gap-3 text-xs text-slate-500">
                    <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-emerald-500 inline-block"></span>Available</span>
                    <span class="flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-red-500 inline-block"></span>Occupied</span>
                </div>
            </div>
            <div class="p-5">
                <div class="grid grid-cols-4 sm:grid-cols-6 md:grid-cols-8 lg:grid-cols-10 xl:grid-cols-12 gap-2.5">
                    <?php foreach($floorTables as $t):
                        $occupied = $t['status'] === 'occupied';
                        $bg     = $occupied ? 'rgba(239,68,68,0.15)' : 'rgba(16,185,129,0.1)';
                        $border = $occupied ? 'rgba(239,68,68,0.35)'  : 'rgba(16,185,129,0.25)';
                        $tc     = $occupied ? '#fca5a5'               : '#6ee7b7';
                    ?>
                    <div class="rounded-xl p-2.5 text-center relative group cursor-default"
                         style="background:<?php echo $bg; ?>; border:1px solid <?php echo $border; ?>">
                        <div class="text-xs font-bold text-white leading-tight"><?php echo htmlspecialchars($t['name']); ?></div>
                        <div class="text-xs mt-0.5" style="color:<?php echo $tc; ?>"><?php echo $t['capacity'] ?? '—'; ?> <i class="fas fa-user text-xs opacity-60"></i></div>
                        <!-- Delete button on hover -->
                        <form action="/restpo/admin/tables/delete" method="POST"
                              class="absolute -top-1.5 -right-1.5 hidden group-hover:block"
                              onsubmit="return confirm('Delete <?php echo htmlspecialchars($t['name']); ?>?')">
                            <input type="hidden" name="table_id" value="<?php echo $t['id']; ?>">
                            <button type="submit" class="w-5 h-5 rounded-full flex items-center justify-center text-xs"
                                    style="background:#ef4444; color:white">
                                <i class="fas fa-times" style="font-size:8px"></i>
                            </button>
                        </form>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php elseif(empty($floors)): ?>
    <div class="rounded-2xl p-10 text-center" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
        <i class="fas fa-layer-group text-4xl text-slate-700 mb-3"></i>
        <p class="text-slate-500">No floors yet. Add a floor first, then create tables.</p>
    </div>
    <?php endif; ?>
</div>

<!-- Seat radio highlight + live preview -->
<script>
document.addEventListener('DOMContentLoaded', () => {
    const form = document.querySelector('form[action="/restpo/admin/tables/store"]');
    if (!form) return;

    // Highlight radio buttons
    function syncRadios() {
        document.querySelectorAll('[name="seats"]').forEach(r => {
            const lbl = r.parentElement;
            if (r.checked) {
                lbl.style.background = 'rgba(59,130,246,0.25)';
                lbl.style.borderColor = 'rgba(59,130,246,0.5)';
                lbl.style.color = '#93c5fd';
            } else {
                lbl.style.background = 'rgba(255,255,255,0.05)';
                lbl.style.borderColor = 'rgba(255,255,255,0.1)';
                lbl.style.color = '#94a3b8';
            }
        });
    }
    document.querySelectorAll('[name="seats"]').forEach(r => {
        r.addEventListener('change', syncRadios);
    });
    syncRadios();

    // Live preview
    const prefixInput = form.querySelector('[name="prefix"]');
    const countInput  = form.querySelector('[name="count"]');
    const preview     = document.getElementById('preview');
    const previewText = document.getElementById('previewText');

    function updatePreview() {
        const prefix = prefixInput.value.trim() || 'T';
        const count  = parseInt(countInput.value) || 1;
        if (count === 1) {
            previewText.textContent = prefix;
            preview.classList.remove('hidden');
        } else {
            const pad = n => String(n).padStart(2, '0');
            const examples = [];
            for (let i = 1; i <= Math.min(count, 5); i++) examples.push(`${prefix}-${pad(i)}`);
            if (count > 5) examples.push(`… ${prefix}-${pad(count)}`);
            previewText.textContent = `${count} tables: ${examples.join(', ')}`;
            preview.classList.remove('hidden');
        }
    }

    prefixInput.addEventListener('input', updatePreview);
    countInput.addEventListener('input', updatePreview);
    updatePreview();
});
</script>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    // ── Store Floor ─────────────────────────────────────────────
    public function store() {
        $this->requireAdmin();

        $cashier_id = !empty($_POST['cashier_id']) ? intval($_POST['cashier_id']) : null;

        $floorCheck = FeatureGate::canAddFloor($_SESSION['restaurant_id'], $cashier_id);
        if (!$floorCheck['allowed']) {
            $msg = 'Floor limit reached';
            if ($floorCheck['max'] !== null) {
                $msg .= ' (' . $floorCheck['max'] . ' max per branch)';
            }
            $msg .= '. Upgrade your package.';
            header('Location: /restpo/admin/floors?error=' . urlencode($msg)); exit;
        }

        $db = getDB();
        $db->prepare('INSERT INTO floors (restaurant_id, cashier_id, name) VALUES (?, ?, ?)')
           ->execute([$_SESSION['restaurant_id'], $cashier_id, trim($_POST['name'])]);
        header('Location: /restpo/admin/floors?msg=Floor+added'); exit;
    }

    // ── Delete Floor ─────────────────────────────────────────────
    public function deleteFloor() {
        $this->requireAdmin();
        $db = getDB();
        // Remove all tables on this floor first
        $db->prepare('DELETE FROM tables WHERE floor_id = ? AND restaurant_id = ?')
           ->execute([$_POST['floor_id'], $_SESSION['restaurant_id']]);
        $db->prepare('DELETE FROM floors WHERE id = ? AND restaurant_id = ?')
           ->execute([$_POST['floor_id'], $_SESSION['restaurant_id']]);
        header('Location: /restpo/admin/floors?msg=Floor+deleted'); exit;
    }

    // ── Bulk-create Tables ───────────────────────────────────────
    public function storeTable() {
        $this->requireAdmin();
        $db      = getDB();
        $rest_id = $_SESSION['restaurant_id'];

        $floor_id = intval($_POST['floor_id'] ?? 0);
        $prefix   = trim($_POST['prefix'] ?? 'T');
        $count    = max(1, min(200, intval($_POST['count'] ?? 1)));

        // Seats: prefer radio, fallback to custom field
        $seats = intval($_POST['seats'] ?? 0);
        if (!$seats) $seats = intval($_POST['seats_custom'] ?? 4);
        if ($seats < 1) $seats = 4;

        // Verify floor belongs to this restaurant and get cashier_id
        $chk = $db->prepare('SELECT id, cashier_id FROM floors WHERE id = ? AND restaurant_id = ?');
        $chk->execute([$floor_id, $rest_id]);
        $floorData = $chk->fetch();
        if (!$floorData) {
            header('Location: /restpo/admin/floors?error=Invalid+floor'); exit;
        }
        $cashier_id = $floorData['cashier_id'];

        $tableCheck = FeatureGate::canAddTable($rest_id, $count, $cashier_id);
        if (!$tableCheck['allowed']) {
            $msg = 'Table limit reached. Can only add ' . $tableCheck['remaining'] . ' more tables';
            if ($tableCheck['max'] !== null) {
                $msg .= ' (' . $tableCheck['max'] . ' max per branch)';
            }
            $msg .= '. Upgrade your package.';
            header('Location: /restpo/admin/floors?error=' . urlencode($msg)); exit;
        }

        $stmt = $db->prepare('INSERT INTO tables (restaurant_id, floor_id, name, capacity) VALUES (?, ?, ?, ?)');

        if ($count === 1) {
            // Single table – use the prefix as the exact name
            $stmt->execute([$rest_id, $floor_id, $prefix, $seats]);
        } else {
            // Bulk-create: prefix-01, prefix-02, …
            $pad = strlen((string)$count); // dynamic zero-padding width
            for ($i = 1; $i <= $count; $i++) {
                $name = $prefix . '-' . str_pad($i, max(2, $pad), '0', STR_PAD_LEFT);
                $stmt->execute([$rest_id, $floor_id, $name, $seats]);
            }
        }

        $msg = $count === 1 ? urlencode("Table '{$prefix}' added") : urlencode("{$count} tables created successfully");
        header("Location: /restpo/admin/floors?msg={$msg}"); exit;
    }

    // ── Delete Single Table ──────────────────────────────────────
    public function deleteTable() {
        $this->requireAdmin();
        $db = getDB();
        $db->prepare('DELETE FROM tables WHERE id = ? AND restaurant_id = ?')
           ->execute([$_POST['table_id'], $_SESSION['restaurant_id']]);
        header('Location: /restpo/admin/floors?msg=Table+deleted'); exit;
    }
}
