<?= view('admin/layouts/header', ['title' => 'Data Barang']) ?>
<?php
$isLowStockFilter = ($stockFilter ?? '') === 'hampir-habis';
$isAdministrator = ($userRole ?? '') === 'administrator';
$barangTopbarAction = '<div class="d-flex flex-wrap gap-2 justify-content-end">'
    . '<a href="' . site_url('admin/barang/print/barcode') . '" target="_blank" class="btn btn-outline-dark"><i class="bi bi-upc-scan me-1"></i>Cetak Massal Barcode</a>'
    . '<a href="' . site_url('admin/barang/print/qrcode') . '" target="_blank" class="btn btn-outline-dark"><i class="bi bi-qr-code me-1"></i>Cetak Massal QR Code</a>';

if ($isAdministrator) {
    $barangTopbarAction .= '<a href="' . site_url('admin/barang/import') . '" class="btn btn-success"><i class="bi bi-upload me-1"></i>Import Barang</a>'
        . '<a href="' . site_url('admin/barang/create') . '" class="btn btn-dark"><i class="bi bi-plus-lg me-1"></i>Tambah Barang</a>';
}

$barangTopbarAction .= '</div>';
?>
<?= view('admin/layouts/sidebar', [
    'activeMenu' => 'barang',
    'userName'   => $userName,
    'userEmail'  => $userEmail,
]) ?>
<?= view('admin/layouts/topbar', [
    'pageTitle'    => 'Data Barang',
    'pageSubtitle' => $isLowStockFilter ? 'Menampilkan barang dengan stok hampir habis.' : 'Kelola master data barang inventaris.',
    'topbarAction' => $barangTopbarAction,
    'userName'     => $userName,
    'userRole'     => $userRole,
]) ?>

<section class="content-area">
    <?php if (session()->getFlashdata('success')) : ?>
        <div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')) : ?>
        <div class="alert alert-danger"><?= esc(session()->getFlashdata('error')) ?></div>
    <?php endif; ?>

    <div class="panel p-4">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
            <div>
                <div class="fw-bold">Daftar Barang</div>
                <div class="small text-secondary">
                    <?= $isLowStockFilter ? 'Filter aktif: stok hampir habis.' : 'Menampilkan semua data barang.' ?>
                </div>
            </div>
            <div class="d-flex flex-wrap gap-2">
                <?php if ($isLowStockFilter) : ?>
                    <a href="<?= site_url('admin/barang') ?>" class="btn btn-secondary">
                        <i class="bi bi-list-ul me-1"></i>Semua Barang
                    </a>
                <?php endif; ?>
                <a href="<?= site_url('admin/barang?stok=hampir-habis') ?>" class="btn <?= $isLowStockFilter ? 'btn-warning' : 'btn-warning' ?>">
                    <i class="bi bi-exclamation-triangle me-1"></i>Stok Hampir Habis
                </a>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-hover table-bordered align-middle datatable">
                <thead>
                    <tr>
                        <th>Foto</th>                        
                        <th>Barang</th>
                        <th>Kategori</th>
                        <th>Harga</th>
                        <th width="60" class="text-center">Stok</th>
                        <th width="80">QR/Barcode</th>
                        <th class="text-end">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($barang as $item) : ?>
                        <?php
                        $stok = (int) ($item['stok'] ?? 0);
                        $stokMinimum = (int) ($item['stok_minimum'] ?? 0);
                        $isLowStock = $stok <= $stokMinimum;
                        $isUsedInTransaction = ((int) ($item['total_pembelian'] ?? 0) + (int) ($item['total_penjualan'] ?? 0) + (int) ($item['total_service'] ?? 0)) > 0;
                        $hasStockAdjustment = (int) ($item['total_stok_penyesuaian'] ?? 0) > 0;
                        $deleteConfirmation = $hasStockAdjustment
                            ? 'Hapus barang ini? Data penyesuaian stok terkait juga akan ikut dihapus.'
                            : 'Hapus barang ini?';
                        ?>
                        <tr>
                            <td>
                                <?php if (! empty($item['foto'])) : ?>
                                    <img src="<?= base_url('uploads/barang/' . $item['foto']) ?>" alt="Foto <?= esc($item['nama_barang']) ?>" class="user-photo">
                                <?php else : ?>
                                    <div class="photo-placeholder">
                                        <i class="bi bi-box-seam"></i>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="fw-semibold d-block"><?= esc($item['kode_barang']) ?></span>                                
                                <span class="d-block"><?= esc($item['nama_barang']) ?></span>
                                <span class="badge text-bg-light border mt-1"><?= esc($item['lokasi_barang'] ?? '-') ?></span>
                            </td>
                            <td>
                                <span class="badge text-bg-light border">
                                    <i class="bi <?= esc($item['icon_kategori'] ?? 'bi-tag', 'attr') ?> me-1"></i><?= esc($item['nama_kategori'] ?? '-') ?>
                                </span>
                            </td>                                
                            <td>
                                <div class="small text-secondary">Beli</div>
                                <div class="fw-semibold">Rp <?= esc(number_format((float) ($item['harga_beli'] ?? 0), 0, ',', '.')) ?></div>
                                <div class="small text-secondary mt-1">Jual</div>
                                <div class="fw-semibold">Rp <?= esc(number_format((float) ($item['harga_jual'] ?? 0), 0, ',', '.')) ?></div>
                            </td>
                            <td class="text-center">
                                <div class="fw-semibold"><?= esc((string) $stok) ?> <?= esc($item['satuan']) ?></div>
                                <?php if ($isLowStock) : ?>
                                    <span class="badge text-bg-warning">Hampir habis</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-nowrap">
                                <a href="<?= site_url('admin/barang/qrcode/' . $item['id']) ?>" target="_blank" class="btn btn-sm btn-outline-dark d-block mb-2" title="Download QR Code">
                                    <i class="bi bi-qr-code"></i> QR
                                </a>
                                <a href="<?= site_url('admin/barang/barcode/' . $item['id']) ?>" target="_blank" class="btn btn-sm btn-outline-dark" title="Download Barcode">
                                    <i class="bi bi-upc-scan"></i> Barcode
                                </a>
                            </td>
                            <td class="text-end text-nowrap">
                                <a href="<?= site_url('admin/barang/detail/' . $item['id']) ?>" class="btn btn-sm btn-info btn-icon" title="Detail barang" aria-label="Detail barang">
                                    <i class="bi bi-eye"></i>
                                </a>
                                <?php if ($isAdministrator) : ?>
                                    <a href="<?= site_url('admin/barang/edit/' . $item['id']) ?>" class="btn btn-sm btn-primary btn-icon" title="Edit barang" aria-label="Edit barang">
                                        <i class="bi bi-pencil-square"></i>
                                    </a>
                                    <?php if ($isUsedInTransaction) : ?>
                                        <span tabindex="0" data-bs-toggle="popover" data-bs-trigger="hover focus" data-bs-placement="top" data-bs-content="Barang ini tidak bisa dihapus karena sudah terhubung ke data pembelian, penjualan, atau service. Hapus transaksi terkait terlebih dahulu.">
                                            <button type="button" class="btn btn-sm btn-secondary btn-icon" aria-label="Barang tidak dapat dihapus" disabled>
                                                <i class="bi bi-trash3"></i>
                                            </button>
                                        </span>
                                    <?php else : ?>
                                        <form action="<?= site_url('admin/barang/delete/' . $item['id']) ?>" method="post" class="d-inline" data-confirm="<?= esc($deleteConfirmation, 'attr') ?>">
                                            <?= csrf_field() ?>
                                            <button type="submit" class="btn btn-sm btn-danger btn-icon" title="Hapus barang" aria-label="Hapus barang">
                                                <i class="bi bi-trash3"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</section>

<?= view('admin/layouts/footer') ?>
