<div class="stock-header" style="background: linear-gradient(120deg, #1B5FA8 0%, #123E70 100%);">
    <div class="sth-icon"><i class="fa-solid fa-truck"></i></div>
    <div class="sth-text">
        <h2>Suppliers</h2>
        <div class="sth-sub">
            <?= (int) $summary['total_active'] ?> active suppliers · <?= (int) $summary['with_payable'] ?> with outstanding payable · Total payable: <?= formatMoney($totalDues) ?>
        </div>
    </div>
    <div class="sth-actions">
        <?php if (Auth::can('suppliers', 'add')): ?>
        <button type="button" class="btn sth-btn" onclick="rmsOpenModal('rmsAddSupplierModal')"><i class="fa-solid fa-plus"></i> Add Supplier</button>
        <?php endif; ?>
        <button type="button" class="btn sth-btn" onclick="window.print()"><i class="fa-solid fa-print"></i> Print</button>
    </div>
</div>

<div class="stat-mini-grid">
    <div class="stat-mini sm-blue"><div class="sm-value"><?= (int) $summary['total_active'] ?></div><div class="sm-label">Total Active</div></div>
    <div class="stat-mini sm-red"><div class="sm-value"><?= (int) $summary['with_payable'] ?></div><div class="sm-label">With Payable</div></div>
    <div class="stat-mini sm-gold"><div class="sm-value"><?= formatMoney($totalDues) ?></div><div class="sm-label">Total Payable</div></div>
    <div class="stat-mini sm-green"><div class="sm-value" id="rmsSupplierCount"><?= count($suppliers) ?></div><div class="sm-label">Filtered Results</div></div>
</div>

<div class="filter-bar">
    <div class="fb-search"><i class="fa-solid fa-magnifying-glass"></i><input type="text" id="rmsSupplierSearch" placeholder="Name, phone, contact person..." onkeyup="rmsFilterSuppliers()"></div>
    <div class="fb-pills" id="rmsSupplierStatusPills">
        <button type="button" class="fb-pill active" data-status="all" onclick="rmsSetSupplierStatus('all', this)">All</button>
        <button type="button" class="fb-pill fp-green" data-status="active" onclick="rmsSetSupplierStatus('active', this)">Active</button>
        <button type="button" class="fb-pill fp-red" data-status="inactive" onclick="rmsSetSupplierStatus('inactive', this)">Inactive</button>
    </div>
    <div class="fb-pills" id="rmsSupplierBalancePills">
        <button type="button" class="fb-pill active" data-balance="all" onclick="rmsSetSupplierBalance('all', this)">All Balances</button>
        <button type="button" class="fb-pill fp-red" data-balance="due" onclick="rmsSetSupplierBalance('due', this)">Has Due</button>
        <button type="button" class="fb-pill fp-green" data-balance="clear" onclick="rmsSetSupplierBalance('clear', this)">Settled</button>
    </div>
    <button type="button" class="btn btn-secondary" onclick="rmsClearSupplierFilters()"><i class="fa-solid fa-xmark"></i></button>
</div>

<div class="dark-table-panel">
    <div class="dtp-head">
        <span><i class="fa-solid fa-truck"></i> Supplier List</span>
        <span class="dtp-count"><?= count($suppliers) ?> records</span>
    </div>
    <div style="overflow-x:auto;">
    <table class="data-table">
    <thead><tr><th>#</th><th>Supplier</th><th>Contact</th><th>Orders</th><th>Total Purchased</th><th>Payable</th><th>Last Order</th><th>Status</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($suppliers as $i => $s):
        $due = (float) $s['total_ordered'] - (float) $s['total_paid'];
        $initials = strtoupper(substr($s['supplier_name'], 0, 2));
        $statusKey = $s['is_active'] ? 'active' : 'inactive';
        $balanceKey = $due > 0 ? 'due' : 'clear';
        $lastOrderRel = '';
        if ($s['last_order_date']) {
            $days = (int) floor((strtotime(date('Y-m-d')) - strtotime($s['last_order_date'])) / 86400);
            $lastOrderRel = $days === 0 ? 'Today' : ($days === 1 ? 'Yesterday' : "{$days} days ago");
        }
    ?>
    <tr class="rms-supplier-row" data-name="<?= e(mb_strtolower($s['supplier_name'] . ' ' . ($s['contact_person'] ?? '') . ' ' . ($s['phone'] ?? ''))) ?>" data-status="<?= $statusKey ?>" data-balance="<?= $balanceKey ?>">
        <td><?= $i + 1 ?></td>
        <td>
            <div style="display:flex;align-items:center;gap:10px;">
                <div class="supplier-avatar"><?= e($initials) ?></div>
                <div>
                    <strong><?= e($s['supplier_name']) ?></strong>
                    <?php if ($s['address']): ?><div style="font-size:11px;color:var(--color-text-muted);"><?= e($s['address']) ?></div><?php endif; ?>
                </div>
            </div>
        </td>
        <td>
            <?php if ($s['contact_person']): ?><div style="font-weight:700;font-size:12px;"><?= e($s['contact_person']) ?></div><?php endif; ?>
            <?php if ($s['phone']): ?><div style="font-size:11.5px;color:var(--color-text-muted);"><i class="fa-solid fa-phone"></i> <?= e($s['phone']) ?></div><?php endif; ?>
            <?php if ($s['email']): ?><div style="font-size:11.5px;color:var(--color-text-muted);"><i class="fa-solid fa-envelope"></i> <?= e($s['email']) ?></div><?php endif; ?>
        </td>
        <td><span class="badge badge-blue"><?= (int) $s['po_count'] ?></span></td>
        <td><?= formatMoney((float) $s['total_ordered']) ?></td>
        <td><?= $due > 0 ? '<span class="badge badge-red">' . formatMoney($due) . '</span>' : '<span class="badge badge-green"><i class="fa-solid fa-circle-check"></i> Clear</span>' ?></td>
        <td>
            <?php if ($s['last_order_date']): ?>
            <div style="font-size:12px;"><?= date('d M Y', strtotime($s['last_order_date'])) ?></div>
            <div style="font-size:10.5px;color:var(--color-text-muted);"><?= e($lastOrderRel) ?></div>
            <?php else: ?>
            <span style="color:var(--color-text-muted);">—</span>
            <?php endif; ?>
        </td>
        <td><?= $s['is_active'] ? '<span class="badge badge-green">Active</span>' : '<span class="badge badge-gray">Inactive</span>' ?></td>
        <td style="white-space:nowrap;">
            <?php if (Auth::can('suppliers', 'edit')): ?>
            <button type="button" class="icon-btn icon-btn-gray" onclick="rmsOpenModal('rmsEditSupplierModal<?= $s['id'] ?>')" title="Edit"><i class="fa-solid fa-pen"></i></button>
            <?php endif; ?>
            <a href="<?= Router::url('purchasing?supplier_id=' . $s['id']) ?>" class="icon-btn icon-btn-teal" title="New Purchase Order"><i class="fa-solid fa-cart-plus"></i></a>
            <?php if (Auth::can('suppliers', 'edit')): ?>
            <form method="POST" action="<?= Router::url('suppliers/toggle') ?>" style="display:inline;">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $s['id'] ?>">
                <button type="submit" class="icon-btn <?= $s['is_active'] ? 'icon-btn-red' : 'icon-btn-blue' ?>" title="<?= $s['is_active'] ? 'Deactivate' : 'Activate' ?>"><i class="fa-solid <?= $s['is_active'] ? 'fa-ban' : 'fa-check' ?>"></i></button>
            </form>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($suppliers)): ?>
    <tr><td colspan="9" style="text-align:center;color:var(--color-text-muted);padding:30px;">No suppliers yet.</td></tr>
    <?php endif; ?>
    </tbody>
    </table>
    </div>
</div>

<?php if (Auth::can('suppliers', 'add')): ?>
<div class="rms-modal-overlay" id="rmsAddSupplierModal">
    <div class="rms-modal">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-truck" style="color:var(--color-teal);margin-right:6px;"></i>Add Supplier</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsAddSupplierModal')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('suppliers/store') ?>">
            <?= $csrf ?>
            <div class="form-group"><label>Supplier Name</label><input type="text" name="supplier_name" class="form-control" required></div>
            <div class="form-group"><label>Contact Person</label><input type="text" name="contact_person" class="form-control"></div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div class="form-group"><label>Phone</label><input type="text" name="phone" class="form-control"></div>
                <div class="form-group"><label>Email</label><input type="email" name="email" class="form-control"></div>
            </div>
            <div class="form-group"><label>Address</label><textarea name="address" class="form-control" rows="2"></textarea></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-plus"></i> Add Supplier</button>
        </form>
    </div>
</div>
<?php endif; ?>

<?php foreach ($suppliers as $s): if (!Auth::can('suppliers', 'edit')) continue; ?>
<div class="rms-modal-overlay" id="rmsEditSupplierModal<?= $s['id'] ?>">
    <div class="rms-modal">
        <div class="rms-modal-head">
            <h3><i class="fa-solid fa-pen" style="color:var(--color-teal);margin-right:6px;"></i>Edit Supplier</h3>
            <button type="button" class="rms-modal-close" onclick="rmsCloseModal('rmsEditSupplierModal<?= $s['id'] ?>')"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <form method="POST" action="<?= Router::url('suppliers/update') ?>">
            <?= $csrf ?>
            <input type="hidden" name="id" value="<?= $s['id'] ?>">
            <div class="form-group"><label>Supplier Name</label><input type="text" name="supplier_name" class="form-control" value="<?= e($s['supplier_name']) ?>" required></div>
            <div class="form-group"><label>Contact Person</label><input type="text" name="contact_person" class="form-control" value="<?= e($s['contact_person'] ?? '') ?>"></div>
            <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                <div class="form-group"><label>Phone</label><input type="text" name="phone" class="form-control" value="<?= e($s['phone'] ?? '') ?>"></div>
                <div class="form-group"><label>Email</label><input type="email" name="email" class="form-control" value="<?= e($s['email'] ?? '') ?>"></div>
            </div>
            <div class="form-group"><label>Address</label><textarea name="address" class="form-control" rows="2"><?= e($s['address'] ?? '') ?></textarea></div>
            <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-floppy-disk"></i> Save Changes</button>
        </form>
    </div>
</div>
<?php endforeach; ?>

<style>
.supplier-avatar {
    width: 34px; height: 34px; border-radius: 8px; background: var(--color-navy); color: #fff;
    display: flex; align-items: center; justify-content: center; font-size: 11.5px; font-weight: 700; flex-shrink: 0;
}
</style>

<script>
let rmsSupplierStatus = 'all';
let rmsSupplierBalance = 'all';

function rmsSetSupplierStatus(val, btn) {
    rmsSupplierStatus = val;
    document.querySelectorAll('#rmsSupplierStatusPills .fb-pill').forEach(p => p.classList.remove('active'));
    btn.classList.add('active');
    rmsApplySupplierFilters();
}
function rmsSetSupplierBalance(val, btn) {
    rmsSupplierBalance = val;
    document.querySelectorAll('#rmsSupplierBalancePills .fb-pill').forEach(p => p.classList.remove('active'));
    btn.classList.add('active');
    rmsApplySupplierFilters();
}
function rmsFilterSuppliers() { rmsApplySupplierFilters(); }

function rmsApplySupplierFilters() {
    const q = document.getElementById('rmsSupplierSearch').value.toLowerCase();
    let visible = 0;
    document.querySelectorAll('.rms-supplier-row').forEach(row => {
        const matchesName = row.dataset.name.includes(q);
        const matchesStatus = rmsSupplierStatus === 'all' || row.dataset.status === rmsSupplierStatus;
        const matchesBalance = rmsSupplierBalance === 'all' || row.dataset.balance === rmsSupplierBalance;
        const show = matchesName && matchesStatus && matchesBalance;
        row.style.display = show ? '' : 'none';
        if (show) visible++;
    });
    document.getElementById('rmsSupplierCount').textContent = visible;
}
function rmsClearSupplierFilters() {
    document.getElementById('rmsSupplierSearch').value = '';
    rmsSupplierStatus = 'all'; rmsSupplierBalance = 'all';
    document.querySelectorAll('.fb-pill').forEach(p => p.classList.remove('active'));
    document.querySelector('#rmsSupplierStatusPills .fb-pill[data-status="all"]').classList.add('active');
    document.querySelector('#rmsSupplierBalancePills .fb-pill[data-balance="all"]').classList.add('active');
    rmsApplySupplierFilters();
}
</script>
