<?php $__env->startSection('title', 'Purchase ' . $purchase->invoice_number); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">

    <div class="page-title-head d-flex align-items-center">
        <div class="flex-grow-1">
            <h4 class="page-main-title m-0">
                Purchase
                <span class="badge bg-soft-primary text-primary ms-2"><?php echo e($purchase->invoice_number); ?></span>
                <span class="badge <?php echo e($purchase->statusBadgeClass()); ?> ms-1"><?php echo e($purchase->statusLabel()); ?></span>
                <span class="badge <?php echo e($purchase->paymentStatusBadgeClass()); ?> ms-1"><?php echo e($purchase->paymentStatusLabel()); ?></span>
            </h4>
        </div>
        <div class="text-end d-flex gap-1 align-items-center">
            <?php if (\Illuminate\Support\Facades\Blade::check('permission', 'purchases.edit')): ?>
                <?php if(! $editBlockReason): ?>
                    <a href="<?php echo e(route('purchases.edit', $purchase)); ?>" class="btn btn-soft-primary btn-sm">
                        <i class="ti ti-edit me-1"></i> Edit
                    </a>
                <?php endif; ?>
            <?php endif; ?>

            <?php if (\Illuminate\Support\Facades\Blade::check('permission', 'purchases.post')): ?>
                <?php if($purchase->isDraft()): ?>
                    <button type="button" class="btn btn-soft-success btn-sm" id="postBtn" data-id="<?php echo e($purchase->id); ?>">
                        <i class="ti ti-check me-1"></i> Post
                    </button>
                <?php endif; ?>
            <?php endif; ?>

            <a href="<?php echo e(route('purchases.index')); ?>" class="btn btn-light btn-sm">
                <i class="ti ti-arrow-left me-1"></i> Back
            </a>
        </div>
    </div>

    <?php if(session('success')): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo e(session('success')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if(session('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo e(session('error')); ?>

            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (\Illuminate\Support\Facades\Blade::check('permission', 'purchases.edit')): ?>
        <?php if($editBlockReason && ! $purchase->isCancelled()): ?>
            <div class="alert alert-warning d-flex align-items-center gap-2" role="alert">
                <i class="ti ti-lock fs-lg"></i>
                <div><strong>Editing locked:</strong> <?php echo e($editBlockReason); ?></div>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <div class="row g-3">

        
        <div class="col-xl-10">
            <div class="card">
                <div class="card-body">

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <h6 class="text-muted text-uppercase fs-xxs mb-1">Supplier</h6>
                            <strong><?php echo e($purchase->supplier?->company_name ?: $purchase->supplier?->name); ?></strong><br>
                            <small class="text-muted"><?php echo e($purchase->supplier?->supplier_code); ?></small>
                            <?php if($purchase->supplier?->gst_number): ?>
                                <br><small class="text-muted">GST: <?php echo e($purchase->supplier->gst_number); ?></small>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-3">
                            <h6 class="text-muted text-uppercase fs-xxs mb-1">Location</h6>
                            <?php if($purchase->location): ?>
                                <strong><?php echo e($purchase->location->name); ?></strong><br>
                                <small class="text-muted"><?php echo e($purchase->location->location_code); ?></small>
                                <br><small class="text-muted"><?php echo e($purchase->location->typeLabel()); ?></small>
                            <?php else: ?>
                                <span class="text-muted">&mdash;</span>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-3 text-md-end">
                            <h6 class="text-muted text-uppercase fs-xxs mb-1">Purchase Date</h6>
                            <strong><?php echo e($purchase->purchase_date?->format('d M Y')); ?></strong><br>
                            <small class="text-muted">Tax: <?php echo e(strtoupper($purchase->tax_type)); ?></small>
                        </div>
                    </div>

                    <div class="d-flex justify-content-end align-items-center gap-2 mb-2">
                        <span class="text-muted small" id="labelSelectedCount">0 selected</span>
                        <button type="button" class="btn btn-soft-primary btn-sm" id="printLabelsBtn" disabled>
                            <i class="ti ti-tag me-1"></i> Print Labels
                        </button>
                    </div>
                    <form id="printLabelsForm" method="GET" action="<?php echo e(route('purchases.print-labels', $purchase)); ?>" target="_blank" class="d-none"></form>

                    <div class="table-responsive">
                        <table class="table table-bordered align-middle mb-0">
                            <thead class="bg-light bg-opacity-25 text-uppercase fs-xxs">
                                <tr>
                                    <th style="width:36px;">
                                        <input type="checkbox" class="form-check-input" id="labelSelectAll" title="Select all">
                                    </th>
                                    <th>#</th>
                                    <th>Product</th>
                                    <th>Country of Origin</th>
                                    <th>Pcs</th>
                                    <th class="text-end">Carat</th>
                                    <th>Barcode</th>
                                    <th>Lot Code</th>
                                    
                                    <th class="text-end">Price</th>
                                    <th class="text-end">Selling Price</th>
                                    
                                    <th class="text-end">Net</th>
                                    <th style="width:90px;">Copies</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php $__currentLoopData = $purchase->lines; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $i => $line): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    
                                    <tr class="table-light">
                                        <td></td>
                                        <td class="fw-semibold"><?php echo e($i + 1); ?></td>
                                        <td>
                                            <div class="d-flex align-items-center gap-2">
                                                <div>
                                                    <div class="fw-semibold"><?php echo e($line->title ?? $line->product?->title); ?></div>
                                                    <small class="text-muted"><?php echo e($line->category?->name ?? ('SKU: ' . $line->product?->sku)); ?></small>
                                                </div>
                                                <i class="ti fs-16 <?php echo e($line->website_enabled ? 'ti-world text-info' : 'ti-world-off text-muted'); ?>"
                                                   title="<?php echo e($line->website_enabled ? 'Website hint: On (default when this stock is packed)' : 'Website hint: Off (default when this stock is packed)'); ?>"></i>
                                            </div>
                                        </td>
                                        <td class="small"><?php echo e($line->countryOfOrigin?->name ?? '—'); ?></td>
                                        <td colspan="6"></td>
                                        <td class="text-end fw-bold"><?php echo e(number_format((float) $line->total, 2)); ?></td>
                                        <td></td>
                                    </tr>

                                    
                                    <?php $__currentLoopData = $line->rows; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $ri => $row): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <tr>
                                            <td class="text-center">
                                                <input type="checkbox" class="form-check-input js-label-row" value="<?php echo e($row->id); ?>">
                                            </td>
                                            <td></td>
                                            <td class="ps-4 text-muted small">
                                                <i class="ti ti-corner-down-right me-1"></i>
                                                Pcs #<?php echo e($ri + 1); ?>

                                                <?php if($row->product): ?>
                                                    <br><code class="fs-xxs"><?php echo e($row->product->sku); ?></code>
                                                <?php endif; ?>
                                            </td>
                                            <td></td>
                                            <td><?php echo e($row->qty); ?></td>
                                            <td class="text-end small"><?php echo e($row->carat_weight !== null ? rtrim(rtrim(number_format((float) $row->carat_weight, 3), '0'), '.') : '—'); ?></td>
                                            <td><code class="small"><?php echo e($row->barcode ?: '—'); ?></code></td>
                                            <td><code class="small"><?php echo e($row->lot_code ?: '—'); ?></code></td>
                                            
                                            <td class="text-end"><?php echo e(number_format((float) $row->price, 2)); ?></td>
                                            <td class="text-end"><?php echo e($row->website_price !== null ? number_format((float) $row->website_price, 2) : '—'); ?></td>
                                            
                                            <td class="text-end"><?php echo e(number_format($row->net(), 2)); ?></td>
                                            <td>
                                                <input type="number" class="form-control form-control-sm js-label-copies" value="1" min="1" max="100" style="width:70px;">
                                            </td>
                                        </tr>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if($purchase->note): ?>
                        <div class="alert alert-info mt-3 mb-0">
                            <strong>Notes:</strong> <?php echo e($purchase->note); ?>

                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        
        <div class="col-xl-2">
            <div class="card position-sticky" style="top: 1rem;">
                <div class="card-header border-light">
                    <h5 class="card-title mb-0">Summary</h5>
                </div>
                <div class="card-body">

                    <div class="mb-3 pb-3 border-bottom">
                        <div class="text-muted fs-xxs text-uppercase mb-1">Location</div>
                        <?php if($purchase->location): ?>
                            <div class="fw-semibold"><?php echo e($purchase->location->name); ?></div>
                            <div class="text-muted small"><?php echo e($purchase->location->location_code); ?> &middot; <?php echo e($purchase->location->typeLabel()); ?></div>
                        <?php else: ?>
                            <span class="text-muted">&mdash;</span>
                        <?php endif; ?>
                    </div>

                    <div class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Subtotal</span>
                        <span><?php echo e(app(\App\Services\SettingService::class)->formatMoney($purchase->subtotal)); ?></span>
                    </div>
                    

                    <hr class="my-2">

                    <div class="d-flex justify-content-between mb-3">
                        <span class="fw-semibold">Grand Total</span>
                        <span class="fw-bold fs-18 text-primary"><?php echo e(app(\App\Services\SettingService::class)->formatMoney($purchase->grand_total)); ?></span>
                    </div>

                    <div class="d-flex justify-content-between mb-2 small">
                        <span class="text-muted">Paid</span>
                        <span><?php echo e(app(\App\Services\SettingService::class)->formatMoney($purchase->paid_amount)); ?></span>
                    </div>
                    <div class="d-flex justify-content-between mb-3 small">
                        <span class="text-muted">Due</span>
                        <span class="fw-semibold <?php echo e($purchase->due_amount > 0 ? 'text-warning' : 'text-success'); ?>">
                            <?php echo e(app(\App\Services\SettingService::class)->formatMoney($purchase->due_amount)); ?>

                        </span>
                    </div>

                </div>
            </div>

            
            <div class="card">
                <div class="card-header border-light"><h5 class="card-title mb-0">Payments</h5></div>
                <div class="card-body p-0">
                    <?php if($purchase->payments->isEmpty()): ?>
                        <p class="text-muted small text-center py-3 mb-0">No payments recorded.</p>
                    <?php else: ?>
                        <ul class="list-group list-group-flush">
                            <?php $__currentLoopData = $purchase->payments; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $p): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <li class="list-group-item px-3 py-2">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <span class="badge <?php echo e($p->methodBadgeClass()); ?> fs-xxs"><?php echo e($p->methodLabel()); ?></span>
                                        <?php if (\Illuminate\Support\Facades\Blade::check('permission', 'purchases.edit')): ?>
                                        <?php if(! $purchase->isCancelled()): ?>
                                            <button type="button" class="btn btn-default btn-icon btn-sm text-danger js-remove-payment"
                                                data-url="<?php echo e(route('purchases.payments.destroy', [$purchase, $p])); ?>"
                                                title="Remove">
                                                <i class="ti ti-x"></i>
                                            </button>
                                        <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                    <div class="fw-semibold <?php echo e($p->isRefund() ? 'text-danger' : ''); ?> mt-1">
                                        <?php echo e($p->isRefund() ? '−' : ''); ?><?php echo e(number_format(abs((float) $p->amount), 2)); ?>

                                    </div>
                                    <small class="d-block text-muted">
                                        <?php echo e(optional($p->payment_date)->format('d M Y')); ?>

                                        <?php if($p->reference_number): ?> <br>Ref: <?php echo e($p->reference_number); ?> <?php endif; ?>
                                    </small>
                                </li>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </ul>
                    <?php endif; ?>
                </div>

                <?php if (\Illuminate\Support\Facades\Blade::check('permission', 'purchases.edit')): ?>
                <?php if($purchase->isPosted()): ?>
                <div class="card-footer border-top">
                    <h6 class="text-muted text-uppercase small mb-2">Add Payment</h6>
                    <form id="addPaymentForm">
                        <select class="form-select form-select-sm mb-1" id="paymentMethod">
                            <?php $__currentLoopData = $paymentMethods; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($key); ?>"><?php echo e($label); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <input type="number" step="0.01" class="form-control form-control-sm mb-1 text-end"
                            id="paymentAmount" placeholder="Amount"
                            value="<?php echo e(number_format((float) $purchase->due_amount, 2, '.', '')); ?>" required>
                        <input type="date" class="form-control form-control-sm mb-1" id="paymentDate"
                            value="<?php echo e(now()->toDateString()); ?>" required>
                        <input type="text" class="form-control form-control-sm mb-2" id="paymentReference"
                            placeholder="Reference (optional)">
                        <button type="submit" class="btn btn-primary btn-sm w-100" id="paymentSubmitBtn">
                            Save
                        </button>
                        <div id="paymentError" class="alert alert-danger mt-2 mb-0 py-2 small d-none"></div>
                    </form>
                </div>
                <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<script>
(function () {
    const csrf = document.querySelector('meta[name="csrf-token"]').content;

    const postBtn = document.getElementById('postBtn');
    if (postBtn) {
        postBtn.addEventListener('click', function () {
            if (!confirm('Post this purchase?')) return;
            fetch(`/purchases/${postBtn.dataset.id}/post`, {
                method: 'PATCH',
                headers: { 'X-CSRF-TOKEN': csrf, 'Accept': 'application/json' },
            }).then(r => r.json()).then(() => window.location.reload());
        });
    }

    // Payments: add + remove
    const addPaymentForm = document.getElementById('addPaymentForm');
    if (addPaymentForm) {
        addPaymentForm.addEventListener('submit', function (e) {
            e.preventDefault();
            const btn    = document.getElementById('paymentSubmitBtn');
            const errBox = document.getElementById('paymentError');
            errBox.classList.add('d-none');
            btn.disabled = true;

            fetch('<?php echo e(route('purchases.payments.store', $purchase)); ?>', {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': csrf,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    payment_date:     document.getElementById('paymentDate').value,
                    amount:           Number(document.getElementById('paymentAmount').value),
                    payment_method:   document.getElementById('paymentMethod').value,
                    reference_number: document.getElementById('paymentReference').value || null,
                }),
            })
            .then(async (r) => {
                const data = await r.json().catch(() => ({}));
                if (!r.ok) {
                    errBox.textContent = data.message || 'Please check the amount and method.';
                    errBox.classList.remove('d-none');
                    btn.disabled = false;
                    return;
                }
                window.location.reload();
            })
            .catch(() => {
                errBox.textContent = 'Network error. Please try again.';
                errBox.classList.remove('d-none');
                btn.disabled = false;
            });
        });
    }

    document.querySelectorAll('.js-remove-payment').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (!confirm('Remove this payment?')) return;
            fetch(this.dataset.url, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': csrf, 'Accept': 'application/json' },
            })
            .then(async (r) => {
                const data = await r.json().catch(() => ({}));
                if (!r.ok) { alert(data.message || 'Failed.'); return; }
                window.location.reload();
            })
            .catch(() => alert('Network error.'));
        });
    });

    // Print labels: select rows + copies, submit to a new tab.
    const rowChecks   = () => Array.from(document.querySelectorAll('.js-label-row'));
    const selectAll   = document.getElementById('labelSelectAll');
    const printBtn    = document.getElementById('printLabelsBtn');
    const countLabel  = document.getElementById('labelSelectedCount');
    const printForm   = document.getElementById('printLabelsForm');

    function refreshLabelUI() {
        const checked = rowChecks().filter(cb => cb.checked);
        countLabel.textContent = checked.length + ' selected';
        printBtn.disabled = checked.length === 0;
    }

    if (selectAll) {
        selectAll.addEventListener('change', function () {
            rowChecks().forEach(cb => { cb.checked = selectAll.checked; });
            refreshLabelUI();
        });
    }

    rowChecks().forEach(cb => cb.addEventListener('change', refreshLabelUI));

    if (printBtn) {
        printBtn.addEventListener('click', function () {
            const checked = rowChecks().filter(cb => cb.checked);
            if (checked.length === 0) return;

            printForm.innerHTML = '';
            checked.forEach(function (cb, idx) {
                const tr = cb.closest('tr');
                const copiesInput = tr ? tr.querySelector('.js-label-copies') : null;
                const copies = copiesInput ? (parseInt(copiesInput.value, 10) || 1) : 1;

                const idField = document.createElement('input');
                idField.type = 'hidden';
                idField.name = `items[${idx}][id]`;
                idField.value = cb.value;
                printForm.appendChild(idField);

                const copiesField = document.createElement('input');
                copiesField.type = 'hidden';
                copiesField.name = `items[${idx}][copies]`;
                copiesField.value = copies;
                printForm.appendChild(copiesField);
            });

            printForm.submit();
        });
    }
})();
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layout.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH F:\VScode LIve ftp\paces\resources\views/purchases/show.blade.php ENDPATH**/ ?>