<?= $this->extend('layouts/enterprise') ?>

<?= $this->section('content') ?>

<?php
$statusPill = static function (string $status): string {
    $label = ucwords(str_replace('_', ' ', $status));
    $active = ['approved', 'confirmed', 'fulfilled', 'delivered', 'dispatched', 'in_transit', 'sent', 'converted'];
    $inactive = ['cancelled', 'rejected'];
    $mod = '';
    if (in_array($status, $active, true)) {
        $mod = ' enterprise-status-pill--active';
    } elseif (in_array($status, $inactive, true)) {
        $mod = ' enterprise-status-pill--inactive';
    }

    return '<span class="enterprise-status-pill' . $mod . '">' . esc($label) . '</span>';
};

$orderStatuses = ['draft', 'pending_approval', 'approved', 'rejected', 'confirmed', 'in_progress', 'fulfilled', 'cancelled'];
?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Sales & CRM',
    'workspaceCrumbCurrent' => 'Orders',
    'workspaceTitle'        => 'Order Management',
    'workspaceDesc'         => 'Create and manage sales orders from confirmed quotations.',
    'workspaceAction'       => [
        'href'  => base_url('sale/orders/create'),
        'label' => 'New Order',
        'icon'  => 'fa-solid fa-plus',
    ],
]) ?>

<div class="enterprise-data-panel">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Sales Orders</h2>
        <p class="enterprise-data-panel__subtitle">Draft, submit, and track customer sales orders.</p>
    </div>

    <div class="enterprise-data-panel__toolbar">
        <form action="<?= base_url('sale/orders') ?>" method="get">
            <div class="enterprise-filter-grid">
                <div>
                    <label class="enterprise-field-label">Search</label>
                    <input type="text" name="q" class="form-control form-control-sm" placeholder="Number, company, quotation"
                           value="<?= esc($filters['search'] ?? '') ?>">
                </div>
                <div>
                    <label class="enterprise-field-label">Status</label>
                    <select name="status" class="form-select form-select-sm">
                        <option value="">Any</option>
                        <?php foreach ($orderStatuses as $s): ?>
                            <option value="<?= $s ?>" <?= ($filters['status'] ?? '') === $s ? 'selected' : '' ?>>
                                <?= esc(ucwords(str_replace('_', ' ', $s))) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="enterprise-field-label">Company</label>
                    <select name="company_id" class="form-select form-select-sm">
                        <option value="">Any</option>
                        <?php foreach ($companies as $c): ?>
                            <option value="<?= $c['id'] ?>" <?= (string) ($filters['companyId'] ?? '') === (string) $c['id'] ? 'selected' : '' ?>>
                                <?= esc($c['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="enterprise-filter-actions">
                    <button type="submit" class="btn btn-sm btn-primary">Apply Filters</button>
                </div>
            </div>
        </form>
    </div>

    <div class="enterprise-data-panel__body">
        <div class="table-responsive">
            <table class="enterprise-data-table">
                <thead>
                    <tr>
                        <th>Number</th>
                        <th>Company</th>
                        <th>Quotation</th>
                        <th>Order Date</th>
                        <th>Status</th>
                        <th class="text-end">Total</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($orders as $o): ?>
                        <?php
                        $canEdit   = in_array($o['status'], ['draft', 'rejected'], true);
                        $canSubmit = in_array($o['status'], ['draft', 'rejected'], true);
                        $canDelete = in_array($o['status'], ['draft', 'rejected', 'cancelled'], true);
                        ?>
                        <tr>
                            <td><span class="enterprise-data-table__primary"><code><?= esc($o['number']) ?></code></span></td>
                            <td><?= esc($o['company_name'] ?? '—') ?></td>
                            <td><?= ! empty($o['quotation_number']) ? '<code>' . esc($o['quotation_number']) . '</code>' : '—' ?></td>
                            <td><?= esc($o['order_date']) ?></td>
                            <td><?= $statusPill($o['status']) ?></td>
                            <td class="text-end"><?= number_format((float) ($o['total'] ?? 0), 2) ?></td>
                            <td class="text-end enterprise-row-actions">
                                <?php if ($canEdit || $canSubmit || $canDelete): ?>
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-outline-secondary" data-bs-toggle="dropdown"><i class="fa-solid fa-ellipsis"></i></button>
                                        <ul class="dropdown-menu dropdown-menu-end enterprise-nav-menu">
                                            <?php if ($canEdit): ?>
                                                <li><a class="dropdown-item" href="<?= base_url('sale/orders/' . $o['id'] . '/edit') ?>"><i class="fa-solid fa-pen me-2"></i>Edit</a></li>
                                            <?php endif; ?>
                                            <?php if ($canSubmit): ?>
                                                <li>
                                                    <form action="<?= base_url('sale/orders/' . $o['id'] . '/submit') ?>" method="post">
                                                        <?= csrf_field() ?>
                                                        <button type="submit" class="dropdown-item"><i class="fa-solid fa-paper-plane me-2"></i>Submit for Approval</button>
                                                    </form>
                                                </li>
                                            <?php endif; ?>
                                            <?php if ($canDelete): ?>
                                                <li><hr class="dropdown-divider"></li>
                                                <li>
                                                    <form action="<?= base_url('sale/orders/' . $o['id'] . '/delete') ?>" method="post" onsubmit="return confirm('Delete this sales order?');">
                                                        <?= csrf_field() ?>
                                                        <button type="submit" class="dropdown-item text-danger"><i class="fa-solid fa-trash me-2"></i>Delete</button>
                                                    </form>
                                                </li>
                                            <?php endif; ?>
                                        </ul>
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted small">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    <?php if (count($orders) === 0): ?>
                        <tr><td colspan="7" class="text-center text-muted py-5">No sales orders found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?= $this->endSection() ?>
