<?php
require 'auth_check.php';
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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>New Ingredient Requests - Purchase Manager</title>
    <style>
        .tab-container {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            border-bottom: 2px solid var(--border-color);
        }

        .tab {
            padding: 12px 20px;
            background: none;
            border: none;
            cursor: pointer;
            font-weight: 600;
            color: var(--text-secondary);
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
        }

        .tab.active {
            color: var(--primary);
            border-bottom-color: var(--primary);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .request-card {
            background: var(--bg-secondary);
            border: 1px solid var(--border-color);
            border-radius: var(--radius);
            padding: 20px;
            margin-bottom: 15px;
            transition: all 0.3s ease;
        }

        .request-card:hover {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .request-card-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 15px;
        }

        .request-card-title {
            font-size: 18px;
            font-weight: 700;
            color: var(--text-primary);
        }

        .request-card-meta {
            display: flex;
            gap: 15px;
            margin: 12px 0;
            flex-wrap: wrap;
            font-size: 14px;
        }

        .request-card-meta-item {
            display: flex;
            align-items: center;
            gap: 8px;
            color: var(--text-secondary);
        }

        .request-card-meta-item strong {
            color: var(--text-primary);
        }

        .request-details {
            background: var(--bg-tertiary);
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            font-size: 14px;
        }

        .request-details-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 10px;
        }

        .request-details-row:last-child {
            margin-bottom: 0;
        }

        .detail-item {
            display: flex;
            flex-direction: column;
        }

        .detail-label {
            font-weight: 600;
            color: var(--text-secondary);
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .detail-value {
            font-size: 16px;
            color: var(--text-primary);
            margin-top: 5px;
        }

        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .badge-pending {
            background: #fef3c7;
            color: #92400e;
        }

        .badge-approved {
            background: #d1fae5;
            color: #065f46;
        }

        .badge-rejected {
            background: #fee2e2;
            color: #991b1b;
        }

        .badge-priority-high {
            background: #fee2e2;
            color: #991b1b;
        }

        .badge-priority-medium {
            background: #fef3c7;
            color: #92400e;
        }

        .badge-priority-low {
            background: #e0f2fe;
            color: #0c4a6e;
        }

        .request-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .approval-form {
            background: var(--bg-tertiary);
            padding: 20px;
            border-radius: 8px;
            margin-top: 15px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 8px;
            font-size: 14px;
        }

        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            font-family: inherit;
            font-size: 14px;
        }

        .form-group input:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: var(--text-secondary);
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
        }
    </style>
</head>
<body>
<?php include 'pm-sidebar.php'; ?>
<div class="pm-main-container">
        <div class="container">
            <!-- Header -->
            <div class="page-header">
                <div class="page-header-content">
                    <h1><i class="fas fa-leaf"></i> New Ingredient Requests</h1>
                    <p>Review and approve requests for new ingredients to add to inventory</p>
                </div>
            </div>

            <!-- Tabs -->
            <div class="tab-container">
                <button class="tab active" onclick="switchTab('pending')">
                    <i class="fas fa-clock"></i> Pending <span id="pendingCount" style="margin-left: 8px; background: #ef4444; color: white; padding: 2px 8px; border-radius: 12px; font-size: 12px;">0</span>
                </button>
                <button class="tab" onclick="switchTab('approved')">
                    <i class="fas fa-check-circle"></i> Approved
                </button>
                <button class="tab" onclick="switchTab('rejected')">
                    <i class="fas fa-ban"></i> Rejected
                </button>
            </div>

            <!-- Pending Requests -->
            <div id="pending" class="tab-content active" style="min-height: 400px;">
                <div id="pendingContainer"></div>
            </div>

            <!-- Approved Requests -->
            <div id="approved" class="tab-content" style="min-height: 400px;">
                <div id="approvedContainer"></div>
            </div>

            <!-- Rejected Requests -->
            <div id="rejected" class="tab-content" style="min-height: 400px;">
                <div id="rejectedContainer"></div>
            </div>
        </div>
    </div>

    <!-- Approval Modal -->
    <div id="approvalModal" class="modal">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <span><i class="fas fa-check-circle"></i> Approve Ingredient Request</span>
                <button class="close" type="button" onclick="closeApprovalModal()">&times;</button>
            </div>
            <form id="approvalForm" onsubmit="submitApproval(event)">
                <input type="hidden" id="approvalRequestId">
                <div class="approval-form">
                    <div class="form-group">
                        <label>Ingredient Name (Read-Only)</label>
                        <input type="text" id="approvalIngredientName" readonly style="background: var(--bg-secondary);">
                    </div>

                    <div class="form-grid">
                        <div class="form-group">
                            <label>Current Stock *</label>
                            <input type="number" id="approvalCurrentStock" step="0.01" required placeholder="0" value="0">
                        </div>
                        <div class="form-group">
                            <label>Minimum Stock *</label>
                            <input type="number" id="approvalMinimumStock" step="0.01" required placeholder="10" value="10">
                        </div>
                        <div class="form-group">
                            <label>Unit Cost (₹) *</label>
                            <input type="number" id="approvalUnitCost" step="0.01" required placeholder="0" value="0" min="0">
                        </div>
                    </div>

                    <div style="margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border-color);">
                        <p style="color: var(--text-secondary); font-size: 14px; margin-bottom: 15px;">
                            After approval, admin will not be able to request this ingredient again. The system will track it as an active ingredient. Initial stock will be created with quantity = 0 (PM updates when deliveries arrive).
                        </p>
                    </div>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: flex-end;">
                    <button type="button" class="btn-secondary" onclick="closeApprovalModal()">Cancel</button>
                    <button type="submit" class="btn-primary">Approve & Create Ingredient</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Rejection Modal -->
    <div id="rejectionModal" class="modal">
        <div class="modal-content" style="max-width: 500px;">
            <div class="modal-header">
                <span><i class="fas fa-ban"></i> Reject Ingredient Request</span>
                <button class="close" type="button" onclick="closeRejectionModal()">&times;</button>
            </div>
            <form id="rejectionForm" onsubmit="submitRejection(event)">
                <input type="hidden" id="rejectionRequestId">
                <div class="approval-form">
                    <div class="form-group">
                        <label>Ingredient Name (Read-Only)</label>
                        <input type="text" id="rejectionIngredientName" readonly style="background: var(--bg-secondary);">
                    </div>

                    <div class="form-group">
                        <label for="rejectionReason">Reason for Rejection *</label>
                        <textarea id="rejectionReason" required placeholder="e.g., Already have similar ingredient, Budget constraints, Quality concerns..." rows="4"></textarea>
                    </div>
                </div>

                <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: flex-end;">
                    <button type="button" class="btn-secondary" onclick="closeRejectionModal()">Cancel</button>
                    <button type="submit" class="btn-danger">Reject Request</button>
                </div>
            </form>
        </div>
    </div>

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

    <script>
        let currentRequestId = null;

        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 loadRequests(status) {
            try {
                const response = await fetch(`../backend/admin_new_ingredient_request_api.php?action=get_requests&status=${status}`, {
                    method: 'GET',
                    headers: { 'Content-Type': 'application/json' }
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || 'Failed to load requests');
                }

                const requests = data.requests || [];
                const containerId = status + 'Container';
                const container = document.getElementById(containerId);

                // Update pending count badge
                if (status === 'pending') {
                    document.getElementById('pendingCount').textContent = requests.length;
                }

                if (requests.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-inbox"></i>
                            <p>No ${status} requests</p>
                        </div>
                    `;
                    return;
                }

                const html = requests.map(req => `
                    <div class="request-card">
                        <div class="request-card-header">
                            <div>
                                <div class="request-card-title">${escapeHtml(req.name)}</div>
                                <div class="request-card-meta">
                                    <span class="badge badge-priority-${req.priority}">${req.priority.toUpperCase()}</span>
                                    <span class="badge badge-${status}">${status.toUpperCase()}</span>
                                </div>
                            </div>
                        </div>

                        ${req.description ? `<p style="color: var(--text-secondary); margin-bottom: 12px;"><strong>Description:</strong> ${escapeHtml(req.description)}</p>` : ''}

                        <div class="request-details">
                            <div class="request-details-row">
                                <div class="detail-item">
                                    <span class="detail-label">Unit</span>
                                    <span class="detail-value">${escapeHtml(req.unit)}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">Quantity Requested</span>
                                    <span class="detail-value">${parseFloat(req.quantity_requested).toFixed(2)} ${escapeHtml(req.unit)}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">Supplier</span>
                                    <span class="detail-value">${req.supplier || '-'}</span>
                                </div>
                            </div>
                            <div class="request-details-row">
                                <div class="detail-item">
                                    <span class="detail-label">Requested By</span>
                                    <span class="detail-value">${escapeHtml(req.requested_by)}</span>
                                </div>
                                <div class="detail-item">
                                    <span class="detail-label">Requested Date</span>
                                    <span class="detail-value">${new Date(req.created_at).toLocaleDateString()}</span>
                                </div>
                                ${status !== 'pending' ? `
                                    <div class="detail-item">
                                        <span class="detail-label">Processed By</span>
                                        <span class="detail-value">${escapeHtml(req.approved_by || '-')}</span>
                                    </div>
                                ` : ''}
                            </div>
                        </div>

                        ${req.notes ? `<p style="color: var(--text-secondary); font-size: 14px; background: var(--bg-tertiary); padding: 12px; border-radius: 6px; margin: 12px 0;"><strong>Notes:</strong> ${escapeHtml(req.notes)}</p>` : ''}

                        ${status === 'pending' ? `
                            <div class="request-actions">
                                <button class="btn btn-primary" onclick="openApprovalModal(${req.id}, '${req.name.replace(/'/g, "\\'")}')">
                                    <i class="fas fa-check-circle"></i> Approve
                                </button>
                                <button class="btn btn-danger" onclick="openRejectionModal(${req.id}, '${req.name.replace(/'/g, "\\'")}')">
                                    <i class="fas fa-ban"></i> Reject
                                </button>
                            </div>
                        ` : ''}

                        ${(status === 'approved' || status === 'rejected') ? `
                            <div class="request-actions">
                                <button class="btn btn-danger" onclick="deleteProcessedRequest(${req.id}, '${req.name.replace(/'/g, "\\'")}', '${status}')">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            </div>
                        ` : ''}

                        ${status === 'approved' && req.created_ingredient_id ? `
                            <p style="color: var(--secondary); font-size: 14px; padding: 8px 12px; background: rgba(16, 185, 129, 0.1); border-radius: 6px; margin-top: 12px;">
                                <i class="fas fa-check"></i> Created as Ingredient ID #${req.created_ingredient_id}
                            </p>
                        ` : ''}

                        ${status === 'rejected' && req.rejection_reason ? `
                            <p style="color: #991b1b; font-size: 14px; padding: 8px 12px; background: rgba(239, 68, 68, 0.1); border-radius: 6px; margin-top: 12px;">
                                <i class="fas fa-times"></i> <strong>Rejection Reason:</strong> ${escapeHtml(req.rejection_reason)}
                            </p>
                        ` : ''}
                    </div>
                `).join('');

                container.innerHTML = html;
            } catch (error) {
                console.error('Error:', error);
                const container = document.getElementById(status + 'Container');
                container.innerHTML = `<div class="empty-state"><i class="fas fa-exclamation-triangle"></i><p>Error loading requests</p></div>`;
            }
        }

        function switchTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // Show selected tab
            document.getElementById(tabName).classList.add('active');
            event.target.closest('.tab').classList.add('active');

            // Load requests for this tab
            loadRequests(tabName);
        }

        function openApprovalModal(requestId, requestName) {
            currentRequestId = requestId;
            document.getElementById('approvalRequestId').value = requestId;
            document.getElementById('approvalIngredientName').value = requestName;
            document.getElementById('approvalCurrentStock').value = '0';
            document.getElementById('approvalMinimumStock').value = '10';
            document.getElementById('approvalUnitCost').value = '0';
            document.getElementById('approvalModal').style.display = 'flex';
        }

        function closeApprovalModal() {
            document.getElementById('approvalModal').style.display = 'none';
        }

        function openRejectionModal(requestId, requestName) {
            currentRequestId = requestId;
            document.getElementById('rejectionRequestId').value = requestId;
            document.getElementById('rejectionIngredientName').value = requestName;
            document.getElementById('rejectionReason').value = '';
            document.getElementById('rejectionModal').style.display = 'flex';
        }

        function closeRejectionModal() {
            document.getElementById('rejectionModal').style.display = 'none';
        }

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

            const currentStock = parseFloat(document.getElementById('approvalCurrentStock').value);
            const minimumStock = parseFloat(document.getElementById('approvalMinimumStock').value);
            const unitCost = parseFloat(document.getElementById('approvalUnitCost').value);

            try {
                const response = await fetch('../backend/admin_new_ingredient_request_api.php?action=approve_request', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        request_id: currentRequestId,
                        current_stock: currentStock,
                        minimum_stock: minimumStock,
                        unit_cost: unitCost
                    })
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || 'Failed to approve request');
                }

                Swal.fire('Approved!', `"${data.ingredient_name}" has been added to inventory.`, 'success');
                closeApprovalModal();
                loadRequests('pending');
                loadRequests('approved');
            } catch (error) {
                Swal.fire('Error', error.message, 'error');
            }
        }

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

            const reason = document.getElementById('rejectionReason').value.trim();

            try {
                const response = await fetch('../backend/admin_new_ingredient_request_api.php?action=reject_request', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        request_id: currentRequestId,
                        reason: reason
                    })
                });

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || 'Failed to reject request');
                }

                Swal.fire('Rejected!', 'The request has been rejected.', 'success');
                closeRejectionModal();
                loadRequests('pending');
                loadRequests('rejected');
            } catch (error) {
                Swal.fire('Error', error.message, 'error');
            }
        }

        async function deleteProcessedRequest(requestId, requestName, status) {
            const result = await Swal.fire({
                title: 'Delete Request?',
                text: `Delete "${requestName}" from ${status} requests?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#ef4444'
            });

            if (!result.isConfirmed) return;

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

                const data = await response.json();

                if (!response.ok) {
                    throw new Error(data.message || 'Failed to delete request');
                }

                Swal.fire('Deleted!', 'The request has been deleted.', 'success');
                loadRequests(status);
            } catch (error) {
                Swal.fire('Error', error.message, 'error');
            }
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // Modal outside click handling
        document.getElementById('approvalModal').addEventListener('click', function(e) {
            if (e.target === this) closeApprovalModal();
        });

        document.getElementById('rejectionModal').addEventListener('click', function(e) {
            if (e.target === this) closeRejectionModal();
        });

        // Load pending requests on page load
        window.addEventListener('DOMContentLoaded', function() {
            checkSession();
            loadRequests('pending');
        });

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

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