<?php
require_once 'includes/db.php';
$orders = fetchAll("SELECT o.*, b.name as buyer_name, pl.name as line_name FROM orders o LEFT JOIN buyers b ON o.buyer_id = b.id LEFT JOIN production_lines pl ON o.production_line_id = pl.id ORDER BY o.created_at DESC");
$buyers = fetchAll("SELECT * FROM buyers WHERE status = 'Active'");
$lines = fetchAll("SELECT * FROM production_lines WHERE status = 'Active'");

$stages = [
    'HANDOVER' => 'Handover Materials',
    'CUTTING' => 'Cutting',
    'SEWING' => 'Sewing',
    'QC' => 'QC',
    'PACKING' => 'Packing',
    'LOGISTIC' => 'Logistic',
    'REVIEW' => 'Final Review',
    'COMPLETED' => 'Completed'
];
?>

<div class="card">
    <div style="display: flex; justify-content: flex-end; align-items: center; margin-bottom: 2rem;">
        <button class="btn btn-primary" onclick="openAddOrderModal()">
            <i class="fas fa-plus"></i> Create New Order
        </button>
    </div>

    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Order No</th>
                    <th>Product</th>
                    <th>Buyer</th>
                    <th>Quantity</th>
                    <th>Current Stage</th>
                    <th>Deadline</th>
                    <th>Line</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): ?>
                <tr>
                    <td><strong style="color: var(--primary); font-family: monospace;"><?php echo $order['order_no']; ?></strong></td>
                    <td><?php echo $order['product_name']; ?></td>
                    <td><?php echo $order['buyer_name']; ?></td>
                    <td><?php echo number_format($order['qty']); ?></td>
                    <td>
                        <div style="display: flex; flex-direction: column; gap: 0.25rem;">
                            <span class="btn" style="padding: 0.25rem 0.75rem; font-size: 0.75rem; background: rgba(99, 102, 241, 0.1); color: var(--primary);">
                                <?php echo $stages[$order['current_stage']] ?? $order['current_stage']; ?>
                            </span>
                            <div style="height: 4px; background: rgba(255,255,255,0.1); border-radius: 2px; overflow: hidden;">
                                <div style="width: <?php echo $order['progress']; ?>%; height: 100%; background: var(--success);"></div>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div style="font-size: 0.875rem; color: <?php echo (strtotime($order['deadline']) < time() && $order['current_stage'] !== 'COMPLETED') ? 'var(--danger)' : 'inherit'; ?>;">
                            <i class="far fa-calendar-check" style="margin-right: 5px;"></i>
                            <?php echo date('M d, Y', strtotime($order['deadline'])); ?>
                        </div>
                    </td>
                    <td><?php echo $order['line_name'] ?: 'Not Assigned'; ?></td>
                    <td>
                        <div style="display: flex; gap: 0.5rem;">
                            <button class="btn" style="background: var(--glass-bg); padding: 0.5rem;" onclick='editOrder(<?php echo json_encode($order); ?>)'>
                                <i class="fas fa-edit"></i>
                            </button>
                            <button class="btn" style="background: rgba(239, 68, 68, 0.1); color: var(--danger); padding: 0.5rem;" onclick="deleteOrder(<?php echo $order['id']; ?>)">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Order Modal -->
<div id="orderModal" class="modal-overlay">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="modalTitle">Create New Order</h2>
            <button class="btn" style="background: none; color: var(--text-muted);" onclick="closeModal('orderModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form id="orderForm">
            <input type="hidden" id="order_id" name="id">
            <div class="modal-body">
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Order Number</label>
                        <input type="text" id="order_no" name="order_no" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Product Name</label>
                        <input type="text" id="order_product" name="product_name" class="form-control" placeholder="e.g. Slim Fit Chinos" required>
                    </div>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Buyer</label>
                        <select id="order_buyer" name="buyer_id" class="form-control" required>
                            <option value="">Select Buyer</option>
                            <?php foreach ($buyers as $b): ?>
                                <option value="<?php echo $b['id']; ?>"><?php echo $b['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Quantity</label>
                        <input type="number" id="order_qty" name="qty" class="form-control" required>
                    </div>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Current Stage</label>
                        <select id="order_stage" name="current_stage" class="form-control" required>
                            <?php foreach ($stages as $key => $val): ?>
                                <option value="<?php echo $key; ?>"><?php echo $val; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Progress (%)</label>
                        <input type="number" id="order_progress" name="progress" min="0" max="100" class="form-control" value="0">
                    </div>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Deadline</label>
                        <input type="date" id="order_deadline" name="deadline" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Production Line</label>
                        <select id="order_line" name="production_line_id" class="form-control">
                            <option value="">Not Assigned</option>
                            <?php foreach ($lines as $l): ?>
                                <option value="<?php echo $l['id']; ?>"><?php echo $l['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn" style="background: var(--glass-bg);" onclick="closeModal('orderModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">Save Order</button>
            </div>
        </form>
    </div>
</div>

<script>
function openAddOrderModal() {
    document.getElementById('modalTitle').innerText = 'Create New Order';
    document.getElementById('orderForm').reset();
    document.getElementById('order_id').value = '';
    document.getElementById('order_no').value = 'ORD-' + Date.now().toString().slice(-6);
    openModal('orderModal');
}

function editOrder(order) {
    document.getElementById('modalTitle').innerText = 'Edit Order';
    document.getElementById('order_id').value = order.id;
    document.getElementById('order_no').value = order.order_no;
    document.getElementById('order_product').value = order.product_name;
    document.getElementById('order_buyer').value = order.buyer_id;
    document.getElementById('order_qty').value = order.qty;
    document.getElementById('order_stage').value = order.current_stage;
    document.getElementById('order_progress').value = order.progress;
    document.getElementById('order_deadline').value = order.deadline;
    document.getElementById('order_line').value = order.production_line_id || '';
    openModal('orderModal');
}

document.getElementById('orderForm').onsubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const data = Object.fromEntries(formData.entries());
    
    const result = await apiCall('orders', { action: 'save', order: data });
    if (result.success) {
        notify(result.message);
        setTimeout(() => location.reload(), 1000);
    } else {
        notify(result.message, 'error');
    }
};

async function deleteOrder(id) {
    if (await confirmAction({ title: 'Delete Order', message: 'Are you sure you want to delete this order?' })) {
        const result = await apiCall('orders', { action: 'delete', id: id });
        if (result.success) {
            notify(result.message);
            setTimeout(() => location.reload(), 1000);
        } else {
            notify(result.message, 'error');
        }
    }
}
</script>
