<?php include '../purchase_manager/auth_check.php'; ?>
<!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">
    <meta name="description" content="Purchase Requisitions - Purchase Manager">
    <link href="../assets/images/favicon/favicon.png" rel="icon">
    <link href="https://fonts.googleapis.com/css?family=Raleway:400,500,600,700,800" rel="stylesheet">
    <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">
    <link rel="stylesheet" href="./pm-sidebar-styles.css">
    <link rel="stylesheet" href="./pm-theme-enhanced.css">
    <title>Purchase Requisitions</title>
</head>
<body>
<?php include 'pm-sidebar.php'; ?>
<div class="pm-main-container">
    <div class="container">
    <div class="page-header">
        <h1>Kitchen Ingredient Requests</h1>
        <p>Approve kitchen requests and route them to purchasing.</p>
    </div>

    <div class="toolbar">
        <button class="btn-primary" onclick="openRequisitionModal()"><i class="fas fa-plus"></i> New Requisition</button>
        <button class="btn-secondary" onclick="loadRequisitions()"><i class="fas fa-rotate"></i> Refresh</button>
    </div>

    <div class="table-wrapper">
        <table>
            <thead>
            <tr>
                <th>Req #</th>
                <th>Ingredient/Item</th>
                <th>Qty</th>
                <th>Priority</th>
                <th>Status</th>
                <th>Needed By</th>
                <th>Created</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody id="requisitionBody">
            <tr><td colspan="8" class="empty-state">Loading requisitions...</td></tr>
            </tbody>
        </table>
    </div>
</div>

<div class="modal" id="requisitionModal">
    <div class="modal-content">
        <div class="modal-header">
            <span>Create Requisition</span>
            <button class="close" type="button" onclick="closeRequisitionModal()">&times;</button>
        </div>
        <form id="requisitionForm" onsubmit="saveRequisition(event)">
            <div class="form-grid">
                <div class="form-group">
                    <label>Ingredient (optional)</label>
                    <select id="ingredientId">
                        <option value="">Custom item description</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Item Description *</label>
                    <input type="text" id="itemDescription" required>
                </div>
                <div class="form-group">
                    <label>Quantity *</label>
                    <input type="number" step="0.001" min="0.001" id="quantity" required>
                </div>
                <div class="form-group">
                    <label>Unit *</label>
                    <input type="text" id="unit" required>
                </div>
                <div class="form-group">
                    <label>Priority</label>
                    <select id="priority">
                        <option value="medium">Medium</option>
                        <option value="high">High</option>
                        <option value="urgent">Urgent</option>
                        <option value="low">Low</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Needed By</label>
                    <input type="date" id="neededByDate">
                </div>
                <div class="form-group">
                    <label>Requested By</label>
                    <input type="text" id="requestedByName" value="Kitchen">
                </div>
            </div>
            <div class="form-group">
                <label>Notes</label>
                <textarea id="notes" rows="3"></textarea>
            </div>
            <button class="btn-primary" type="submit"><i class="fas fa-check"></i> Save Requisition</button>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
<script>
    let ingredients = [];

    async function checkSession() {
        const response = await fetch('../backend/purchase_manager_session_check.php');
        const data = await response.json();
        if (!data.valid) {
            window.location.href = 'login.php';
            return;
        }
        const name = data.purchase_manager_name || 'Purchase Manager';
        const initials = name.split(' ').map(n => n[0]).join('').substring(0, 2).toUpperCase();
        
        // Update sidebar user info
        const sidebarUserName = document.getElementById('userNameSidebar');
        const sidebarUserAvatar = document.getElementById('userAvatarSidebar');
        if (sidebarUserName) sidebarUserName.textContent = name;
        if (sidebarUserAvatar) sidebarUserAvatar.textContent = initials;
    }

    async function loadIngredients() {
        const response = await fetch('../backend/requisitions_api.php?action=get_ingredients');
        const data = await response.json();
        if (!data.success) return;
        ingredients = data.ingredients || [];
        const select = document.getElementById('ingredientId');
        select.innerHTML = '<option value="">Custom item description</option>' + ingredients.map(i => {
            return `<option value="${i.id}" data-name="${i.name}" data-unit="${i.unit}">${i.name} (${i.current_stock} ${i.unit})</option>`;
        }).join('');
    }

    async function loadRequisitions() {
        const response = await fetch('../backend/requisitions_api.php?action=get_all');
        const data = await response.json();
        const tbody = document.getElementById('requisitionBody');
        tbody.innerHTML = '';

        if (!data.success || !data.requisitions?.length) {
            tbody.innerHTML = '<tr><td colspan="8" class="empty-state">No requisitions found.</td></tr>';
            return;
        }

        data.requisitions.forEach(req => {
            const neededBy = req.needed_by_date ? req.needed_by_date : '-';
            const created = req.created_at ? new Date(req.created_at).toLocaleDateString() : '-';
            const canApprove = req.status === 'pending';
            const canCreatePO = req.status === 'approved' && !req.purchase_order_id;

            tbody.innerHTML += `
                <tr>
                    <td>REQ-${String(req.id).padStart(5, '0')}</td>
                    <td>${escapeHtml(req.item_description)}</td>
                    <td>${Number(req.quantity).toFixed(3).replace(/\.?0+$/, '')} ${escapeHtml(req.unit || '')}</td>
                    <td><span class="status-badge status-${req.priority || 'medium'}">${escapeHtml(req.priority || 'medium')}</span></td>
                    <td><span class="status-badge status-${req.status}">${escapeHtml(req.status)}</span></td>
                    <td>${escapeHtml(neededBy)}</td>
                    <td>${escapeHtml(created)}</td>
                    <td>
                        ${canApprove ? `<button class="action-btn btn-approve" onclick="approveRequisition(${req.id})">Approve</button>` : ''}
                        ${canApprove ? `<button class="action-btn btn-reject" onclick="rejectRequisition(${req.id})">Reject</button>` : ''}
                        ${canCreatePO ? `<button class="action-btn btn-view" onclick="createPOFromReq(${req.id})">Create PO</button>` : ''}
                        ${req.status === 'pending' ? `<button class="action-btn btn-delete" onclick="deleteRequisition(${req.id})">Delete</button>` : ''}
                    </td>
                </tr>
            `;
        });
    }

    function openRequisitionModal() {
        document.getElementById('requisitionForm').reset();
        document.getElementById('requestedByName').value = 'Kitchen';
        document.getElementById('requisitionModal').classList.add('show');
    }

    function closeRequisitionModal() {
        document.getElementById('requisitionModal').classList.remove('show');
    }

    async function saveRequisition(event) {
        event.preventDefault();

        const payload = {
            action: 'create',
            ingredient_id: document.getElementById('ingredientId').value || null,
            item_description: document.getElementById('itemDescription').value.trim(),
            quantity: document.getElementById('quantity').value,
            unit: document.getElementById('unit').value.trim(),
            priority: document.getElementById('priority').value,
            needed_by_date: document.getElementById('neededByDate').value || null,
            requested_by_name: document.getElementById('requestedByName').value.trim(),
            notes: document.getElementById('notes').value.trim()
        };

        const response = await fetch('../backend/requisitions_api.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(payload)
        });
        const data = await response.json();
        if (!data.success) {
            Swal.fire('Error', data.message, 'error');
            return;
        }
        Swal.fire('Saved', 'Requisition created', 'success');
        closeRequisitionModal();
        loadRequisitions();
    }

    async function approveRequisition(id) {
        await updateRequisitionStatus(id, 'approved');
    }

    async function rejectRequisition(id) {
        const {value: reason} = await Swal.fire({
            title: 'Reject Requisition',
            input: 'text',
            inputLabel: 'Reason',
            inputPlaceholder: 'Supplier issue / duplicate / not required',
            showCancelButton: true
        });
        if (!reason) return;
        await updateRequisitionStatus(id, 'rejected', '', reason);
    }

    async function updateRequisitionStatus(id, status, notes = '', rejection_reason = '') {
        const response = await fetch('../backend/requisitions_api.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({action: 'update_status', id, status, notes, rejection_reason})
        });
        const data = await response.json();
        if (!data.success) {
            Swal.fire('Error', data.message, 'error');
            return;
        }
        Swal.fire('Updated', data.message, 'success');
        loadRequisitions();
    }

    function createPOFromReq(id) {
        window.location.href = `purchase_orders.php?requisition_id=${id}`;
    }

    async function deleteRequisition(id) {
        const result = await Swal.fire({
            title: 'Delete requisition?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Delete'
        });
        if (!result.isConfirmed) return;

        const response = await fetch('../backend/requisitions_api.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({action: 'delete', id})
        });
        const data = await response.json();
        if (!data.success) {
            Swal.fire('Error', data.message, 'error');
            return;
        }
        Swal.fire('Deleted', 'Requisition removed', 'success');
        loadRequisitions();
    }

    function escapeHtml(value) {
        return String(value ?? '')
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    document.getElementById('ingredientId').addEventListener('change', function() {
        const option = this.options[this.selectedIndex];
        if (!option || !option.dataset) return;
        if (option.dataset.name) document.getElementById('itemDescription').value = option.dataset.name;
        if (option.dataset.unit) document.getElementById('unit').value = option.dataset.unit;
    });

    function handleLogout() {
        Swal.fire({
            title: 'Logout',
            text: 'Are you sure you want to logout?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, logout'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = '../backend/purchase_manager_logout.php';
            }
        });
    }

    // Update new ingredients notification badge
    async function updateNewIngredientsBadge() {
        try {
            const response = await fetch('../backend/admin_new_ingredient_request_api.php?action=get_requests&status=pending', {
                method: 'GET',
                headers: { 'Content-Type': 'application/json' }
            });

            const data = await response.json();
            const count = data.count || 0;
            const badge = document.getElementById('navNewIngredientsCount');

            if (badge) {
                if (count > 0) {
                    badge.textContent = count;
                    badge.style.display = 'flex';
                } else {
                    badge.style.display = 'none';
                }
            }
        } catch (error) {
            console.log('Could not load new ingredients count');
        }
    }

    document.addEventListener('DOMContentLoaded', async () => {
        await checkSession();
        await loadIngredients();
        await loadRequisitions();
        await updateNewIngredientsBadge();
        setInterval(updateNewIngredientsBadge, 30000);
        const params = new URLSearchParams(window.location.search);
        if (params.get('new') === '1') openRequisitionModal();
    });
</script>

</div>
<script src="./pm-sidebar.js"></script>
</body>
</html>
