<?php
$jasa = $jasa ?? [];
$biayaRaw = old('biaya', $jasa['biaya'] ?? 0);
$biayaValue = (int) (preg_replace('/\D/', '', (string) $biayaRaw) ?: 0);
?>

<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; ?>

    <div class="row">
        <div class="col-lg-6">
            <div class="panel p-4">
                <form action="<?= esc($action, 'attr') ?>" method="post">
                    <?= csrf_field() ?>

                    <div class="row g-4">
                        <div class="col-12">
                            <label for="nama_jasa" class="form-label fw-semibold">Nama Jasa</label>
                            <input type="text" class="form-control" id="nama_jasa" name="nama_jasa" value="<?= esc(old('nama_jasa', $jasa['nama_jasa'] ?? ''), 'attr') ?>" required>
                        </div>

                        <div class="col-12">
                            <label for="biaya" class="form-label fw-semibold">Biaya</label>
                            <input type="text" class="form-control" id="biaya" name="biaya" inputmode="numeric" value="<?= esc(number_format($biayaValue, 0, ',', '.'), 'attr') ?>" required>
                        </div>
                    </div>

                    <div class="d-flex justify-content-end gap-2 mt-4">
                        <a href="<?= site_url('admin/jasa') ?>" class="btn btn-light">Batal</a>
                        <button type="submit" class="btn btn-dark"><?= esc($submitLabel ?? 'Simpan') ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</section>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const biayaInput = document.getElementById('biaya');

        const formatNumber = function (value) {
            const digits = String(value ?? '').replace(/\D/g, '');
            const number = parseInt(digits || '0', 10);

            return (Number.isFinite(number) ? number : 0).toLocaleString('id-ID', {
                minimumFractionDigits: 0,
                maximumFractionDigits: 0
            });
        };

        biayaInput.addEventListener('input', function () {
            biayaInput.value = formatNumber(biayaInput.value);
        });
    });
</script>
