<?php
// Session Guard
if (empty($_SESSION['namauser']) && empty($_SESSION['passuser'])) {
    echo "
    <div class='adm-card text-center py-5' style='max-width: 480px; margin: 40px auto;'>
        <div class='mb-3' style='font-size: 3rem; color: var(--adm-primary);'>
            <i class='fa fa-lock'></i>
        </div>
        <h4 style='color: var(--adm-text); font-weight: 700;' class='mb-2'>Akses Terbatas</h4>
        <p style='color: var(--adm-text-sub); font-size: 0.9rem;' class='mb-4'>
            Silahkan login terlebih dahulu untuk mengakses modul ini.
        </p>
        <a href='../../index.php' class='btn btn-danger d-inline-flex align-items-center gap-2 px-4 py-2'>
            <i class='fa fa-sign-in-alt'></i> Login Sekarang
        </a>
    </div>";
    exit();
}

include "../config/koneksi.php";

$aksi = "modul/mod_blog/aksi_blog.php";
$act  = isset($_GET['act']) ? $_GET['act'] : '';

switch ($act) {
    // ==========================================
    // TAMPIL DATA BLOG (DEFAULT)
    // ==========================================
    default:
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="fw-bold m-0" style="color: var(--adm-text);">Manajemen Blog</h4>
            <small style="color: var(--adm-text-sub);">Kelola postingan artikel dan berita terbaru</small>
        </div>
        <a href="?module=blog&act=tambahblog" class="btn btn-danger d-inline-flex align-items-center gap-2">
            <i class="fa fa-plus"></i> Tambah Blog
        </a>
    </div>

    <div class="adm-card p-4">
        <div class="table-responsive">
            <table class="table align-middle text-nowrap mb-0" style="color: var(--adm-text); border-color: var(--adm-border);">
                <thead>
                    <tr style="border-bottom: 2px solid var(--adm-border-active); color: var(--adm-text-sub); font-size: 0.8rem; text-transform: uppercase;">
                        <th scope="col" class="py-3" style="width: 50px;">NO</th>
                        <th scope="col" class="py-3" style="width: 100px;">GAMBAR</th>
                        <th scope="col" class="py-3">JUDUL BLOG</th>
                        <th scope="col" class="py-3" style="width: 150px;">TGL. POSTING</th>
                        <th scope="col" class="py-3 text-center" style="width: 140px;">AKSI</th>
                    </tr>
                </thead>
                <tbody style="font-size: 0.88rem;">
                    <?php
                    if (isset($_SESSION['leveluser']) && $_SESSION['leveluser'] == 'admin') {
                        $query  = "SELECT * FROM blog ORDER BY id_blog DESC";
                    } else {
                        $username = mysqli_real_escape_string($konek, $_SESSION['namauser'] ?? '');
                        $query    = "SELECT * FROM blog WHERE username='$username' ORDER BY id_blog DESC";
                    }

                    $tampil = mysqli_query($konek, $query);
                    $no     = 1;

                    if ($tampil && mysqli_num_rows($tampil) > 0) {
                        while ($r = mysqli_fetch_array($tampil)) {
                            $tgl_posting = !empty($r['tgl_posting']) ? tgl_indo($r['tgl_posting']) : '-';
                            $img_src     = !empty($r['gambar']) ? "../foto_blog/{$r['gambar']}" : "https://via.placeholder.com/100x70?text=No+Image";

                            echo "
                            <tr style='border-bottom: 1px solid var(--adm-border);'>
                                <td class='py-3'>{$no}</td>
                                <td class='py-3'>
                                    <img src='{$img_src}' class='rounded border' style='width: 70px; height: 50px; object-fit: cover; border-color: var(--adm-border) !important;'>
                                </td>
                                <td class='py-3 fw-semibold'>" . htmlspecialchars($r['judul_blog']) . "</td>
                                <td class='py-3' style='color: var(--adm-text-sub);'>{$tgl_posting}</td>
                                <td class='py-3 text-center'>
                                    <div class='d-flex justify-content-center gap-2'>
                                        <a href='?module=blog&act=editblog&id={$r['id_blog']}' class='btn btn-sm btn-outline-primary d-inline-flex align-items-center gap-1' title='Edit'>
                                            <i class='fa fa-edit'></i> Edit
                                        </a>
                                        <a href='{$aksi}?module=blog&act=hapus&id={$r['id_blog']}' onclick=\"return confirm('Yakin ingin menghapus blog ini?')\" class='btn btn-sm btn-outline-danger d-inline-flex align-items-center gap-1' title='Hapus'>
                                            <i class='fa fa-trash'></i>
                                        </a>
                                    </div>
                                </td>
                            </tr>";
                            $no++;
                        }
                    } else {
                        echo "<tr><td colspan='5' class='text-center py-4' style='color: var(--adm-text-sub);'>Belum ada artikel/blog.</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
<?php
    break;

    // ==========================================
    // FORM TAMBAH BLOG
    // ==========================================
    case "tambahblog":
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="fw-bold m-0" style="color: var(--adm-text);">Tambah Blog Baru</h4>
            <small style="color: var(--adm-text-sub);">Isi formulir di bawah ini untuk menambahkan artikel baru</small>
        </div>
        <button onclick="self.history.back()" class="btn btn-sm btn-secondary d-inline-flex align-items-center gap-2">
            <i class="fa fa-arrow-left"></i> Kembali
        </button>
    </div>

    <div class="row">
        <div class="col-12 col-lg-10">
            <div class="adm-card p-4">
                <form method="POST" enctype="multipart/form-data" action="<?= $aksi ?>?module=blog&act=input">
                    <div class="mb-3 row">
                        <label class="col-sm-2 col-form-label fw-semibold" style="color: var(--adm-text);">Judul Blog</label>
                        <div class="col-sm-10">
                            <input type="text" name="judul_blog" class="form-control adm-input" placeholder="Masukkan judul blog..." required>
                        </div>
                    </div>

                    <div class="mb-3 row">
                        <label class="col-sm-2 col-form-label fw-semibold" style="color: var(--adm-text);">Isi Blog</label>
                        <div class="col-sm-10">
                            <textarea name="isi_blog" id="lokomedia" class="form-control adm-input" style="height: 300px;"></textarea>
                        </div>
                    </div>

                    <div class="mb-4 row">
                        <label class="col-sm-2 col-form-label fw-semibold" style="color: var(--adm-text);">Foto</label>
                        <div class="col-sm-10">
                            <input type="file" name="foto" id="inputFoto" class="form-control adm-input" accept="image/*">
                            <div id="previewFoto" class="mt-2"></div>
                        </div>
                    </div>

                    <div class="row pt-2">
                        <div class="col-sm-10 offset-sm-2 d-flex gap-2">
                            <button type="submit" class="btn btn-danger px-4 d-inline-flex align-items-center gap-2">
                                <i class="fa fa-save"></i> Simpan
                            </button>
                            <button type="button" onclick="self.history.back()" class="btn btn-outline-secondary px-4">
                                Batal
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    document.getElementById('inputFoto').addEventListener('change', function(e) {
        const file = e.target.files[0];
        const preview = document.getElementById('previewFoto');
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(evt) {
                preview.innerHTML = `<img src="${evt.target.result}" class="rounded border mt-1" style="max-width: 180px; height: auto;">`;
            };
            reader.readAsDataURL(file);
        } else {
            preview.innerHTML = '';
        }
    });
    </script>
<?php
    break;

    // ==========================================
    // FORM EDIT BLOG
    // ==========================================
    case "editblog":
        $id = mysqli_real_escape_string($konek, $_GET['id'] ?? '');

        if (isset($_SESSION['leveluser']) && $_SESSION['leveluser'] == 'admin') {
            $query = "SELECT * FROM blog WHERE id_blog='$id'";
        } else {
            $username = mysqli_real_escape_string($konek, $_SESSION['namauser'] ?? '');
            $query    = "SELECT * FROM blog WHERE id_blog='$id' AND username='$username'";
        }

        $hasil = mysqli_query($konek, $query);
        $r     = mysqli_fetch_array($hasil);
?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="fw-bold m-0" style="color: var(--adm-text);">Edit Blog</h4>
            <small style="color: var(--adm-text-sub);">Perbarui informasi artikel #<?= htmlspecialchars($r['id_blog'] ?? '') ?></small>
        </div>
        <button onclick="self.history.back()" class="btn btn-sm btn-secondary d-inline-flex align-items-center gap-2">
            <i class="fa fa-arrow-left"></i> Kembali
        </button>
    </div>

    <div class="row">
        <div class="col-12 col-lg-10">
            <div class="adm-card p-4">
                <form method="POST" enctype="multipart/form-data" action="<?= $aksi ?>?module=blog&act=update">
                    <input type="hidden" name="id" value="<?= htmlspecialchars($r['id_blog'] ?? '') ?>">
                    <input type="hidden" name="fotoku" value="<?= htmlspecialchars($r['gambar'] ?? '') ?>">

                    <div class="mb-3 row">
                        <label class="col-sm-2 col-form-label fw-semibold" style="color: var(--adm-text);">Judul Blog</label>
                        <div class="col-sm-10">
                            <input type="text" name="judul_blog" class="form-control adm-input" value="<?= htmlspecialchars($r['judul_blog'] ?? '') ?>" required>
                        </div>
                    </div>

                    <div class="mb-3 row">
                        <label class="col-sm-2 col-form-label fw-semibold" style="color: var(--adm-text);">Isi Blog</label>
                        <div class="col-sm-10">
                            <textarea name="isi_blog" id="lokomedia" class="form-control adm-input" style="height: 300px;"><?= htmlspecialchars($r['isi_blog'] ?? '') ?></textarea>
                        </div>
                    </div>

                    <div class="mb-3 row">
                        <label class="col-sm-2 col-form-label fw-semibold" style="color: var(--adm-text);">Gambar Terpasang</label>
                        <div class="col-sm-10">
                            <?php if (!empty($r['gambar'])): ?>
                                <img src="../foto_blog/<?= $r['gambar'] ?>" class="rounded border p-1" style="max-width: 180px; height: auto; border-color: var(--adm-border) !important;">
                            <?php else: ?>
                                <span class="badge bg-secondary">Belum ada gambar</span>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="mb-4 row">
                        <label class="col-sm-2 col-form-label fw-semibold" style="color: var(--adm-text);">Ganti Gambar</label>
                        <div class="col-sm-10">
                            <input type="file" name="foto" id="inputFotoEdit" class="form-control adm-input" accept="image/*">
                            <small class="text-muted d-block mt-1" style="font-size: 0.75rem;">* Apabila gambar tidak diganti, biarkan kosong.</small>
                            <div id="previewFotoEdit" class="mt-2"></div>
                        </div>
                    </div>

                    <div class="row pt-2">
                        <div class="col-sm-10 offset-sm-2 d-flex gap-2">
                            <button type="submit" class="btn btn-danger px-4 d-inline-flex align-items-center gap-2">
                                <i class="fa fa-save"></i> Perbarui
                            </button>
                            <button type="button" onclick="self.history.back()" class="btn btn-outline-secondary px-4">
                                Batal
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    document.getElementById('inputFotoEdit').addEventListener('change', function(e) {
        const file = e.target.files[0];
        const preview = document.getElementById('previewFotoEdit');
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(evt) {
                preview.innerHTML = `<img src="${evt.target.result}" class="rounded border mt-1" style="max-width: 180px; height: auto;">`;
            };
            reader.readAsDataURL(file);
        } else {
            preview.innerHTML = '';
        }
    });
    </script>
<?php
    break;
}
?>