<?php
// ======================================================
// CREATE NEW ISSUE (WITH AVERAGE RATE)
// ======================================================

require_once '../includes/auth.php';
require_once '../config/database.php';

// Get departments for dropdown
$departments = $conn->query("SELECT id, name FROM departments WHERE $items = mysqli_query($conn, "SELECT id, item_code, item_name FROM items WHERE status = 1 ORDER BY item_name");$items = mysqli_query($conn, "SELECT id, item_code, item_name FROM items ORDER BY item_name"); ORDER BY name ASC");

// Get items with current average rate and available stock
$items = $conn->query("
    SELECT 
        i.*,
        c.name as category_name,
        COALESCE(SUM(CASE WHEN st.transaction_type IN ('opening', 'in') THEN st.quantity ELSE 0 END), 0) -
        COALESCE(SUM(CASE WHEN st.transaction_type = 'out' THEN st.quantity ELSE 0 END), 0) as available_stock,
        COALESCE(i.current_average_rate, 0) as current_rate
    FROM items i
    LEFT JOIN categories c ON i.category_id = c.id
    LEFT JOIN stock_transactions st ON i.id = st.item_id
    WHERE i.status = 1
    GROUP BY i.id
    HAVING available_stock > 0
    ORDER BY i.item_name ASC
");
?>
<?php include '../includes/header.php'; ?>
<?php include '../includes/navbar.php'; ?>
<?php include '../includes/sidebar.php'; ?>

<div class="main-content">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-plus-circle me-2"></i>New Issue</h2>
            <a href="index.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left me-2"></i> Back to History
            </a>
        </div>
        
        <!-- Issue Form -->
        <div class="card shadow-sm mb-4">
            <div class="card-body">
                <form id="issueForm" method="POST" action="save.php">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="issue_date" class="form-label fw-bold">Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="issue_date" name="issue_date" 
                                       value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="department_id" class="form-label fw-bold">Department <span class="text-danger">*</span></label>
                                <select class="form-select" id="department_id" name="department_id" required>
                                    <option value="">Select Department</option>
                                    <?php while ($row = $departments->fetch_assoc()): ?>
                                        <option value="<?php echo $row['id']; ?>">
                                            <?php echo htmlspecialchars($row['name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="issued_to" class="form-label fw-bold">Issued To <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="issued_to" name="issued_to" 
                                       placeholder="Person name" required>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="remarks" class="form-label fw-bold">Remarks</label>
                                <input type="text" class="form-control" id="remarks" name="remarks" 
                                       placeholder="Optional">
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Item Selection -->
        <div class="card shadow-sm mb-4">
            <div class="card-header bg-white">
                <h5 class="mb-0"><i class="fas fa-cart-plus me-2 text-primary"></i>Add Items</h5>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-md-5">
                        <select class="form-select" id="itemSelect">
                            <option value="">-- Select Item --</option>
                            <?php while ($row = $items->fetch_assoc()): ?>
                                <option value="<?php echo $row['id']; ?>" 
                                        data-code="<?php echo htmlspecialchars($row['item_code']); ?>"
                                        data-name="<?php echo htmlspecialchars($row['item_name']); ?>"
                                        data-unit="<?php echo htmlspecialchars($row['unit']); ?>"
                                        data-stock="<?php echo $row['available_stock']; ?>"
                                        data-rate="<?php echo number_format($row['current_rate'], 2); ?>">
                                    <?php echo htmlspecialchars($row['item_code'] . ' - ' . $row['item_name']); ?>
                                    (Stock: <?php echo number_format($row['available_stock']); ?>, Rate: <?php echo number_format($row['current_rate'], 2); ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <input type="number" class="form-control" id="itemQuantity" placeholder="Qty" min="1">
                    </div>
                    <div class="col-md-3">
                        <span id="availableStockDisplay" class="form-control bg-light">Available: 0 | Rate: 0.00</span>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-primary w-100" id="addItemBtn">
                            <i class="fas fa-plus me-1"></i> Add
                        </button>
                    </div>
                </div>
                
                <!-- Items Grid -->
                <div class="table-responsive mt-3">
                    <table class="table table-bordered" id="issueItemsTable">
                        <thead class="table-light">
                            <tr>
                                <th>Item Code</th>
                                <th>Item Name</th>
                                <th>Unit</th>
                                <th>Rate</th>
                                <th>Available</th>
                                <th>Quantity</th>
                                <th>Total</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody id="issueItemsBody">
                            <tr id="noItemsRow">
                                <td colspan="8" class="text-center text-muted py-3">
                                    No items added yet. Select an item above.
                                </td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="7" class="text-end fw-bold">
                                    Total Items: <span id="totalItemsCount">0</span> | 
                                    Total Quantity: <span id="totalQuantityCount">0</span> |
                                    Total Value: <span id="totalValueCount">0.00</span>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
                
                <button type="button" class="btn btn-success mt-3" id="submitIssueBtn">
                    <i class="fas fa-check-circle me-2"></i> Submit Issue
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    let items = [];
    let itemCounter = 0;
    
    const itemSelect = document.getElementById('itemSelect');
    const itemQuantity = document.getElementById('itemQuantity');
    const availableStockDisplay = document.getElementById('availableStockDisplay');
    const addBtn = document.getElementById('addItemBtn');
    const submitBtn = document.getElementById('submitIssueBtn');
    const tbody = document.getElementById('issueItemsBody');
    const noItemsRow = document.getElementById('noItemsRow');
    const totalItemsSpan = document.getElementById('totalItemsCount');
    const totalQuantitySpan = document.getElementById('totalQuantityCount');
    const totalValueSpan = document.getElementById('totalValueCount');
    
    // Update available stock display
    itemSelect.addEventListener('change', function() {
        const selected = this.options[this.selectedIndex];
        const stock = selected.dataset.stock || 0;
        const rate = selected.dataset.rate || '0.00';
        availableStockDisplay.textContent = 'Available: ' + stock + ' | Rate: ' + rate;
        itemQuantity.value = '';
        itemQuantity.focus();
    });
    
    // Auto-select on enter in quantity field
    itemQuantity.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            addItem();
        }
    });
    
    // Add item function
    function addItem() {
        const selected = itemSelect.options[itemSelect.selectedIndex];
        const itemId = itemSelect.value;
        const quantity = parseInt(itemQuantity.value);
        const available = parseInt(selected.dataset.stock || 0);
        const rate = parseFloat(selected.dataset.rate || 0);
        
        if (!itemId) {
            alert('Please select an item.');
            return;
        }
        
        if (!quantity || quantity <= 0) {
            alert('Please enter a valid quantity.');
            return;
        }
        
        if (quantity > available) {
            alert('Insufficient stock. Available quantity is ' + available + '.');
            return;
        }
        
        // Check if item already added
        if (items.some(item => item.id === itemId)) {
            alert('Item already added to this issue.');
            return;
        }
        
        const total = quantity * rate;
        
        // Add to items array
        items.push({
            id: itemId,
            code: selected.dataset.code,
            name: selected.dataset.name,
            unit: selected.dataset.unit,
            available: available,
            quantity: quantity,
            rate: rate,
            total: total
        });
        
        // Update table
        renderItems();
        
        // Reset form
        itemSelect.value = '';
        itemQuantity.value = '';
        availableStockDisplay.textContent = 'Available: 0 | Rate: 0.00';
        itemSelect.focus();
    }
    
    addBtn.addEventListener('click', addItem);
    
    // Remove item
    function removeItem(index) {
        items.splice(index, 1);
        renderItems();
    }
    
    // Update quantity
    function updateQuantity(index, newQuantity) {
        const item = items[index];
        const newQty = parseInt(newQuantity);
        
        if (!newQty || newQty <= 0) {
            alert('Quantity must be greater than zero.');
            return;
        }
        
        if (newQty > item.available) {
            alert('Insufficient stock. Available quantity is ' + item.available + '.');
            return;
        }
        
        items[index].quantity = newQty;
        items[index].total = newQty * item.rate;
        renderItems();
    }
    
    // Render items table
    function renderItems() {
        if (items.length === 0) {
            tbody.innerHTML = `
                <tr id="noItemsRow">
                    <td colspan="8" class="text-center text-muted py-3">
                        No items added yet. Select an item above.
                    </td>
                </tr>
            `;
            totalItemsSpan.textContent = '0';
            totalQuantitySpan.textContent = '0';
            totalValueSpan.textContent = '0.00';
            return;
        }
        
        let html = '';
        let totalItems = 0;
        let totalQuantity = 0;
        let totalValue = 0;
        
        items.forEach((item, index) => {
            totalItems++;
            totalQuantity += item.quantity;
            totalValue += item.total;
            
            html += `
                <tr>
                    <td><span class="badge bg-secondary">${item.code}</span></td>
                    <td>${item.name}</td>
                    <td>${item.unit}</td>
                    <td>${item.rate.toFixed(2)}</td>
                    <td>${item.available}</td>
                    <td>
                        <input type="number" class="form-control form-control-sm" 
                               value="${item.quantity}" min="1" 
                               onchange="updateQuantity(${index}, this.value)"
                               style="width: 80px; display: inline-block;">
                    </td>
                    <td>${item.total.toFixed(2)}</td>
                    <td>
                        <button type="button" class="btn btn-sm btn-danger" onclick="removeItem(${index})">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                </tr>
            `;
        });
        
        tbody.innerHTML = html;
        totalItemsSpan.textContent = totalItems;
        totalQuantitySpan.textContent = totalQuantity;
        totalValueSpan.textContent = totalValue.toFixed(2);
    }
    
    // Make functions global for inline onclick
    window.removeItem = removeItem;
    window.updateQuantity = updateQuantity;
    
    // Submit issue
    submitBtn.addEventListener('click', function() {
        if (items.length === 0) {
            alert('Please add at least one item to the issue.');
            return;
        }
        
        const departmentId = document.getElementById('department_id').value;
        const issuedTo = document.getElementById('issued_to').value.trim();
        const issueDate = document.getElementById('issue_date').value;
        const remarks = document.getElementById('remarks').value.trim();
        
        if (!departmentId) {
            alert('Please select a department.');
            return;
        }
        
        if (!issuedTo) {
            alert('Please enter the person this is issued to.');
            return;
        }
        
        // Prepare form data
        const formData = new FormData();
        formData.append('issue_date', issueDate);
        formData.append('department_id', departmentId);
        formData.append('issued_to', issuedTo);
        formData.append('remarks', remarks);
        formData.append('items', JSON.stringify(items));
        
        // Submit via AJAX
        fetch('save.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                window.location.href = 'view.php?id=' + data.issue_id;
            } else {
                alert(data.message || 'Failed to save issue. Please try again.');
            }
        })
        .catch(error => {
            alert('An error occurred. Please try again.');
            console.error(error);
        });
    });
});
</script>

<?php include '../includes/footer.php'; ?>