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

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

<?php
$statusPill = static function (string $status): string {
    $label    = ucwords(str_replace('_', ' ', $status));
    $active   = ['issued', 'partially_paid', 'paid'];
    $inactive = ['cancelled'];
    if (in_array($status, $active, true)) {
        $class = 'active';
    } elseif (in_array($status, $inactive, true)) {
        $class = 'inactive';
    } else {
        $class = 'default';
    }
    return '<span class="enterprise-status-pill enterprise-status-pill--' . esc($class) . '">' . esc($label) . '</span>';
};

$invoiceStatuses = ['draft', 'issued', 'partially_paid', 'paid', 'overdue', 'cancelled'];
?>

<?= view('partials/workspace_hero', [
    'workspaceCrumbPill'    => 'Sales & CRM',
    'workspaceCrumbCurrent' => 'Invoices',
    'workspaceTitle'        => 'Invoices',
    'workspaceDesc'         => 'Create, issue, and track customer invoices.',
    'workspaceAction'       => [
        'href'  => base_url('sale/invoices/create'),
        'label' => 'New Invoice',
        'icon'  => 'fa-solid fa-plus',
    ],
]) ?>

<div class="enterprise-data-panel">
    <div class="enterprise-data-panel__head">
        <h2 class="enterprise-data-panel__title">Invoices</h2>
        <p class="enterprise-data-panel__subtitle">Draft through issue, payment, and cancellation.</p>
    </div>

    <div class="enterprise-data-panel__toolbar">
        <form action="<?= base_url('sale/invoices') ?>" 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, order"
                           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 ($invoiceStatuses 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>Order</th>
                        <th>Invoice Date</th>
                        <th>Due Date</th>
                        <th class="text-end">Total</th>
                        <th class="text-end">Paid</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($invoices as $inv): ?>
                        <?php
                        $st         = $inv['status'];
                        $canEdit    = $st === 'draft';
                        $canIssue   = $st === 'draft';
                        $canCancel  = ! in_array($st, ['paid', 'cancelled'], true);
                        $canDelete  = in_array($st, ['draft', 'cancelled'], true);
                        ?>
                        <tr>
                            <td><span class="enterprise-data-table__primary"><code><?= esc($inv['number']) ?></code></span></td>
                            <td><?= esc($inv['company_name'] ?? '—') ?></td>
                            <td><?= ! empty($inv['order_number']) ? '<code>' . esc($inv['order_number']) . '</code>' : '—' ?></td>
                            <td><?= esc($inv['invoice_date'] ?? '—') ?></td>
                            <td><?= ! empty($inv['due_date']) ? esc($inv['due_date']) : '—' ?></td>
                            <td class="text-end"><?= number_format((float) ($inv['total'] ?? 0), 2) ?></td>
                            <td class="text-end"><?= number_format((float) ($inv['amount_paid'] ?? 0), 2) ?></td>
                            <td><?= $statusPill($st) ?></td>
                            <td class="text-end enterprise-row-actions">
                                <?php if ($canEdit || $canIssue || $canCancel || $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/invoices/' . $inv['id'] . '/edit') ?>"><i class="fa-solid fa-pen me-2"></i>Edit</a></li>
                                            <?php endif; ?>
                                            <?php if ($canIssue): ?>
                                                <li>
                                                    <form action="<?= base_url('sale/invoices/' . $inv['id'] . '/issue') ?>" method="post">
                                                        <?= csrf_field() ?>
                                                        <button type="submit" class="dropdown-item"><i class="fa-solid fa-file-circle-check me-2"></i>Issue</button>
                                                    </form>
                                                </li>
                                            <?php endif; ?>
                                            <?php if ($canCancel): ?>
                                                <li>
                                                    <form action="<?= base_url('sale/invoices/' . $inv['id'] . '/cancel') ?>" method="post" onsubmit="return confirm('Cancel this invoice?');">
                                                        <?= csrf_field() ?>
                                                        <button type="submit" class="dropdown-item"><i class="fa-solid fa-ban me-2"></i>Cancel</button>
                                                    </form>
                                                </li>
                                            <?php endif; ?>
                                            <?php if ($canDelete): ?>
                                                <li><hr class="dropdown-divider"></li>
                                                <li>
                                                    <form action="<?= base_url('sale/invoices/' . $inv['id'] . '/delete') ?>" method="post" onsubmit="return confirm('Delete this invoice?');">
                                                        <?= 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($invoices) === 0): ?>
                        <tr><td colspan="9" class="text-center text-muted py-5">No invoices found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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