<?php
/**
 * @var object $order
 * @var array $items
 * @var object|null $grn
 * @var bool $isGrn
 */
?>
<div class="page-title mb-4">
    <h5><i class="fas fa-<?= !empty($isGrn) ? 'clipboard-check' : 'file-invoice' ?> me-2 text-gold"></i>
        <?= !empty($isGrn) ? 'GRN - ' . e($order->grn_number) : 'PO - ' . e($order->order_number) ?></h5>
</div>

<?php if (!empty($isGrn)): ?>
<div class="row g-4">
    <div class="col-lg-8">
        <div class="glass-card p-0">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-clipboard-list card-icon"></i>
                    <h6 class="card-title">GRN Items</h6>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Product</th>
                                <th>SKU</th>
                                <th class="text-center">Ordered</th>
                                <th class="text-center">Received</th>
                                <th class="text-end">Unit Cost</th>
                                <th class="text-end">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; ?>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?= $i++ ?></td>
                                    <td><?= e($item->product_name ?? '-') ?></td>
                                    <td><code><?= e($item->sku ?? '-') ?></code></td>
                                    <td class="text-center"><?= (int)$item->quantity_ordered ?></td>
                                    <td class="text-center"><?= (int)$item->quantity_received ?></td>
                                    <td class="text-end"><?= currency($item->unit_cost ?? 0) ?></td>
                                    <td class="text-end"><?= currency(($item->quantity_received ?? 0) * ($item->unit_cost ?? 0)) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="glass-card p-0">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-info-circle card-icon"></i>
                    <h6 class="card-title">GRN Details</h6>
                </div>
            </div>
            <div class="card-body">
                <table class="table table-sm table-borderless mb-0">
                    <tr>
                        <td class="text-muted">GRN Number:</td>
                        <td><strong><?= e($order->grn_number) ?></strong></td>
                    </tr>
                    <tr>
                        <td class="text-muted">PO Reference:</td>
                        <td><a href="<?= url('purchases/show/' . $order->purchase_order_id) ?>" class="text-gold"><?= e($order->order_number) ?></a></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Supplier:</td>
                        <td><strong><?= e($order->supplier_name ?? '-') ?></strong></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Received Date:</td>
                        <td><?= formatDate($order->received_date ?? $order->created_at) ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Received By:</td>
                        <td><?= e($order->user_first_name ?? '') ?> <?= e($order->user_last_name ?? '') ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Status:</td>
                        <td>
                            <span class="badge bg-<?= statusBadge($order->status) ?>">
                                <?= e(ucfirst($order->status)) ?>
                            </span>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
</div>
<?php else: ?>

<div class="row g-4">
    <div class="col-lg-8">
        <div class="glass-card p-0">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-list card-icon"></i>
                    <h6 class="card-title">Order Items</h6>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Product</th>
                                <th>SKU</th>
                                <th class="text-center">Quantity</th>
                                <th class="text-end">Unit Cost</th>
                                <th class="text-end">Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $i = 1; $total = 0; ?>
                            <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?= $i++ ?></td>
                                    <td><?= e($item->product_name ?? '-') ?></td>
                                    <td><code><?= e($item->sku ?? '-') ?></code></td>
                                    <td class="text-center"><?= (int)$item->quantity ?></td>
                                    <td class="text-end"><?= currency($item->unit_cost ?? 0) ?></td>
                                    <td class="text-end"><?= currency($item->total_cost ?? 0) ?></td>
                                </tr>
                                <?php $total += (float)($item->total_cost ?? 0); ?>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="table-active">
                                <td colspan="5" class="text-end"><strong>Grand Total:</strong></td>
                                <td class="text-end"><strong><?= currency($total) ?></strong></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="glass-card p-0">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-info-circle card-icon"></i>
                    <h6 class="card-title">Order Details</h6>
                </div>
            </div>
            <div class="card-body">
                <table class="table table-sm table-borderless mb-0">
                    <tr>
                        <td class="text-muted">Order Number:</td>
                        <td><strong><?= e($order->order_number) ?></strong></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Supplier:</td>
                        <td><strong><?= e($order->supplier_name ?? '-') ?></strong></td>
                    </tr>
                    <?php if (!empty($order->contact_person)): ?>
                    <tr>
                        <td class="text-muted">Contact:</td>
                        <td><?= e($order->contact_person) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if (!empty($order->supplier_email)): ?>
                    <tr>
                        <td class="text-muted">Email:</td>
                        <td><?= e($order->supplier_email) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if (!empty($order->supplier_phone)): ?>
                    <tr>
                        <td class="text-muted">Phone:</td>
                        <td><?= e($order->supplier_phone) ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr>
                        <td class="text-muted">Order Date:</td>
                        <td><?= formatDate($order->order_date ?? $order->created_at) ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Expected Date:</td>
                        <td><?= !empty($order->expected_date) ? formatDate($order->expected_date) : '-' ?></td>
                    </tr>
                    <tr>
                        <td class="text-muted">Status:</td>
                        <td>
                            <span class="badge bg-<?= statusBadge($order->status) ?>">
                                <?= e(ucfirst($order->status)) ?>
                            </span>
                        </td>
                    </tr>
                    <tr>
                        <td class="text-muted">Created By:</td>
                        <td><?= e($order->user_first_name ?? '') ?> <?= e($order->user_last_name ?? '') ?></td>
                    </tr>
                </table>

                <?php if (!empty($order->notes)): ?>
                <div class="mt-3">
                    <label class="text-muted small">Notes:</label>
                    <p class="mb-0 small"><?= nl2br(e($order->notes)) ?></p>
                </div>
                <?php endif; ?>

                <?php if (!empty($order->supplier_address)): ?>
                <div class="mt-3">
                    <label class="text-muted small">Supplier Address:</label>
                    <p class="mb-0 small"><?= nl2br(e($order->supplier_address)) ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="glass-card p-0 mt-4">
            <div class="card-header">
                <div class="card-header-left">
                    <i class="fas fa-cog card-icon"></i>
                    <h6 class="card-title">Actions</h6>
                </div>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <?php if ($order->status === 'draft' && can('purchases_approve')): ?>
                        <button type="button" class="btn btn-success" onclick="confirmAction('approve')">
                            <i class="fas fa-check-circle me-1"></i>Approve Order
                        </button>
                    <?php endif; ?>
                    <?php if ($order->status === 'approved' && can('purchases_receive')): ?>
                        <button type="button" class="btn btn-info text-white" data-bs-toggle="modal" data-bs-target="#receiveModal">
                            <i class="fas fa-download me-1"></i>Receive Goods
                        </button>
                    <?php endif; ?>
                    <?php if (!empty($grn)): ?>
                        <a href="<?= url('purchases/grn/' . $grn->id) ?>" class="btn btn-outline-gold">
                            <i class="fas fa-clipboard-list me-1"></i>View GRN
                        </a>
                    <?php endif; ?>
                    <a href="<?= url('purchases') ?>" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i>Back to List
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Receive Goods Modal -->
<div class="modal fade" id="receiveModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content bg-dark border-gold">
            <form method="POST" action="<?= url('purchases/receive/' . $order->id) ?>">
                <input type="hidden" name="_csrf_token" value="<?= csrf_token() ?>">
                <div class="modal-header border-gold">
                    <h6 class="modal-title text-gold">Receive Goods - Batch Details</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p class="text-muted small mb-3">Enter batch number and expiry date for each product. Leave batch number blank if not tracking batches.</p>
                    <div class="table-responsive">
                        <table class="table table-dark table-hover mb-0">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th>Qty</th>
                                    <th>Batch #</th>
                                    <th>Expiry Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?= e($item->product_name ?? '-') ?></td>
                                    <td><?= (int)$item->quantity ?></td>
                                    <td>
                                        <input type="hidden" name="items[<?= $item->product_id ?>][product_id]" value="<?= $item->product_id ?>">
                                        <input type="hidden" name="items[<?= $item->product_id ?>][quantity]" value="<?= (int)$item->quantity ?>">
                                        <input type="text" name="items[<?= $item->product_id ?>][batch_number]" class="form-control form-control-sm batch-input" placeholder="e.g. LOT-A1" data-product="<?= $item->product_id ?>">
                                    </td>
                                    <td>
                                        <input type="date" name="items[<?= $item->product_id ?>][expiry_date]" class="form-control form-control-sm expiry-input" data-product="<?= $item->product_id ?>">
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer border-gold">
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-sm btn-info text-white">Receive Goods</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php endif; ?>
<?php $id = (int)($order->id ?? 0); ?>
<?php $approveUrl = url("purchases/approve/$id"); ?>
<?php $receiveUrl = url("purchases/receive/$id"); ?>
<?php $csrfTok = csrf_token(); ?>
<?php $inlineScripts = <<<EOS
window.confirmAction = function(action) {
    if (!confirm('Are you sure you want to ' + action + ' this purchase order?')) return;
    var f = document.createElement('form');
    f.method = 'POST';
    f.action = action === 'approve' ? '$approveUrl' : '$receiveUrl';
    var inp = document.createElement('input');
    inp.type = 'hidden';
    inp.name = '_csrf_token';
    inp.value = '$csrfTok';
    f.appendChild(inp);
    document.body.appendChild(f);
    f.submit();
};

document.querySelectorAll('.batch-input, .expiry-input').forEach(function(el) {
    el.addEventListener('input', function() {
        var product = this.dataset.product;
        var batchInput = document.querySelector('.batch-input[data-product="' + product + '"]');
        var expiryInput = document.querySelector('.expiry-input[data-product="' + product + '"]');
        if (batchInput.value.trim() !== '' || expiryInput.value !== '') {
            batchInput.required = true;
            expiryInput.required = true;
        } else {
            batchInput.required = false;
            expiryInput.required = false;
        }
    });
});
EOS;
?>
