<?php
ob_start();
include 'db.php';
include 'auth.php';
include 'handlers/production_handler.php';
include 'layout.php';

$production_order_id = (int)($_GET['order_id'] ?? 0);

if (!$production_order_id) {
    header("Location: production_orders.php");
    exit;
}

// Get production order details
$order_query = "SELECT * FROM production_orders WHERE id = ?";
$order_stmt = $conn->prepare($order_query);
$order_stmt->bind_param("i", $production_order_id);
$order_stmt->execute();
$order_result = $order_stmt->get_result();
$order = $order_result->fetch_assoc();
$order_stmt->close();

if (!$order || $order['status'] !== 'pending') {
    header("Location: production_orders.php");
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $item_id = (int)$_POST['item_id'];
    $quantity = (float)$_POST['quantity'];
    
    $result = addProductionItem($conn, $production_order_id, $item_id, $quantity);
    
    if ($result['success']) {
        $_SESSION['success_message'] = 'Production item added successfully';
        header("Location: production_orders.php?view=" . $production_order_id);
        exit;
    } else {
        $_SESSION['error_message'] = $result['error'];
    }
}

// Get items with BOM (for production)
$items_query = "
    SELECT DISTINCT i.id, i.item_code, i.name, i.cost_price
    FROM items i
    JOIN bom_master bm ON i.id = bm.item_id
    WHERE i.item_role IN ('stock', 'non_stock')
    ORDER BY i.name
";
$items_result = $conn->query($items_query);
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="page-title">
                <h4>Add Production Item</h4>
                <h6>Add items to production order</h6>
            </div>
            <div class="page-btn">
                <a href="production_orders.php?view=<?php echo $production_order_id; ?>" class="btn btn-secondary">
                    <i class="fas fa-arrow-left me-2"></i>Back to Order
                </a>
            </div>
        </div>

                <div class="alert alert-info">
                    <strong>Production Order:</strong> <?php echo htmlspecialchars($order['order_number']); ?><br>
                    <strong>Production Date:</strong> <?php echo date('d M Y', strtotime($order['production_date'])); ?>
                </div>

                <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Add Item to Production</h5>
                    </div>
                    <div class="card-body">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Select Item</label>
                                        <select name="item_id" class="form-select" required onchange="loadItemDetails(this.value)">
                                            <option value="">Select an item to produce</option>
                                            <?php while ($item = $items_result->fetch_assoc()): ?>
                                                <option value="<?php echo $item['id']; ?>" data-cost="<?php echo $item['cost_price']; ?>">
                                                    <?php echo htmlspecialchars($item['item_code'] . ' - ' . $item['name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Quantity to Produce</label>
                                        <input type="number" name="quantity" class="form-control" step="0.01" min="0.01" required onchange="calculateTotal()">
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Unit Cost (from BOM)</label>
                                        <input type="text" id="unitCost" class="form-control" readonly>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Total Cost</label>
                                        <input type="text" id="totalCost" class="form-control" readonly>
                                    </div>
                                </div>
                            </div>

                            <div id="bomDetails" class="mb-3" style="display: none;">
                                <h6>BOM Materials (will be consumed):</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm table-bordered">
                                        <thead>
                                            <tr>
                                                <th>Material</th>
                                                <th>Quantity per Unit</th>
                                                <th>Total Quantity</th>
                                                <th>Unit Cost</th>
                                                <th>Total Cost</th>
                                            </tr>
                                        </thead>
                                        <tbody id="bomTableBody">
                                        </tbody>
                                    </table>
                                </div>
                            </div>

                            <div class="d-flex justify-content-end">
                                <a href="production_orders.php?view=<?php echo $production_order_id; ?>" class="btn btn-secondary me-2">Cancel</a>
                                <button type="submit" class="btn btn-primary">Add to Production</button>
                            </div>
                        </form>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function loadItemDetails(itemId) {
            if (!itemId) {
                document.getElementById('unitCost').value = '';
                document.getElementById('totalCost').value = '';
                document.getElementById('bomDetails').style.display = 'none';
                return;
            }

            // Get selected option
            const selectedOption = document.querySelector(`option[value="${itemId}"]`);
            const unitCost = selectedOption.dataset.cost || 0;
            document.getElementById('unitCost').value = 'Rs ' + parseFloat(unitCost).toFixed(2);
            
            calculateTotal();
            loadBOMDetails(itemId);
        }

        function calculateTotal() {
            const quantity = parseFloat(document.querySelector('input[name="quantity"]').value) || 0;
            const unitCost = parseFloat(document.getElementById('unitCost').value.replace('Rs ', '')) || 0;
            const totalCost = quantity * unitCost;
            document.getElementById('totalCost').value = 'Rs ' + totalCost.toFixed(2);
        }

        function loadBOMDetails(itemId) {
            fetch(`ajax/fetch_bom_detailed.php?item_id=${itemId}`)
                .then(response => response.json())
                .then(data => {
                    const bomTableBody = document.getElementById('bomTableBody');
                    const bomDetails = document.getElementById('bomDetails');
                    
                    if (data.length === 0) {
                        bomDetails.style.display = 'none';
                        return;
                    }

                    bomTableBody.innerHTML = '';
                    
                    data.forEach(bom => {
                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td>${bom.material_name || 'Loading...'}</td>
                            <td>${parseFloat(bom.quantity).toFixed(2)}</td>
                            <td id="total-qty-${bom.component_item_id}">0.00</td>
                            <td>Rs ${parseFloat(bom.unit_cost || 0).toFixed(2)}</td>
                            <td id="total-cost-${bom.component_item_id}">Rs 0.00</td>
                        `;
                        bomTableBody.appendChild(row);
                    });

                    bomDetails.style.display = 'block';
                    updateBOMTotals();
                })
                .catch(error => {
                    console.error('Error loading BOM details:', error);
                    document.getElementById('bomDetails').style.display = 'none';
                });
        }

        function updateBOMTotals() {
            const quantity = parseFloat(document.querySelector('input[name="quantity"]').value) || 0;
            
            // Update BOM totals based on quantity
            fetch(`ajax/fetch_bom_detailed.php?item_id=${document.querySelector('select[name="item_id"]').value}`)
                .then(response => response.json())
                .then(data => {
                    data.forEach(bom => {
                        const totalQty = quantity * parseFloat(bom.quantity);
                        const totalCost = totalQty * parseFloat(bom.unit_cost || 0);
                        
                        const totalQtyElement = document.getElementById(`total-qty-${bom.component_item_id}`);
                        const totalCostElement = document.getElementById(`total-cost-${bom.component_item_id}`);
                        
                        if (totalQtyElement) totalQtyElement.textContent = totalQty.toFixed(2);
                        if (totalCostElement) totalCostElement.textContent = 'Rs ' + totalCost.toFixed(2);
                    });
                });
        }

        // Update BOM totals when quantity changes
        document.querySelector('input[name="quantity"]').addEventListener('input', updateBOMTotals);
    </script>
    </div>
</div>
