<?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;
        }

        .overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.45);
            z-index: 998;
        }

        .overlay.active {
            display: block;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100vh;
            display: flex;
            flex-direction: column;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            color: white;
            z-index: 1000;
            overflow-y: auto;
            box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
        }

        .sidebar-header {
            padding: 30px 20px;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            text-align: center;
            border-bottom: 3px solid #d4a574;
        }

        .sidebar-logo {
            font-size: 40px;
            margin-bottom: 10px;
            display: block;
        }

        .sidebar-header h2 {
            font-size: 20px;
            margin: 10px 0 5px;
            font-weight: 700;
        }

        .sidebar-header p {
            font-size: 12px;
            opacity: 0.9;
            margin: 0;
        }

        .admin-name {
            font-size: 11px;
            opacity: 0.8;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .sidebar-menu {
            list-style: none;
            padding: 20px 0;
            flex: 1;
        }

        .sidebar-menu a {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 25px;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 500;
            border-left: 3px solid transparent;
        }

        .sidebar-menu a:hover,
        .sidebar-menu a.active {
            background: rgba(255, 255, 255, 0.12);
            color: white;
            border-left-color: #d4a574;
        }

        .sidebar-menu i {
            width: 20px;
            text-align: center;
        }

        .sidebar-footer {
            width: 100%;
            margin-top: auto;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            background: rgba(0, 0, 0, 0.1);
        }

        .logout-btn {
            width: 100%;
            padding: 14px 12px;
            border: none;
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            cursor: pointer;
            font-weight: 600;
            font-size: 13px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }

        .topbar {
            position: fixed;
            top: 0;
            left: 280px;
            right: 0;
            height: 70px;
            background: white;
            border-bottom: 1px solid #e8e8e8;
            padding: 0 30px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            z-index: 999;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .topbar-left,
        .topbar-right,
        .topbar-user {
            display: flex;
            align-items: center;
            gap: 18px;
        }

        .topbar-title {
            font-size: 24px;
            font-weight: 700;
            color: #333;
        }

        .menu-toggle {
            width: 42px;
            height: 42px;
            display: none;
            border: none;
            border-radius: 8px;
            background: #f4efe8;
            color: #8b6f47;
            cursor: pointer;
            font-size: 16px;
        }

        .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            font-size: 16px;
        }

        .user-info p {
            margin: 0;
            font-size: 13px;
            color: #999;
        }

        .user-info strong {
            display: block;
            font-size: 14px;
            color: #333;
        }

        .main-content {
            margin-left: 280px;
            margin-top: 70px;
            padding: 30px;
            min-height: calc(100vh - 70px);
        }
        
        .container {
            max-width: none;
            margin: 0;
            padding: 0;
        }
        
        .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: 2000;
            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;
        }

        .search-box select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: white;
        }
        
        .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) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s ease;
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .topbar {
                left: 0;
                padding: 0 20px;
            }

            .menu-toggle {
                display: inline-flex;
                align-items: center;
                justify-content: center;
            }

            .main-content {
                margin-left: 0;
                padding: 20px;
            }

            .form-row {
                grid-template-columns: 1fr;
            }
            
            .stats {
                grid-template-columns: 1fr;
            }

            .header,
            .search-box {
                flex-direction: column;
                align-items: stretch;
            }
            
            table {
                font-size: 12px;
            }
            
            table th,
            table td {
                padding: 8px;
            }
        }
    </style>
</head>
<body>
    <div id="menuOverlay" class="overlay"></div>

    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <i class="fas fa-crown sidebar-logo"></i>
            <h2>Admin Portal</h2>
            <p>Granny Restaurant</p>
            <div class="admin-name" id="sidebarAdminName">Admin</div>
        </div>

        <ul class="sidebar-menu">
            <li><a href="dashboard.php"><i class="fas fa-chart-line"></i> <span>Dashboard</span></a></li>
            <li><a href="carousel.php"><i class="fas fa-images"></i> <span>Carousel</span></a></li>
            <li><a href="gallery.php"><i class="fas fa-th-large"></i> <span>Gallery</span></a></li>
            <li><a href="chefs.php"><i class="fas fa-user-tie"></i> <span>Chefs</span></a></li>
            <li><a href="menu.php"><i class="fas fa-utensils"></i> <span>Menu</span></a></li>
            <li><a href="blog.php"><i class="fas fa-blog"></i> <span>Blog</span></a></li>
            <li><a href="ingredients.php" class="active"><i class="fas fa-leaf"></i> <span>Ingredients</span></a></li>
            <li><a href="recipes.php"><i class="fas fa-book-open"></i> <span>Recipes</span></a></li>
            <li><a href="tables.php"><i class="fas fa-chair"></i> <span>Dine-in Tables</span></a></li>
            <li><a href="online_tables.php"><i class="fas fa-laptop"></i> <span>Online Tables</span></a></li>
            <li><a href="bookings.php"><i class="fas fa-calendar-check"></i> <span>Bookings</span></a></li>
            <li><a href="orders.php"><i class="fas fa-file-invoice"></i> <span>Orders</span></a></li>
            <li><a href="contacts.php"><i class="fas fa-envelope"></i> <span>Contacts</span></a></li>
            <li><a href="feedback.php"><i class="fas fa-comments"></i> <span>Feedback</span></a></li>
            <li><a href="servers.php"><i class="fas fa-user-secret"></i> <span>Servers</span></a></li>
            <li><a href="purchase_managers.php"><i class="fas fa-handshake"></i> <span>Purchase Managers</span></a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> <span>Users</span></a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> <span>Settings</span></a></li>
        </ul>

        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i> Logout
            </button>
        </div>
    </div>

    <div class="topbar">
        <div class="topbar-left">
            <button class="menu-toggle" id="menuToggle">
                <i class="fas fa-bars"></i>
            </button>
            <div class="topbar-title">Ingredients</div>
        </div>
        <div class="topbar-right">
            <div class="topbar-user">
                <div class="user-avatar" id="userInitial">A</div>
                <div class="user-info">
                    <p>Welcome back</p>
                    <strong id="topbarUserName">Admin</strong>
                </div>
            </div>
        </div>
    </div>

    <div class="main-content">
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div>
                <h1><i class="fas fa-warehouse"></i> Stock Receiver - Ingredients</h1>
                <p style="color: #999; margin-top: 5px;">Record incoming stock deliveries and update inventory levels</p>
            </div>
            <div style="display: flex; gap: 10px;">
                <button class="btn btn-primary" onclick="openNewIngredientModal()" style="font-size: 16px; background: #2563eb;">
                    <i class="fas fa-plus"></i> Request New Ingredient
                </button>
                <button class="btn btn-success" onclick="Swal.fire('Stock Management', 'Use the receive stock button next to each ingredient to record incoming deliveries', 'info')" style="font-size: 16px;">
                    <i class="fas fa-info-circle"></i> How to Use
                </button>
            </div>
        </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>
    </div>

    <!-- Request Stock Modal -->
    <div id="requestModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fas fa-cart-plus"></i> Request Stock from Purchase Manager</h2>
                <button class="close-btn" onclick="closeRequestModal()">&times;</button>
            </div>

            <form id="requestForm" onsubmit="submitStockRequest(event)">
                <input type="hidden" id="requestIngredientId">
                
                <div class="form-group">
                    <label>Ingredient: <strong id="requestIngredientName" style="color: var(--primary);"></strong></label>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>Current Stock: <strong id="requestCurrentStock">0</strong> <span id="requestUnit"></span></label>
                    </div>
                    <div class="form-group">
                        <label>Minimum Required: <strong id="requestMinimumStock">0</strong> <span id="requestUnit2"></span></label>
                    </div>
                </div>

                <div class="form-group">
                    <label for="requestQuantity">Quantity Needed <span style="color: red;">*</span></label>
                    <input type="number" id="requestQuantity" step="0.01" required placeholder="How much do you need?" value="0">
                </div>

                <div class="form-group">
                    <label for="requestPriority">Priority</label>
                    <select id="requestPriority">
                        <option value="high">🔴 High - Needed ASAP</option>
                        <option value="medium" selected>🟡 Medium - Soon</option>
                        <option value="low">🟢 Low - Can Wait</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="requestNotes">Notes for Purchase Manager</label>
                    <textarea id="requestNotes" placeholder="e.g., Why is this needed? Any specific requirements?"></textarea>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-paper-plane"></i> Send Request
                    </button>
                    <button type="button" class="btn" style="background: #999; color: white;" onclick="closeRequestModal()">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Request New Ingredient Modal -->
    <div id="newIngredientModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fas fa-sparkles"></i> Request New Ingredient</h2>
                <button class="close-btn" onclick="closeNewIngredientModal()">&times;</button>
            </div>

            <form id="newIngredientForm" onsubmit="submitNewIngredientRequest(event)">
                <div class="form-group">
                    <label for="newIngName">Ingredient Name <span style="color: red;">*</span></label>
                    <input type="text" id="newIngName" required placeholder="e.g., Saffron, Fresh Basil, Imported Olive Oil">
                </div>

                <div class="form-group">
                    <label for="newIngDescription">Description</label>
                    <textarea id="newIngDescription" placeholder="e.g., Grade A, organic, premium quality..."></textarea>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="newIngUnit">Unit <span style="color: red;">*</span></label>
                        <select id="newIngUnit" required>
                            <option value="">Select unit...</option>
                            <option value="kg">kg (Kilogram)</option>
                            <option value="g">g (Gram)</option>
                            <option value="liter">liter (Litre)</option>
                            <option value="ml">ml (Millilitre)</option>
                            <option value="piece">piece</option>
                            <option value="dozen">dozen</option>
                            <option value="box">box</option>
                            <option value="packet">packet</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="newIngSupplier">Supplier (if known)</label>
                        <input type="text" id="newIngSupplier" placeholder="Optional - supplier name">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="newIngQuantity">Initial Quantity to Order <span style="color: red;">*</span></label>
                        <input type="number" id="newIngQuantity" step="0.01" required placeholder="How much to order?" min="0.01">
                    </div>
                    <div class="form-group">
                        <label for="newIngPriority">Priority</label>
                        <select id="newIngPriority">
                            <option value="high">🔴 High - Urgent</option>
                            <option value="medium" selected>🟡 Medium - Soon</option>
                            <option value="low">🟢 Low - Can Wait</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label for="newIngNotes">Notes for Purchase Manager</label>
                    <textarea id="newIngNotes" placeholder="e.g., Why needed? Specific brand? Quality requirements?"></textarea>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-paper-plane"></i> Send Request
                    </button>
                    <button type="button" class="btn" style="background: #999; color: white;" onclick="closeNewIngredientModal()">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() {
            initializeAdminLayout();
            loadIngredients();
            // Request modal click-outside handler
            document.getElementById('requestModal').addEventListener('click', function(e) {
                if (e.target === this) closeRequestModal();
            });
        });

        function initializeAdminLayout() {
            checkAdminAccess();
            document.getElementById('menuToggle').addEventListener('click', toggleSidebar);
            document.getElementById('menuOverlay').addEventListener('click', closeSidebar);
            document.getElementById('logoutBtn').addEventListener('click', logout);
        }

        function checkAdminAccess() {
            let adminData = localStorage.getItem('admin_user') || localStorage.getItem('adminData') || sessionStorage.getItem('admin_user');

            if (adminData) {
                try {
                    const admin = JSON.parse(adminData);
                    updateAdminHeader(admin.name || 'Admin');
                    return;
                } catch (error) {
                    console.error('Error parsing admin data:', error);
                }
            }

            fetch('auth_check.php')
                .then(response => response.json())
                .then(data => {
                    if (data.authenticated && data.user) {
                        updateAdminHeader(data.user.name || 'Admin');
                        localStorage.setItem('admin_user', JSON.stringify(data.user));
                    } else {
                        window.location.href = 'login.php';
                    }
                })
                .catch(error => {
                    console.error('Auth check error:', error);
                    window.location.href = 'login.php';
                });
        }

        function updateAdminHeader(name) {
            document.getElementById('sidebarAdminName').textContent = name;
            document.getElementById('topbarUserName').textContent = name;
            document.getElementById('userInitial').textContent = (name || 'A').charAt(0).toUpperCase();
        }

        function toggleSidebar() {
            document.getElementById('sidebar').classList.toggle('active');
            document.getElementById('menuOverlay').classList.toggle('active');
        }

        function closeSidebar() {
            document.getElementById('sidebar').classList.remove('active');
            document.getElementById('menuOverlay').classList.remove('active');
        }

        function logout() {
            Swal.fire({
                icon: 'warning',
                title: 'Confirm Logout',
                text: 'Are you sure you want to logout?',
                showCancelButton: true,
                confirmButtonColor: '#d4a574',
                cancelButtonColor: '#999',
                confirmButtonText: 'Yes, Logout',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    localStorage.removeItem('admin_user');
                    localStorage.removeItem('admin_token');
                    fetch('../backend/admin_logout.php', { method: 'POST' })
                        .finally(() => {
                            window.location.href = 'login.php';
                        });
                }
            });
        }

        // 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">
                                ${ing.stock_status === 'low' ? `<button class="btn btn-warning btn-sm" onclick="openRequestModal(${ing.id}, '${ing.name}', ${ing.current_stock}, ${ing.minimum_stock}, '${ing.unit}')" style="font-weight: 600; background: #f59e0b;">
                                    <i class="fas fa-shopping-cart"></i> Request Stock
                                </button>` : `<button class="btn btn-sm" style="background: #ccc; color: #666;" disabled>
                                    <i class="fas fa-check"></i> Adequate
                                </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');
        }

        // ===== STOCK REQUEST FUNCTIONS (Admin Role) =====
        function openRequestModal(id, name, currentStock, minimumStock, unit) {
            document.getElementById('requestIngredientId').value = id;
            document.getElementById('requestIngredientName').textContent = name;
            document.getElementById('requestCurrentStock').textContent = currentStock.toFixed(2);
            document.getElementById('requestMinimumStock').textContent = minimumStock.toFixed(2);
            document.getElementById('requestUnit').textContent = unit;
            document.getElementById('requestUnit2').textContent = unit;
            // Suggest quantity = minimum stock
            document.getElementById('requestQuantity').value = minimumStock.toFixed(2);
            document.getElementById('requestForm').reset();
            document.getElementById('requestModal').classList.add('active');
        }

        function closeRequestModal() {
            document.getElementById('requestModal').classList.remove('active');
        }

        async function submitStockRequest(e) {
            e.preventDefault();

            const ingredientId = document.getElementById('requestIngredientId').value;
            const quantity = parseFloat(document.getElementById('requestQuantity').value);
            const priority = document.getElementById('requestPriority').value;
            const notes = document.getElementById('requestNotes').value;

            if (!quantity || quantity <= 0) {
                Swal.fire('Error', 'Please enter a valid quantity', 'error');
                return;
            }

            try {
                const response = await fetch('../backend/admin_stock_request_api.php?action=create_request', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        ingredient_id: ingredientId,
                        quantity_requested: quantity,
                        priority: priority,
                        notes: notes,
                        requested_by: 'admin'
                    })
                });

                const data = await response.json();

                if (data.success) {
                    Swal.fire('Success!', 'Stock request sent to Purchase Manager. They will process it soon.', 'success');
                    closeRequestModal();
                    loadIngredients();
                } else {
                    Swal.fire('Error', data.message || 'Failed to submit request', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to submit request: ' + error.message, 'error');
            }
        }

        // ===== NEW INGREDIENT REQUEST FUNCTIONS =====
        function openNewIngredientModal() {
            document.getElementById('newIngredientForm').reset();
            document.getElementById('newIngredientModal').classList.add('active');
        }

        function closeNewIngredientModal() {
            document.getElementById('newIngredientModal').classList.remove('active');
        }

        async function submitNewIngredientRequest(e) {
            e.preventDefault();

            const name = document.getElementById('newIngName').value.trim();
            const description = document.getElementById('newIngDescription').value.trim();
            const unit = document.getElementById('newIngUnit').value;
            const supplier = document.getElementById('newIngSupplier').value.trim();
            const quantity = parseFloat(document.getElementById('newIngQuantity').value);
            const priority = document.getElementById('newIngPriority').value;
            const notes = document.getElementById('newIngNotes').value.trim();

            if (!name || !unit || !quantity || quantity <= 0) {
                Swal.fire('Validation Error', 'Please fill all required fields correctly', 'warning');
                return;
            }

            try {
                const response = await fetch('../backend/admin_new_ingredient_request_api.php?action=create_request', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        name: name,
                        description: description,
                        unit: unit,
                        supplier: supplier,
                        quantity_requested: quantity,
                        priority: priority,
                        notes: notes,
                        requested_by: 'admin'
                    })
                });

                const data = await response.json();

                if (data.success) {
                    Swal.fire('Request Sent!', 'New ingredient request sent to Purchase Manager. They will review and approve it.', 'success');
                    closeNewIngredientModal();
                } else {
                    Swal.fire('Error', data.message || 'Failed to submit request', 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire('Error', 'Failed to submit request: ' + error.message, 'error');
            }
        }

        // Disabled functions for Stock Receiver mode
        function closeStockModal() {
            // Not used in request mode
        }
    </script>
</body>
</html>
