<?php
/**
 * Admin Ingredients Management Page
 * Manage ingredient inventory, stock levels, and suppliers
 */
session_start();

// For now, allow access (in production, check admin authentication)
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit;
}
?>
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Ingredient Management - Granny Restaurant Admin">
    <link href="../assets/images/favicon/favicon.png" rel="icon">
    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <title>Ingredient Management - Granny Restaurant</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Raleway', sans-serif;
            background: #f5f5f5;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 28px;
            color: #333;
        }
        
        .btn {
            display: inline-block;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.3s ease;
            text-decoration: none;
        }
        
        .btn-primary {
            background: #d4a574;
            color: white;
        }
        
        .btn-primary:hover {
            background: #b8935f;
        }
        
        .btn-success {
            background: #4caf50;
            color: white;
        }
        
        .btn-success:hover {
            background: #45a049;
        }
        
        .btn-error {
            background: #f44336;
            color: white;
        }
        
        .btn-error:hover {
            background: #da190b;
        }
        
        .btn-info {
            background: #2196f3;
            color: white;
        }
        
        .btn-info:hover {
            background: #0b7dda;
        }
        
        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        
        .stat-card h3 {
            color: #999;
            font-size: 13px;
            text-transform: uppercase;
            margin-bottom: 10px;
        }
        
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
            color: #d4a574;
        }
        
        .content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .table-responsive {
            overflow-x: auto;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        table thead {
            background: #f5f5f5;
            border-bottom: 2px solid #ddd;
        }
        
        table th {
            padding: 12px;
            text-align: left;
            font-weight: bold;
            color: #333;
        }
        
        table td {
            padding: 12px;
            border-bottom: 1px solid #eee;
        }
        
        table tbody tr:hover {
            background: #f9f9f9;
        }
        
        .stock-status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .stock-low {
            background: #ffebee;
            color: #c62828;
        }
        
        .stock-normal {
            background: #e8f5e9;
            color: #2e7d32;
        }
        
        .stock-adequate {
            background: #e3f2fd;
            color: #1565c0;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease;
        }
        
        .modal.active {
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .modal-content {
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            max-width: 600px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            animation: slideIn 0.3s ease;
        }
        
        @keyframes slideIn {
            from {
                transform: translateY(-30px);
                opacity: 0;
            }
            to {
                transform: translateY(0);
                opacity: 1;
            }
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .modal-header h2 {
            color: #333;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }
        
        .close-btn:hover {
            color: #333;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-family: 'Raleway', sans-serif;
            font-size: 14px;
        }
        
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #d4a574;
            box-shadow: 0 0 5px rgba(212, 165, 116, 0.3);
        }
        
        .form-group textarea {
            resize: vertical;
            min-height: 80px;
        }
        
        .form-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .modal-footer {
            display: flex;
            gap: 10px;
            margin-top: 25px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        
        .modal-footer button {
            flex: 1;
        }
        
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        
        .search-box {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        
        .search-box input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }
        
        @media (max-width: 768px) {
            .form-row {
                grid-template-columns: 1fr;
            }
            
            .stats {
                grid-template-columns: 1fr;
            }
            
            table {
                font-size: 12px;
            }
            
            table th,
            table td {
                padding: 8px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div>
                <h1><i class="fas fa-boxes"></i> Ingredient Management</h1>
                <p style="color: #999; margin-top: 5px;">Manage your restaurant's ingredient inventory</p>
            </div>
            <button class="btn btn-primary" onclick="openAddModal()" style="font-size: 16px;">
                <i class="fas fa-plus"></i> Add Ingredient
            </button>
        </div>

        <!-- Stats -->
        <div class="stats" id="statsContainer">
            <div class="stat-card">
                <h3>Total Ingredients</h3>
                <div class="number" id="totalCount">0</div>
            </div>
            <div class="stat-card">
                <h3>Low Stock Items</h3>
                <div class="number" id="lowStockCount">0</div>
            </div>
            <div class="stat-card">
                <h3>Total Inventory Value</h3>
                <div class="number" id="totalValue">₹0</div>
            </div>
        </div>

        <!-- Content -->
        <div class="content">
            <!-- Search -->
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Search ingredients by name..." onkeyup="filterTable()">
                <select id="statusFilter" onchange="filterTable()">
                    <option value="">All Status</option>
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                    <option value="discontinued">Discontinued</option>
                </select>
            </div>

            <!-- Ingredients Table -->
            <div class="table-responsive">
                <table id="ingredientsTable">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Unit</th>
                            <th>Current Stock</th>
                            <th>Min. Stock</th>
                            <th>Unit Cost</th>
                            <th>Status</th>
                            <th>Supplier</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="ingredientsTableBody">
                        <tr>
                            <td colspan="8" style="text-align: center; padding: 40px 20px; color: #999;">
                                <i class="fas fa-spinner fa-spin"></i> Loading ingredients...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- Empty State -->
            <div id="emptyState" class="empty-state" style="display: none;">
                <i class="fas fa-inbox"></i>
                <p>No ingredients found. Start by adding your first ingredient!</p>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div id="ingredientModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">Add Ingredient</h2>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>

            <form id="ingredientForm" onsubmit="saveIngredient(event)">
                <div class="form-group">
                    <label for="ingredientName">Ingredient Name *</label>
                    <input type="text" id="ingredientName" required>
                </div>

                <div class="form-group">
                    <label for="ingredientDesc">Description</label>
                    <textarea id="ingredientDesc"></textarea>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="ingredientUnit">Unit of Measurement *</label>
                        <select id="ingredientUnit" required>
                            <option value="">Select unit</option>
                            <option value="kg">Kilogram (kg)</option>
                            <option value="g">Gram (g)</option>
                            <option value="liter">Liter (L)</option>
                            <option value="ml">Milliliter (ml)</option>
                            <option value="pieces">Pieces</option>
                            <option value="dozen">Dozen</option>
                            <option value="box">Box</option>
                            <option value="bottle">Bottle</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="ingredientUnitCost">Unit Cost (₹) *</label>
                        <input type="number" id="ingredientUnitCost" step="0.01" required>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="ingredientCurrentStock">Current Stock *</label>
                        <input type="number" id="ingredientCurrentStock" step="0.01" required>
                    </div>

                    <div class="form-group">
                        <label for="ingredientMinStock">Minimum Stock Level *</label>
                        <input type="number" id="ingredientMinStock" step="0.01" required>
                    </div>
                </div>

                <div class="form-group">
                    <label for="ingredientSupplier">Supplier</label>
                    <input type="text" id="ingredientSupplier" placeholder="Supplier name">
                </div>

                <div class="form-group">
                    <label for="ingredientStatus">Status *</label>
                    <select id="ingredientStatus" required>
                        <option value="active">Active</option>
                        <option value="inactive">Inactive</option>
                        <option value="discontinued">Discontinued</option>
                    </select>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-save"></i> Save Ingredient
                    </button>
                    <button type="button" class="btn" style="background: #999; color: white;" onclick="closeModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Stock Update Modal -->
    <div id="stockModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Update Stock</h2>
                <button class="close-btn" onclick="closeStockModal()">&times;</button>
            </div>

            <form id="stockForm" onsubmit="updateStock(event)">
                <div class="form-group">
                    <label>Ingredient: <strong id="stockIngredientName"></strong></label>
                </div>

                <div class="form-group">
                    <label>Current Stock: <strong id="stockCurrentValue">0</strong> <span id="stockUnit"></span></label>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="stockAction">Action *</label>
                        <select id="stockAction" required>
                            <option value="add">Add Stock</option>
                            <option value="subtract">Remove Stock</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="stockQuantity">Quantity *</label>
                        <input type="number" id="stockQuantity" step="0.01" required>
                    </div>
                </div>

                <div class="form-group">
                    <label for="stockNotes">Notes</label>
                    <textarea id="stockNotes" placeholder="Why are you updating this stock?"></textarea>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-check"></i> Update Stock
                    </button>
                    <button type="button" class="btn" style="background: #999; color: white;" onclick="closeStockModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

    <script>
        let currentIngredientId = null;
        let allIngredients = [];

        // Initialize
        document.addEventListener('DOMContentLoaded', function() {
            loadIngredients();
        });

        // Load ingredients
        async function loadIngredients() {
            try {
                const response = await fetch('../backend/admin_ingredients_api.php?action=get_ingredients&status=active');
                const data = await response.json();

                if (data.success) {
                    allIngredients = data.data || [];
                    renderTable();
                    updateStats();
                } else {
                    Swal.fire('Error', data.message || 'Failed to load ingredients', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to load ingredients', 'error');
            }
        }

        // Render table
        function renderTable() {
            const tableBody = document.getElementById('ingredientsTableBody');
            const emptyState = document.getElementById('emptyState');

            if (allIngredients.length === 0) {
                tableBody.innerHTML = '';
                emptyState.style.display = 'block';
                return;
            }

            emptyState.style.display = 'none';
            tableBody.innerHTML = allIngredients.map(ing => {
                const stockStatusClass = ing.stock_status === 'low' ? 'stock-low' : 
                                        ing.stock_status === 'adequate' ? 'stock-adequate' : 'stock-normal';
                const stockLabel = ing.stock_status === 'low' ? 'Low Stock' : 
                                 ing.stock_status === 'adequate' ? 'Adequate' : 'Normal';

                return `
                    <tr>
                        <td><strong>${ing.name}</strong></td>
                        <td>${ing.unit}</td>
                        <td><strong>${parseFloat(ing.current_stock).toFixed(2)}</strong></td>
                        <td>${parseFloat(ing.minimum_stock).toFixed(2)}</td>
                        <td>₹${parseFloat(ing.unit_cost).toFixed(2)}</td>
                        <td><span class="stock-status ${stockStatusClass}">${stockLabel}</span></td>
                        <td>${ing.supplier || '-'}</td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn btn-info btn-sm" onclick="openStockModal(${ing.id}, '${ing.name}', ${ing.current_stock}, '${ing.unit}')">
                                    📦
                                </button>
                                <button class="btn btn-primary btn-sm" onclick="editIngredient(${ing.id})">
                                    ✏️
                                </button>
                                <button class="btn btn-error btn-sm" onclick="deleteIngredient(${ing.id}, '${ing.name}')">
                                    ❌
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
            }).join('');
        }

        // Update stats
        function updateStats() {
            const totalCount = allIngredients.length;
            const lowStockCount = allIngredients.filter(i => i.stock_status === 'low').length;
            const totalValue = allIngredients.reduce((sum, i) => sum + (parseFloat(i.current_stock) * parseFloat(i.unit_cost)), 0);

            document.getElementById('totalCount').textContent = totalCount;
            document.getElementById('lowStockCount').textContent = lowStockCount;
            document.getElementById('totalValue').textContent = '₹' + totalValue.toFixed(2);
        }

        // Filter table
        function filterTable() {
            const searchText = document.getElementById('searchInput').value.toLowerCase();
            const statusFilter = document.getElementById('statusFilter').value;

            const tableBody = document.getElementById('ingredientsTableBody');
            tableBody.querySelectorAll('tr').forEach(row => {
                const name = row.cells[0].textContent.toLowerCase();
                const status = row.cells[5].textContent.toLowerCase();

                const matchesSearch = name.includes(searchText);
                const matchesStatus = !statusFilter || status.includes(statusFilter);

                row.style.display = (matchesSearch && matchesStatus) ? '' : 'none';
            });
        }

        // Open add modal
        function openAddModal() {
            currentIngredientId = null;
            document.getElementById('modalTitle').textContent = 'Add New Ingredient';
            document.getElementById('ingredientForm').reset();
            document.getElementById('ingredientModal').classList.add('active');
        }

        // Open edit modal
        async function editIngredient(id) {
            try {
                const response = await fetch('../backend/admin_ingredients_api.php?action=get_ingredient', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id })
                });

                const data = await response.json();

                if (data.success) {
                    const ing = data.data;
                    currentIngredientId = ing.id;
                    document.getElementById('modalTitle').textContent = 'Edit Ingredient';
                    document.getElementById('ingredientName').value = ing.name;
                    document.getElementById('ingredientDesc').value = ing.description || '';
                    document.getElementById('ingredientUnit').value = ing.unit;
                    document.getElementById('ingredientUnitCost').value = ing.unit_cost;
                    document.getElementById('ingredientCurrentStock').value = ing.current_stock;
                    document.getElementById('ingredientMinStock').value = ing.minimum_stock;
                    document.getElementById('ingredientSupplier').value = ing.supplier || '';
                    document.getElementById('ingredientStatus').value = ing.status;
                    document.getElementById('ingredientModal').classList.add('active');
                } else {
                    Swal.fire('Error', data.message || 'Failed to load ingredient', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to load ingredient', 'error');
            }
        }

        // Save ingredient
        async function saveIngredient(e) {
            e.preventDefault();

            const ingredientData = {
                name: document.getElementById('ingredientName').value,
                description: document.getElementById('ingredientDesc').value,
                unit: document.getElementById('ingredientUnit').value,
                unit_cost: parseFloat(document.getElementById('ingredientUnitCost').value),
                current_stock: parseFloat(document.getElementById('ingredientCurrentStock').value),
                minimum_stock: parseFloat(document.getElementById('ingredientMinStock').value),
                supplier: document.getElementById('ingredientSupplier').value,
                status: document.getElementById('ingredientStatus').value
            };

            if (currentIngredientId) {
                ingredientData.id = currentIngredientId;
            }

            try {
                const action = currentIngredientId ? 'update_ingredient' : 'create_ingredient';
                const response = await fetch(`../backend/admin_ingredients_api.php?action=${action}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(ingredientData)
                });

                const data = await response.json();

                if (data.success) {
                    Swal.fire('Success', data.message || 'Ingredient saved successfully', 'success');
                    closeModal();
                    loadIngredients();
                } else {
                    Swal.fire('Error', data.message || 'Failed to save ingredient', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to save ingredient', 'error');
            }
        }

        // Delete ingredient
        function deleteIngredient(id, name) {
            Swal.fire({
                title: 'Delete Ingredient?',
                text: `Are you sure you want to delete "${name}"?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#f44336',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Delete'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    try {
                        const response = await fetch('../backend/admin_ingredients_api.php?action=delete_ingredient', {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            body: JSON.stringify({ id })
                        });

                        const data = await response.json();

                        if (data.success) {
                            Swal.fire('Deleted', 'Ingredient deleted successfully', 'success');
                            loadIngredients();
                        } else {
                            Swal.fire('Error', data.message || 'Failed to delete ingredient', 'error');
                        }
                    } catch (error) {
                        console.error('Error:', error);
                        Swal.fire('Error', 'Failed to delete ingredient', 'error');
                    }
                }
            });
        }

        // Open stock modal
        function openStockModal(id, name, currentStock, unit) {
            currentIngredientId = id;
            document.getElementById('stockIngredientName').textContent = name;
            document.getElementById('stockCurrentValue').textContent = currentStock.toFixed(2);
            document.getElementById('stockUnit').textContent = unit;
            document.getElementById('stockForm').reset();
            document.getElementById('stockModal').classList.add('active');
        }

        // Close stock modal
        function closeStockModal() {
            document.getElementById('stockModal').classList.remove('active');
        }

        // Update stock
        async function updateStock(e) {
            e.preventDefault();

            const stockData = {
                id: currentIngredientId,
                quantity: parseFloat(document.getElementById('stockQuantity').value),
                action: document.getElementById('stockAction').value,
                notes: document.getElementById('stockNotes').value
            };

            try {
                const response = await fetch('../backend/admin_ingredients_api.php?action=update_stock', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(stockData)
                });

                const data = await response.json();

                if (data.success) {
                    Swal.fire('Success', 'Stock updated successfully', 'success');
                    closeStockModal();
                    loadIngredients();
                } else {
                    Swal.fire('Error', data.message || 'Failed to update stock', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to update stock', 'error');
            }
        }

        // Close modal
        function closeModal() {
            document.getElementById('ingredientModal').classList.remove('active');
            currentIngredientId = null;
        }
    </script>
</body>
</html>
