<?php
// app/Controllers/ProductController.php

class ProductController {
    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 = 'Products';
        $currency = FeatureGate::currency($rest_id);

        $products = $db->prepare('
            SELECT p.*, c.name AS category_name
            FROM products p
            JOIN categories c ON c.id = p.category_id
            WHERE p.restaurant_id = ?
            ORDER BY c.name ASC, p.name ASC
        ');
        $products->execute([$rest_id]);
        $products = $products->fetchAll();

        // Group by category for better display
        $grouped = [];
        foreach ($products as $p) {
            $grouped[$p['category_name']][] = $p;
        }

        ob_start(); ?>
<div class="space-y-6">
    <!-- Header -->
    <div class="flex justify-between items-center">
        <p class="text-slate-400 text-sm"><?php echo count($products); ?> products in menu</p>
        <a href="/restpo/admin/products/create"
           class="px-5 py-2.5 rounded-xl text-white font-semibold text-sm transition shadow-lg flex items-center gap-2"
           style="background:linear-gradient(135deg,#10b981,#059669)">
            <i class="fas fa-plus"></i> Add Product
        </a>
    </div>

    <?php if(empty($products)): ?>
    <div class="rounded-2xl p-12 text-center" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
        <i class="fas fa-hamburger text-4xl text-slate-700 mb-3"></i>
        <p class="text-slate-500 mb-4">No products yet.</p>
        <a href="/restpo/admin/products/create" class="px-6 py-2.5 rounded-xl text-white font-semibold text-sm" style="background:linear-gradient(135deg,#10b981,#059669)">Add First Product</a>
    </div>
    <?php endif; ?>

    <?php foreach($grouped as $catName => $items): ?>
    <div class="rounded-2xl overflow-hidden" style="background:rgba(255,255,255,0.04); border:1px solid rgba(255,255,255,0.08)">
        <!-- Category Header -->
        <div class="px-5 py-3 border-b border-white/5 flex justify-between items-center">
            <h3 class="font-semibold text-white flex items-center gap-2">
                <i class="fas fa-tag text-emerald-400 text-sm"></i>
                <?php echo htmlspecialchars($catName); ?>
            </h3>
            <span class="text-xs text-slate-500"><?php echo count($items); ?> items</span>
        </div>

        <!-- Product Grid -->
        <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-0 divide-x divide-y divide-white/5">
            <?php foreach($items as $p): ?>
            <div class="p-4 hover:bg-white/4 transition group relative">
                <!-- Image -->
                <div class="w-full aspect-video rounded-xl overflow-hidden mb-3" style="background:rgba(255,255,255,0.06)">
                    <?php if($p['image']): ?>
                    <img src="/restpo/public/<?php echo htmlspecialchars($p['image']); ?>"
                         alt="<?php echo htmlspecialchars($p['name']); ?>"
                         loading="lazy"
                         class="w-full h-full object-cover"
                         style="image-rendering:auto">
                    <?php else: ?>
                    <div class="w-full h-full flex items-center justify-center">
                        <i class="fas fa-utensils text-slate-600 text-xl"></i>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Info -->
                <div class="text-white font-medium text-sm leading-tight truncate"><?php echo htmlspecialchars($p['name']); ?></div>
                <div class="text-emerald-400 font-bold text-base mt-0.5"><?php echo htmlspecialchars($currency); ?><?php echo number_format($p['price'],2); ?></div>

                <?php if($p['description']): ?>
                <div class="text-slate-500 text-xs mt-1 line-clamp-2 leading-tight"><?php echo htmlspecialchars($p['description']); ?></div>
                <?php endif; ?>

                <!-- Status -->
                <div class="mt-2">
                    <span class="text-xs px-2 py-0.5 rounded-full font-medium"
                          style="background:<?php echo $p['status']==='active'?'rgba(16,185,129,0.15)':'rgba(239,68,68,0.15)'; ?>;
                                 color:<?php echo $p['status']==='active'?'#6ee7b7':'#f87171'; ?>">
                        <?php echo ucfirst($p['status']); ?>
                    </span>
                </div>

                <!-- Hover Actions -->
                <div class="absolute top-3 right-3 hidden group-hover:flex gap-1">
                    <a href="/restpo/admin/products/edit?id=<?php echo $p['id']; ?>"
                       class="w-7 h-7 rounded-lg flex items-center justify-center text-xs transition"
                       style="background:rgba(59,130,246,0.8); color:white">
                        <i class="fas fa-edit"></i>
                    </a>
                    <form action="/restpo/admin/products/delete" method="POST" onsubmit="return confirm('Delete this product?')">
                        <input type="hidden" name="product_id" value="<?php echo $p['id']; ?>">
                        <button type="submit" class="w-7 h-7 rounded-lg flex items-center justify-center text-xs"
                                style="background:rgba(239,68,68,0.8); color:white">
                            <i class="fas fa-trash"></i>
                        </button>
                    </form>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    public function create() {
        $this->requireAdmin();
        $db      = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pageTitle = 'Add Product';
        $error   = null;
        $currency = FeatureGate::currency($rest_id);

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

        ob_start(); ?>
<div class="max-w-2xl">
    <a href="/restpo/admin/products" class="text-slate-400 hover:text-white text-sm flex items-center gap-2 mb-5">
        <i class="fas fa-arrow-left text-xs"></i> Back to Products
    </a>
    <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-6 py-4 border-b border-white/5">
            <h3 class="font-semibold text-white">New Product</h3>
            <p class="text-slate-500 text-xs mt-0.5">Images are auto-compressed to WebP for fast loading.</p>
        </div>
        <form action="/restpo/admin/products/store" method="POST" enctype="multipart/form-data" class="p-6 space-y-5">

            <!-- Image Upload -->
            <div>
                <label class="block text-xs font-medium text-slate-400 mb-2">Product Image <span class="text-slate-600">(optional · max 8MB · auto-optimised to WebP)</span></label>
                <div class="relative">
                    <div id="dropZone"
                         class="border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition hover:border-emerald-500/50"
                         style="border-color:rgba(255,255,255,0.12); background:rgba(255,255,255,0.03)"
                         onclick="document.getElementById('imageInput').click()">
                        <div id="dropPlaceholder">
                            <i class="fas fa-cloud-upload-alt text-3xl text-slate-600 mb-2"></i>
                            <p class="text-slate-500 text-sm">Click to upload or drag & drop</p>
                            <p class="text-slate-600 text-xs mt-1">JPEG · PNG · WebP · GIF</p>
                        </div>
                        <div id="dropPreview" class="hidden">
                            <img id="previewImg" src="" alt="" class="max-h-40 mx-auto rounded-lg object-contain">
                            <p class="text-emerald-400 text-xs mt-2"><i class="fas fa-check mr-1"></i>Image selected — will be compressed on save</p>
                        </div>
                    </div>
                    <input type="file" id="imageInput" name="image" accept="image/*" class="hidden">
                </div>
            </div>

            <!-- Name -->
            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Product Name *</label>
                <input type="text" name="name" required placeholder="e.g. Grilled Chicken Burger"
                       class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500 transition"
                       style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)">
            </div>

            <!-- Category + Price -->
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Category *</label>
                    <select name="category_id" required
                            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="">Select…</option>
                        <?php foreach($categories as $c): ?>
                        <option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Price (<?php echo htmlspecialchars($currency); ?>) *</label>
                    <input type="number" step="0.01" min="0" name="price" required placeholder="0.00"
                           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>

            <!-- Description -->
            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Description <span class="text-slate-600">(optional)</span></label>
                <textarea name="description" rows="2" placeholder="Short description shown in the QR menu…"
                          class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500 resize-none"
                          style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)"></textarea>
            </div>

            <!-- Status -->
            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Status</label>
                <div class="flex gap-3">
                    <label class="flex items-center gap-2 cursor-pointer text-sm text-slate-300">
                        <input type="radio" name="status" value="active" checked class="accent-emerald-500"> Active
                    </label>
                    <label class="flex items-center gap-2 cursor-pointer text-sm text-slate-300">
                        <input type="radio" name="status" value="inactive" class="accent-red-500"> Inactive
                    </label>
                </div>
            </div>

            <div class="flex gap-3 pt-2">
                <button type="submit" class="px-8 py-3 rounded-xl font-semibold text-white transition shadow-lg"
                        style="background:linear-gradient(135deg,#10b981,#059669)">
                    <i class="fas fa-save mr-2"></i>Save Product
                </button>
                <a href="/restpo/admin/products" class="px-5 py-3 rounded-xl text-slate-400 hover:text-white text-sm transition"
                   style="background:rgba(255,255,255,0.05)">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
// Image preview with drag & drop
const input    = document.getElementById('imageInput');
const dropZone = document.getElementById('dropZone');
const placeholder = document.getElementById('dropPlaceholder');
const dropPreview = document.getElementById('dropPreview');
const previewImg  = document.getElementById('previewImg');

function showPreview(file) {
    if (!file || !file.type.startsWith('image/')) return;
    const url = URL.createObjectURL(file);
    previewImg.src = url;
    placeholder.classList.add('hidden');
    dropPreview.classList.remove('hidden');
    dropZone.style.borderColor = 'rgba(16,185,129,0.5)';
}

input.addEventListener('change', () => { if (input.files[0]) showPreview(input.files[0]); });

dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.style.borderColor='rgba(16,185,129,0.6)'; });
dropZone.addEventListener('dragleave', () => { dropZone.style.borderColor='rgba(255,255,255,0.12)'; });
dropZone.addEventListener('drop', e => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (file) {
        const dt = new DataTransfer(); dt.items.add(file); input.files = dt.files;
        showPreview(file);
    }
});
</script>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    public function edit() {
        $this->requireAdmin();
        $db      = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pageTitle = 'Edit Product';
        $currency = FeatureGate::currency($rest_id);

        $product = $db->prepare('SELECT * FROM products WHERE id = ? AND restaurant_id = ?');
        $product->execute([$_GET['id'] ?? 0, $rest_id]);
        $product = $product->fetch();
        if (!$product) { header('Location: /restpo/admin/products'); exit; }

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

        ob_start(); ?>
<div class="max-w-2xl">
    <a href="/restpo/admin/products" class="text-slate-400 hover:text-white text-sm flex items-center gap-2 mb-5">
        <i class="fas fa-arrow-left text-xs"></i> Back to Products
    </a>
    <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-6 py-4 border-b border-white/5">
            <h3 class="font-semibold text-white">Edit: <?php echo htmlspecialchars($product['name']); ?></h3>
        </div>
        <form action="/restpo/admin/products/update" method="POST" enctype="multipart/form-data" class="p-6 space-y-5">
            <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">

            <!-- Current / New Image -->
            <div>
                <label class="block text-xs font-medium text-slate-400 mb-2">Product Image</label>
                <div class="flex gap-4 items-start">
                    <!-- Current image thumbnail -->
                    <div class="w-24 h-20 rounded-xl overflow-hidden flex-shrink-0" style="background:rgba(255,255,255,0.06)">
                        <?php if($product['image']): ?>
                        <img src="/restpo/public/<?php echo htmlspecialchars($product['image']); ?>"
                             alt="" loading="lazy" class="w-full h-full object-cover">
                        <?php else: ?>
                        <div class="w-full h-full flex items-center justify-center">
                            <i class="fas fa-utensils text-slate-600 text-xl"></i>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="flex-1">
                        <div class="border-2 border-dashed rounded-xl p-4 text-center cursor-pointer transition"
                             style="border-color:rgba(255,255,255,0.12); background:rgba(255,255,255,0.03)"
                             onclick="document.getElementById('imageInput').click()">
                            <p class="text-slate-500 text-xs">Click to replace image</p>
                            <p class="text-slate-600 text-xs">(leave blank to keep current)</p>
                        </div>
                        <input type="file" id="imageInput" name="image" accept="image/*" class="hidden">
                        <div id="newPreview" class="mt-2 hidden">
                            <img id="previewImg" src="" alt="" class="max-h-20 rounded-lg object-contain">
                            <p class="text-emerald-400 text-xs mt-1">New image selected</p>
                        </div>
                        <?php if($product['image']): ?>
                        <label class="flex items-center gap-2 text-xs text-red-400 mt-2 cursor-pointer">
                            <input type="checkbox" name="remove_image" value="1" class="accent-red-500">
                            Remove current image
                        </label>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Product Name *</label>
                <input type="text" name="name" value="<?php echo htmlspecialchars($product['name']); ?>" required
                       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 class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Category *</label>
                    <select name="category_id" required
                            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)">
                        <?php foreach($categories as $c): ?>
                        <option value="<?php echo $c['id']; ?>" <?php echo $c['id']==$product['category_id']?'selected':''; ?>><?php echo htmlspecialchars($c['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-medium text-slate-400 mb-1.5">Price (<?php echo htmlspecialchars($currency); ?>) *</label>
                    <input type="number" step="0.01" name="price" value="<?php echo $product['price']; ?>" required
                           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>

            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Description</label>
                <textarea name="description" rows="2"
                          class="w-full px-4 py-2.5 rounded-xl text-white text-sm outline-none focus:ring-2 focus:ring-emerald-500 resize-none"
                          style="background:rgba(255,255,255,0.07); border:1px solid rgba(255,255,255,0.1)"><?php echo htmlspecialchars($product['description'] ?? ''); ?></textarea>
            </div>

            <div>
                <label class="block text-xs font-medium text-slate-400 mb-1.5">Status</label>
                <div class="flex gap-3">
                    <label class="flex items-center gap-2 cursor-pointer text-sm text-slate-300">
                        <input type="radio" name="status" value="active" <?php echo $product['status']==='active'?'checked':''; ?> class="accent-emerald-500"> Active
                    </label>
                    <label class="flex items-center gap-2 cursor-pointer text-sm text-slate-300">
                        <input type="radio" name="status" value="inactive" <?php echo $product['status']==='inactive'?'checked':''; ?> class="accent-red-500"> Inactive
                    </label>
                </div>
            </div>

            <div class="flex gap-3 pt-2">
                <button type="submit" class="px-8 py-3 rounded-xl font-semibold text-white transition shadow-lg"
                        style="background:linear-gradient(135deg,#10b981,#059669)">
                    <i class="fas fa-save mr-2"></i>Update Product
                </button>
            </div>
        </form>
    </div>
</div>
<script>
const input = document.getElementById('imageInput');
input.addEventListener('change', () => {
    if (!input.files[0]) return;
    const url = URL.createObjectURL(input.files[0]);
    document.getElementById('previewImg').src = url;
    document.getElementById('newPreview').classList.remove('hidden');
});
</script>
<?php
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

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

        $imagePath = null;
        if (!empty($_FILES['image']['name'])) {
            try {
                $imagePath = ImageUploader::saveProductImage($_FILES['image'], $rest_id);
            } catch (\RuntimeException $e) {
                header('Location: /restpo/admin/products/create?error=' . urlencode($e->getMessage())); exit;
            }
        }

        $db->prepare('INSERT INTO products (restaurant_id, category_id, name, description, price, image, status) VALUES (?, ?, ?, ?, ?, ?, ?)')
           ->execute([$rest_id, $_POST['category_id'], $_POST['name'], $_POST['description'] ?? null, $_POST['price'], $imagePath, $_POST['status'] ?? 'active']);

        header('Location: /restpo/admin/products?msg=Product+saved'); exit;
    }

    public function update() {
        $this->requireAdmin();
        $db      = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pid     = intval($_POST['product_id'] ?? 0);

        // Get current product
        $cur = $db->prepare('SELECT image FROM products WHERE id = ? AND restaurant_id = ?');
        $cur->execute([$pid, $rest_id]);
        $cur = $cur->fetch();
        if (!$cur) { header('Location: /restpo/admin/products'); exit; }

        $imagePath = $cur['image']; // keep existing by default

        if (!empty($_POST['remove_image'])) {
            ImageUploader::delete($imagePath);
            $imagePath = null;
        }

        if (!empty($_FILES['image']['name'])) {
            try {
                // Delete old before replacing
                ImageUploader::delete($imagePath);
                $imagePath = ImageUploader::saveProductImage($_FILES['image'], $rest_id);
            } catch (\RuntimeException $e) {
                header('Location: /restpo/admin/products/edit?id=' . $pid . '&error=' . urlencode($e->getMessage())); exit;
            }
        }

        $db->prepare('UPDATE products SET category_id=?, name=?, description=?, price=?, image=?, status=? WHERE id=? AND restaurant_id=?')
           ->execute([$_POST['category_id'], $_POST['name'], $_POST['description'] ?? null, $_POST['price'], $imagePath, $_POST['status'] ?? 'active', $pid, $rest_id]);

        header('Location: /restpo/admin/products?msg=Product+updated'); exit;
    }

    public function delete() {
        $this->requireAdmin();
        $db      = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        $pid     = intval($_POST['product_id'] ?? 0);

        $cur = $db->prepare('SELECT image FROM products WHERE id = ? AND restaurant_id = ?');
        $cur->execute([$pid, $rest_id]);
        $cur = $cur->fetch();
        if ($cur) {
            ImageUploader::delete($cur['image']);
            $db->prepare('DELETE FROM products WHERE id = ? AND restaurant_id = ?')->execute([$pid, $rest_id]);
        }

        header('Location: /restpo/admin/products?msg=Product+deleted'); exit;
    }
}
