<?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_layanan/aksi_layanan.php";
$act  = isset($_GET['act']) ? $_GET['act'] : '';

switch ($act) {
    // ==========================================
    // TAMPIL DATA LAYANAN (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 Layanan</h4>
            <small style="color: var(--adm-text-sub);">Kelola daftar layanan dan galeri foto produk/jasa</small>
        </div>
        <a href="?module=layanan&act=tambahlayanan" class="btn btn-danger d-inline-flex align-items-center gap-2">
            <i class="fa fa-plus"></i> Tambah Layanan
        </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: 60px;">NO</th>
                        <th scope="col" class="py-3">JUDUL LAYANAN</th>
                        <th scope="col" class="py-3 text-center" style="width: 150px;">AKSI</th>
                    </tr>
                </thead>
                <tbody style="font-size: 0.88rem;">
                    <?php
                    $query  = "SELECT * FROM layanan ORDER BY id_layanan DESC";
                    $tampil = mysqli_query($konek, $query);
                    $no     = 1;

                    if (mysqli_num_rows($tampil) > 0) {
                        while ($r = mysqli_fetch_array($tampil)) {
                            echo "
                            <tr style='border-bottom: 1px solid var(--adm-border);'>
                                <td class='py-3'>{$no}</td>
                                <td class='py-3 fw-semibold'>" . htmlspecialchars($r['judul']) . "</td>
                                <td class='py-3 text-center'>
                                    <div class='d-flex justify-content-center gap-2'>
                                        <a href='?module=layanan&act=editlayanan&id={$r['id_layanan']}' 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=layanan&act=hapus&id={$r['id_layanan']}' onclick=\"return confirm('Yakin ingin menghapus layanan 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='3' class='text-center py-4' style='color: var(--adm-text-sub);'>Belum ada data layanan.</td></tr>";
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
<?php
    break;

    // ==========================================
    // FORM TAMBAH LAYANAN
    // ==========================================
    case "tambahlayanan":
?>
    <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 Layanan Baru</h4>
            <small style="color: var(--adm-text-sub);">Isi formulir di bawah ini untuk menambahkan layanan</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=layanan&act=input">
                    <div class="mb-3">
                        <label class="form-label fw-semibold" style="color: var(--adm-text);">Judul Layanan</label>
                        <input type="text" name="judul" class="form-control adm-input" placeholder="Masukkan judul layanan..." required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold" style="color: var(--adm-text);">Deskripsi Layanan</label>
                        <textarea name="isi_layanan" id="lokomedia" class="form-control adm-input" style="height: 320px;"></textarea>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-semibold d-block" style="color: var(--adm-text);">Upload Galeri Foto</label>
                        <div id="uploadWrapper">
                            <div class="upload-item mb-3">
                                <input type="file" name="foto[]" class="form-control adm-input uploadInput" accept="image/*">
                                <div class="preview mt-2"></div>
                            </div>
                        </div>
                        <small class="text-muted d-block" style="font-size: 0.75rem;">File yang dipilih akan otomatis menambahkan field baru di bawahnya.</small>
                    </div>

                    <div class="d-flex gap-2 pt-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>
                </form>
            </div>
        </div>
    </div>

    <script>
    document.addEventListener('change', function(e) {
        if (!e.target.classList.contains('uploadInput')) return;

        const fileInput = e.target;
        const file = fileInput.files[0];
        if (!file || !file.type.startsWith('image/')) return;

        const reader = new FileReader();
        reader.onload = function(event) {
            const previewDiv = fileInput.nextElementSibling;
            previewDiv.innerHTML = `<img src="${event.target.result}" class="rounded border mt-1" style="max-width: 180px; height: auto;">`;

            const allInputs = document.querySelectorAll('.uploadInput');
            const lastInput = allInputs[allInputs.length - 1];

            if (fileInput === lastInput) {
                const uploadWrapper = document.getElementById('uploadWrapper');
                const newUpload = document.createElement('div');
                newUpload.classList.add('upload-item', 'mb-3');
                newUpload.innerHTML = `
                    <input type="file" name="foto[]" class="form-control adm-input uploadInput" accept="image/*">
                    <div class="preview mt-2"></div>
                `;
                uploadWrapper.appendChild(newUpload);
            }
        };
        reader.readAsDataURL(file);
    });
    </script>
<?php
    break;

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

        if (isset($_SESSION['leveluser']) && $_SESSION['leveluser'] == 'admin') {
            $query = "SELECT * FROM layanan WHERE id_layanan='$id'";
        } else {
            $username = $_SESSION['namauser'] ?? '';
            $query    = "SELECT * FROM layanan WHERE id_layanan='$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 Layanan</h4>
            <small style="color: var(--adm-text-sub);">Perbarui informasi layanan #<?= htmlspecialchars($r['id_layanan']) ?></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=layanan&act=update">
                    <input type="hidden" name="id" value="<?= htmlspecialchars($r['id_layanan']) ?>">
                    <input type="hidden" name="fotoku" value="<?= htmlspecialchars($r['gambar'] ?? '') ?>">

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

                    <div class="mb-3">
                        <label class="form-label fw-semibold" style="color: var(--adm-text);">Deskripsi Layanan</label>
                        <textarea name="isi_layanan" id="lokomedia" class="form-control adm-input" style="height: 320px;"><?= htmlspecialchars($r['isi_layanan']) ?></textarea>
                    </div>

                    <!-- GALERI FOTO SAAT INI -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold d-block" style="color: var(--adm-text);">Galeri Foto Terpasang</label>
                        <div class="row g-3">
                            <?php
                            $g = mysqli_query($konek, "SELECT * FROM semua_gambar WHERE id_layanan='{$r['id_layanan']}'");
                            if (mysqli_num_rows($g) > 0) {
                                while ($img = mysqli_fetch_array($g)) {
                                    echo "
                                    <div class='col-6 col-sm-4 col-md-3 text-center'>
                                        <div class='p-2 border rounded' style='border-color: var(--adm-border) !important;'>
                                            <img src='../foto_layanan/{$img['nama_file']}' class='img-fluid rounded mb-2' style='max-height: 120px; object-fit: cover;'>
                                            <a href='{$aksi}?module=layanan&act=hapusgambar&id={$img['id_gambar']}&layanan={$r['id_layanan']}' 
                                               class='btn btn-sm btn-outline-danger w-100 d-inline-flex align-items-center justify-content-center gap-1'
                                               onclick=\"return confirm('Hapus gambar ini?')\">
                                                <i class='fa fa-trash'></i> Hapus
                                            </a>
                                        </div>
                                    </div>";
                                }
                            } else {
                                echo "<div class='col-12'><p class='text-muted small mb-0'>Belum ada foto galeri terhubung.</p></div>";
                            }
                            ?>
                        </div>
                    </div>

                    <hr style="border-color: var(--adm-border);">

                    <!-- TAMBAH FOTO BARU -->
                    <div class="mb-4">
                        <label class="form-label fw-semibold d-block" style="color: var(--adm-text);">Tambah Foto Baru</label>
                        <div id="uploadWrapper">
                            <div class="upload-item mb-3">
                                <input type="file" name="foto[]" class="form-control adm-input uploadInput" accept="image/*">
                                <div class="preview mt-2"></div>
                            </div>
                        </div>
                    </div>

                    <div class="d-flex gap-2 pt-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 Layanan
                        </button>
                        <button type="button" onclick="self.history.back()" class="btn btn-outline-secondary px-4">
                            Batal
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
    document.addEventListener('change', function(e) {
        if (!e.target.classList.contains('uploadInput')) return;

        const fileInput = e.target;
        const file = fileInput.files[0];
        if (!file || !file.type.startsWith('image/')) return;

        const reader = new FileReader();
        reader.onload = function(event) {
            const previewDiv = fileInput.nextElementSibling;
            previewDiv.innerHTML = `<img src="${event.target.result}" class="rounded border mt-1" style="max-width: 180px; height: auto;">`;

            const allInputs = document.querySelectorAll('.uploadInput');
            const lastInput = allInputs[allInputs.length - 1];

            if (fileInput === lastInput) {
                const uploadWrapper = document.getElementById('uploadWrapper');
                const newUpload = document.createElement('div');
                newUpload.classList.add('upload-item', 'mb-3');
                newUpload.innerHTML = `
                    <input type="file" name="foto[]" class="form-control adm-input uploadInput" accept="image/*">
                    <div class="preview mt-2"></div>
                `;
                uploadWrapper.appendChild(newUpload);
            }
        };
        reader.readAsDataURL(file);
    });
    </script>
<?php
    break;
}
?>