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

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'create_order':
                $production_date = $_POST['production_date'];
                $remarks = $_POST['remarks'] ?? '';
                $created_by = $_SESSION['user_id'];
                
                $result = createProductionOrder($conn, $production_date, $remarks, $created_by);
                
                if ($result['success']) {
                    $_SESSION['success_message'] = 'Production order created successfully: ' . $result['order_number'];
                    header("Location: production_orders.php?view=" . $result['production_order_id']);
                    exit;
                } else {
                    $_SESSION['error_message'] = $result['error'];
                }
                break;
                
            case 'execute_production':
                $production_order_id = (int)$_POST['production_order_id'];
                
                $result = executeProduction($conn, $production_order_id);
                
                if ($result['success']) {
                    $_SESSION['success_message'] = $result['message'] . ' Total cost: Rs ' . number_format($result['total_cost'], 2);
                } else {
                    $_SESSION['error_message'] = $result['error'];
                }
                break;
        }
    }
}

// Get filter parameters
$status_filter = $_GET['status'] ?? '';
$view_order = $_GET['view'] ?? '';

// Get production orders
$orders = getProductionOrders($conn, $status_filter ?: null);

// Get specific order details if viewing
$order_details = null;
if ($view_order) {
    $order_details = getProductionOrderDetails($conn, $view_order);
}
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="page-title">
                <h4>Production Orders</h4>
                <h6>Manage production orders and manufacturing</h6>
            </div>
            <div class="page-btn">
                <a href="production_reports.php" class="btn btn-outline-info me-2">
                    <i class="fas fa-chart-bar me-2"></i>Reports
                </a>
                <button type="button" class="btn btn-added" data-bs-toggle="modal" data-bs-target="#createOrderModal">
                    <i class="fas fa-plus me-2"></i>Create Production Order
                </button>
            </div>
        </div>

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

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

                <!-- Filters -->
                <div class="row mb-3">
                    <div class="col-md-3">
                        <select class="form-select" onchange="filterByStatus(this.value)">
                            <option value="">All Status</option>
                            <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="in_progress" <?php echo $status_filter === 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                            <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="cancelled" <?php echo $status_filter === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                        </select>
                    </div>
                </div>

                <?php if ($view_order && $order_details): ?>
                    <!-- Order Details View -->
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">Production Order: <?php echo htmlspecialchars($order_details['order_number']); ?></h5>
                            <div>
                                <span class="badge bg-<?php echo $order_details['status'] === 'completed' ? 'success' : ($order_details['status'] === 'pending' ? 'warning' : 'info'); ?>">
                                    <?php echo ucfirst($order_details['status']); ?>
                                </span>
                                <?php if ($order_details['status'] === 'pending'): ?>
                                    <a href="add_production_item.php?order_id=<?php echo $order_details['id']; ?>" class="btn btn-primary btn-sm ms-2">
                                        <i class="fas fa-plus"></i> Add Item
                                    </a>
                                    <button type="button" class="btn btn-success btn-sm ms-2" onclick="executeProduction(<?php echo $order_details['id']; ?>)">
                                        <i class="fas fa-play"></i> Execute Production
                                    </button>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <strong>Production Date:</strong> <?php echo date('d M Y', strtotime($order_details['production_date'])); ?><br>
                                    <strong>Created By:</strong> <?php echo htmlspecialchars($order_details['created_by_name']); ?><br>
                                    <strong>Created At:</strong> <?php echo date('d M Y H:i', strtotime($order_details['created_at'])); ?>
                                </div>
                                <div class="col-md-6">
                                    <strong>Total Cost:</strong> Rs <?php echo number_format($order_details['total_cost'], 2); ?><br>
                                    <?php if ($order_details['remarks']): ?>
                                        <strong>Remarks:</strong> <?php echo htmlspecialchars($order_details['remarks']); ?>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <h6>Production Items</h6>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Item Code</th>
                                            <th>Item Name</th>
                                            <th>Quantity</th>
                                            <th>Unit Cost</th>
                                            <th>Total Cost</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($order_details['items'] as $item): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($item['item_code']); ?></td>
                                                <td><?php echo htmlspecialchars($item['item_name']); ?></td>
                                                <td><?php echo number_format($item['quantity'], 2); ?></td>
                                                <td>Rs <?php echo number_format($item['unit_cost'], 2); ?></td>
                                                <td>Rs <?php echo number_format($item['total_cost'], 2); ?></td>
                                                <td>
                                                    <span class="badge bg-<?php echo $item['status'] === 'completed' ? 'success' : 'warning'; ?>">
                                                        <?php echo ucfirst($item['status']); ?>
                                                    </span>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                            <div class="mt-3">
                                <a href="production_orders.php" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> Back to Orders
                                </a>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <!-- Orders List View -->
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>Order Number</th>
                                    <th>Production Date</th>
                                    <th>Status</th>
                                    <th>Items</th>
                                    <th>Total Cost</th>
                                    <th>Created By</th>
                                    <th>Created At</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($orders as $order): ?>
                                    <tr>
                                        <td>
                                            <a href="?view=<?php echo $order['id']; ?>" class="text-decoration-none">
                                                <?php echo htmlspecialchars($order['order_number']); ?>
                                            </a>
                                        </td>
                                        <td><?php echo date('d M Y', strtotime($order['production_date'])); ?></td>
                                        <td>
                                            <span class="badge bg-<?php echo $order['status'] === 'completed' ? 'success' : ($order['status'] === 'pending' ? 'warning' : 'info'); ?>">
                                                <?php echo ucfirst($order['status']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo $order['item_count']; ?></td>
                                        <td>Rs <?php echo number_format($order['total_cost'], 2); ?></td>
                                        <td><?php echo htmlspecialchars($order['created_by_name']); ?></td>
                                        <td><?php echo date('d M Y H:i', strtotime($order['created_at'])); ?></td>
                                        <td>
                                            <a href="?view=<?php echo $order['id']; ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>

    <!-- Create Order Modal -->
    <div class="modal fade" id="createOrderModal" tabindex="-1">
        <div class="modal-dialog">
            <form method="POST" class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Production Order</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="create_order">
                    
                    <div class="mb-3">
                        <label class="form-label">Production Date</label>
                        <input type="date" name="production_date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Remarks</label>
                        <textarea name="remarks" class="form-control" rows="3" placeholder="Optional remarks for this production order"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Order</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Execute Production Form -->
    <form id="executeProductionForm" method="POST" style="display: none;">
        <input type="hidden" name="action" value="execute_production">
        <input type="hidden" name="production_order_id" id="executeProductionOrderId">
    </form>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function filterByStatus(status) {
            const url = new URL(window.location);
            if (status) {
                url.searchParams.set('status', status);
            } else {
                url.searchParams.delete('status');
            }
            window.location.href = url.toString();
        }

        function executeProduction(orderId) {
            if (confirm('Are you sure you want to execute this production order? This will consume BOM materials and add finished products to inventory.')) {
                document.getElementById('executeProductionOrderId').value = orderId;
                document.getElementById('executeProductionForm').submit();
            }
        }
    </script>
    </div>
</div>
