<?= view('admin/layouts/header', ['title' => 'Cicilan Penjualan']) ?>
<?= view('admin/layouts/sidebar', [
    'activeMenu' => 'penjualan',
    'userName'   => $userName,
    'userEmail'  => $userEmail,
]) ?>
<?= view('admin/layouts/topbar', [
    'pageTitle'    => 'Cicilan Penjualan',
    'pageSubtitle' => $transaksi['no_transaksi'],
    'topbarAction' => '<a href="' . site_url('admin/penjualan') . '" class="btn btn-outline-dark"><i class="bi bi-arrow-left me-1"></i>Kembali</a>',
    'userName'     => $userName,
    'userRole'     => $userRole,
]) ?>

<section class="content-area">
    <?php $errors = session()->getFlashdata('errors'); ?>
    <?php if ($errors) : ?>
        <div class="alert alert-danger">
            <?php foreach ($errors as $error) : ?>
                <div><?= esc($error) ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?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="row g-4">
        <div class="col-12 col-xl-4">
            <div class="panel p-4 h-100">
                <div class="fw-bold mb-3">Ringkasan Penjualan</div>

                <div class="mb-3">
                    <div class="small text-secondary">Pelanggan</div>
                    <div class="fw-semibold"><?= esc($transaksi['nama_pelanggan'] ?? '-') ?></div>
                    <?php if (! empty($transaksi['no_hp_pelanggan'])) : ?>
                        <div class="small text-secondary"><?= esc($transaksi['no_hp_pelanggan']) ?></div>
                    <?php endif; ?>
                </div>

                <div class="row g-3">
                    <div class="col-6">
                        <div class="small text-secondary">Total Penjualan</div>
                        <div class="h5 fw-bold mb-0">Rp <?= esc(number_format((float) $totalPenjualan, 0, ',', '.')) ?></div>
                    </div>
                    <div class="col-6">
                        <div class="small text-secondary">Total Dibayar</div>
                        <div class="h5 fw-bold mb-0">Rp <?= esc(number_format((float) $totalDibayar, 0, ',', '.')) ?></div>
                    </div>
                    <div class="col-6">
                        <div class="small text-secondary">Sisa Piutang</div>
                        <div class="h5 fw-bold mb-0">Rp <?= esc(number_format((float) $sisaPiutang, 0, ',', '.')) ?></div>
                    </div>
                    <div class="col-6">
                        <div class="small text-secondary">Status</div>
                        <?php $isLunas = ($transaksi['status_pembayaran'] ?? 'piutang') === 'lunas'; ?>
                        <span class="badge <?= $isLunas ? 'text-bg-success' : 'text-bg-warning' ?>"><?= $isLunas ? 'Lunas' : 'Piutang' ?></span>
                    </div>
                </div>

                <hr>

                <form action="<?= site_url('admin/penjualan/cicilan/store/' . $transaksi['id']) ?>" method="post" id="cicilanForm">
                    <?= csrf_field() ?>

                    <div class="mb-3">
                        <label for="tanggal_pembayaran" class="form-label fw-semibold">Tanggal Setoran</label>
                        <input type="date" class="form-control" id="tanggal_pembayaran" name="tanggal_pembayaran" value="<?= esc(old('tanggal_pembayaran', date('Y-m-d')), 'attr') ?>" <?= $sisaPiutang <= 0 ? 'disabled' : 'required' ?>>
                    </div>

                    <div class="mb-3">
                        <label for="jumlah_setoran" class="form-label fw-semibold">Jumlah Setoran</label>
                        <input type="text" class="form-control" id="jumlah_setoran" name="jumlah_setoran" inputmode="numeric" value="<?= esc(old('jumlah_setoran', ''), 'attr') ?>" data-max="<?= esc((string) $sisaPiutang, 'attr') ?>" <?= $sisaPiutang <= 0 ? 'disabled' : 'required' ?>>
                        <div class="form-text">Maksimal Rp <?= esc(number_format((float) $sisaPiutang, 0, ',', '.')) ?>.</div>
                    </div>

                    <div class="mb-3">
                        <label for="catatan_pembayaran" class="form-label fw-semibold">Catatan</label>
                        <textarea class="form-control" id="catatan_pembayaran" name="catatan_pembayaran" rows="2" <?= $sisaPiutang <= 0 ? 'disabled' : '' ?>><?= esc(old('catatan_pembayaran', '')) ?></textarea>
                    </div>

                    <button type="submit" class="btn btn-dark w-100" <?= $sisaPiutang <= 0 ? 'disabled' : '' ?>>
                        <i class="bi bi-plus-lg"></i>Tambah Cicilan
                    </button>
                </form>
            </div>
        </div>

        <div class="col-12 col-xl-8">
            <div class="panel p-4 h-100">
                <div class="d-flex align-items-center justify-content-between gap-3 mb-3">
                    <div>
                        <div class="fw-bold">Riwayat Pembayaran</div>
                        <div class="small text-secondary">Daftar pembayaran dan cicilan untuk transaksi ini.</div>
                    </div>
                    <div class="badge text-bg-light border"><?= esc((string) count($payments)) ?> setoran</div>
                </div>

                <?php $lastPayment = ! empty($payments) ? end($payments) : null; ?>
                <?php $lastPaymentId = is_array($lastPayment) ? (int) ($lastPayment['id'] ?? 0) : 0; ?>

                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead>
                            <tr>
                                <th>Tanggal</th>
                                <th>Jenis</th>
                                <th class="text-end">Jumlah Setoran</th>
                                <th>Catatan</th>
                                <th>User</th>
                                <th class="text-end">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($payments as $payment) : ?>
                                <tr>
                                    <td><?= esc(date('d/m/Y', strtotime($payment['tanggal_pembayaran']))) ?></td>
                                    <td>
                                        <?php if ((int) ($payment['is_pembayaran_awal'] ?? 0) === 1) : ?>
                                            <span class="badge text-bg-primary">Pembayaran Awal</span>
                                        <?php else : ?>
                                            <span class="badge text-bg-light border">Cicilan</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end fw-semibold">Rp <?= esc(number_format((float) ($payment['jumlah'] ?? 0), 0, ',', '.')) ?></td>
                                    <td><?= ! empty($payment['catatan']) ? esc($payment['catatan']) : '-' ?></td>
                                    <td><?= esc($payment['nama_user'] ?? '-') ?></td>
                                    <td class="text-end">
                                        <?php if ((int) ($payment['id'] ?? 0) === $lastPaymentId) : ?>
                                            <form action="<?= site_url('admin/penjualan/cicilan/delete/' . $transaksi['id'] . '/' . $payment['id']) ?>" method="post" class="d-inline" data-confirm="Hapus pembayaran terakhir ini?">
                                                <?= csrf_field() ?>
                                                <button type="submit" class="btn btn-sm btn-danger btn-icon" title="Hapus pembayaran terakhir" aria-label="Hapus pembayaran terakhir">
                                                    <i class="bi bi-trash3"></i>
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            <?php if (empty($payments)) : ?>
                                <tr>
                                    <td colspan="6" class="text-center text-secondary py-4">Belum ada pembayaran.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('cicilanForm');
        const amountInput = document.getElementById('jumlah_setoran');

        if (! form || ! amountInput) {
            return;
        }

        const normalizeNumber = function (value) {
            const digits = String(value || '').replace(/\D/g, '');
            const number = parseInt(digits || '0', 10);
            return Number.isFinite(number) && number >= 0 ? number : 0;
        };

        const formatNumber = function (value) {
            return normalizeNumber(value).toLocaleString('id-ID', {minimumFractionDigits: 0, maximumFractionDigits: 0});
        };

        amountInput.addEventListener('input', function () {
            amountInput.value = formatNumber(amountInput.value);
        });

        form.addEventListener('submit', function (event) {
            const amount = normalizeNumber(amountInput.value);
            const maxAmount = normalizeNumber(amountInput.dataset.max || 0);

            if (amount < 1) {
                event.preventDefault();
                alert('Jumlah setoran wajib lebih dari 0.');
                amountInput.focus();
                return;
            }

            if (amount > maxAmount) {
                event.preventDefault();
                alert('Jumlah setoran tidak boleh lebih besar dari sisa piutang.');
                amountInput.focus();
            }
        });
    });
</script>

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