<?= $this->extend('layouts/main') ?>

<?= $this->section('title') ?>Berita<?= $this->endSection() ?>
<?php $rows = is_array($payload) ? ($payload['rows'] ?? []) : []; ?>
<?php
$beritaPhotoUrl = static function (string $photo): ?string {
    $p = trim($photo);
    if ($p === '' || $p === '-') {
        return null;
    }
    $base = basename(str_replace('\\', '/', $p));

    return base_url('assets/uploads/berita/' . rawurlencode($base));
};
?>

<?= $this->section('content') ?>
<div class="space-y-6">
    <div>
        <h1 class="text-2xl font-semibold text-gray-900">Berita / pengumuman</h1>
        <p class="mt-1 text-sm text-gray-500">Foto disimpan di <code class="rounded bg-gray-100 px-1 text-xs">assets/uploads/berita/</code> (sama lokasi dengan aplikasi mobile). Bisa unggah file atau isi nama file yang sudah ada.</p>
    </div>
    <?= view('layouts/partials/admin_alert', ['errors' => $errors ?? []]) ?>
    <section class="rounded-2xl border border-gray-200 bg-white p-5 shadow-sm">
        <form method="post" action="<?= site_url('admin/perusahaan/berita/save') ?>" enctype="multipart/form-data" class="grid gap-4">
            <?= csrf_field() ?>
            <input type="hidden" name="id_berita" id="f_id" value="">
            <input type="hidden" name="photo_existing" id="f_photo_existing" value="">
            <div class="grid gap-4 sm:grid-cols-2">
                <div>
                    <label class="mb-1 block text-xs font-medium text-gray-600">Tanggal *</label>
                    <input type="date" name="tanggal" id="f_tgl" required class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm shadow-sm">
                </div>
                <div class="sm:col-span-2 rounded-xl border border-gray-100 bg-gray-50/80 p-4">
                    <p class="text-xs font-semibold uppercase tracking-wide text-gray-500">Gambar berita</p>
                    <div id="f_preview_wrap" class="mt-2 hidden">
                        <img id="f_preview_img" src="" alt="Pratinjau" class="h-20 w-20 rounded-lg border border-gray-200 object-cover shadow-sm">
                    </div>
                    <div class="mt-3 grid gap-3 sm:grid-cols-2">
                        <div class="sm:col-span-2">
                            <label class="mb-1 block text-xs font-medium text-gray-600">Unggah foto</label>
                            <input type="file" name="photo_file" id="f_photo_file" accept="image/jpeg,image/png,image/gif,image/webp" class="block w-full text-sm text-gray-600 file:mr-3 file:rounded-lg file:border-0 file:bg-blue-50 file:px-3 file:py-2 file:text-sm file:font-semibold file:text-blue-700 hover:file:bg-blue-100">
                        </div>
                        <div class="sm:col-span-2">
                            <label class="mb-1 block text-xs font-medium text-gray-600">Nama file di server (opsional)</label>
                            <input name="photo" id="f_photo" class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm font-mono shadow-sm" placeholder="-" autocomplete="off">
                        </div>
                    </div>
                </div>
            </div>
            <div>
                <label class="mb-1 block text-xs font-medium text-gray-600">Judul *</label>
                <input name="judul" id="f_judul" required class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm shadow-sm">
            </div>
            <div>
                <label class="mb-1 block text-xs font-medium text-gray-600">Isi *</label>
                <textarea name="isi" id="f_isi" rows="5" required class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm shadow-sm"></textarea>
            </div>
            <div class="flex gap-2">
                <button type="submit" class="rounded-lg bg-blue-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-700">Simpan</button>
                <button type="button" id="f_clear" class="rounded-lg border border-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50">Bersihkan</button>
            </div>
        </form>
    </section>
    <section class="overflow-hidden rounded-2xl border border-gray-200 bg-white shadow-sm">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 text-sm">
                <thead class="border-y border-gray-200 bg-gray-50 text-left text-xs font-semibold uppercase text-gray-500">
                    <tr><th class="px-5 py-3">Tanggal</th><th class="px-5 py-3 w-16">Foto</th><th class="px-5 py-3">Judul</th><th class="px-5 py-3"></th></tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <?php foreach ($rows as $r) : ?>
                        <?php if (! is_array($r)) {
                            continue;
                        } ?>
                        <?php
                        $purl = $beritaPhotoUrl((string) ($r['photo'] ?? ''));
                        ?>
                        <tr class="hover:bg-gray-50">
                            <td class="whitespace-nowrap px-5 py-3"><?= esc((string) ($r['tanggal'] ?? '')) ?></td>
                            <td class="px-5 py-3">
                                <?php if ($purl !== null) : ?>
                                    <img src="<?= esc($purl) ?>" alt="" class="h-10 w-10 rounded-md border border-gray-100 object-cover">
                                <?php else : ?>
                                    <span class="text-xs text-gray-400">—</span>
                                <?php endif ?>
                            </td>
                            <td class="px-5 py-3 font-medium text-gray-900"><?= esc((string) ($r['judul'] ?? '')) ?></td>
                            <td class="whitespace-nowrap px-5 py-3">
                                <button type="button" class="rounded-lg border border-gray-200 px-2 py-1 text-xs font-semibold btn-edit-berita" data-row="<?= esc(json_encode($r, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT), 'attr') ?>">Edit</button>
                                <form method="post" action="<?= site_url('admin/perusahaan/berita/delete/' . (int) ($r['id_berita'] ?? 0)) ?>" class="inline" onsubmit="return confirm('Hapus?');"><?= csrf_field() ?><button type="submit" class="ml-1 rounded-lg bg-red-50 px-2 py-1 text-xs font-semibold text-red-700">Hapus</button></form>
                            </td>
                        </tr>
                    <?php endforeach ?>
                </tbody>
            </table>
        </div>
    </section>
</div>
<script>
(function () {
    var base = <?= json_encode(base_url('assets/uploads/berita/')) ?>;
    function showPreview(filename) {
        var wrap = document.getElementById('f_preview_wrap');
        var img = document.getElementById('f_preview_img');
        if (!wrap || !img) return;
        if (!filename || filename === '-') {
            wrap.classList.add('hidden');
            img.removeAttribute('src');
            return;
        }
        img.src = base + encodeURIComponent(filename.split(/[/\\]/).pop());
        wrap.classList.remove('hidden');
    }
    document.querySelectorAll('.btn-edit-berita').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var o = JSON.parse(this.getAttribute('data-row'));
            document.getElementById('f_id').value = o.id_berita || '';
            document.getElementById('f_tgl').value = o.tanggal || '';
            document.getElementById('f_photo').value = (o.photo && o.photo !== '-') ? o.photo : '';
            document.getElementById('f_photo_existing').value = o.photo || '';
            document.getElementById('f_judul').value = o.judul || '';
            document.getElementById('f_isi').value = o.isi || '';
            var pf = document.getElementById('f_photo_file');
            if (pf) pf.value = '';
            showPreview((o.photo && o.photo !== '-') ? o.photo : '');
        });
    });
    document.getElementById('f_clear').addEventListener('click', function () {
        document.getElementById('f_id').value = '';
        document.getElementById('f_tgl').value = '';
        document.getElementById('f_photo').value = '';
        document.getElementById('f_photo_existing').value = '';
        document.getElementById('f_judul').value = '';
        document.getElementById('f_isi').value = '';
        var pf = document.getElementById('f_photo_file');
        if (pf) pf.value = '';
        showPreview('');
    });
    document.getElementById('f_photo').addEventListener('input', function () {
        var v = this.value.trim();
        showPreview(v && v !== '-' ? v : '');
    });
})();
</script>
<?= $this->endSection() ?>
