<?php
require_once 'db.php';

session_start();
if(!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
$instansi_id = $_SESSION['instansi_id'] ?? 1; 

// Ambil data instansi
$stmt_inst = $pdo->prepare("SELECT nama_instansi, logo_path FROM instansi WHERE id = ?");
$stmt_inst->execute([$instansi_id]);
$inst_data = $stmt_inst->fetch(PDO::FETCH_ASSOC);
$nama_instansi = $inst_data['nama_instansi'] ?? "Instansi ID $instansi_id";
$logo_path = !empty($inst_data['logo_path']) ? $inst_data['logo_path'] : '';

$msg = '';
if (isset($_GET['msg'])) {
    $msg = "<div class='alert alert-success alert-dismissible fade show' role='alert'>" . htmlspecialchars($_GET['msg']) . "<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
}

// Handle CRUD Operations
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action']) && $_POST['action'] == 'add') {
        $nama_skpd = trim($_POST['nama_skpd']);
        $singkatan = trim($_POST['singkatan']);
        $keywords = trim($_POST['keywords']);
        $kontak_wa = trim($_POST['kontak_wa']);
        $email = trim($_POST['email']);
        $status = $_POST['status'] ?? 'aktif';

        $stmt = $pdo->prepare("INSERT INTO skpd (instansi_id, nama_skpd, singkatan, keywords, kontak_wa, email, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
        if ($stmt->execute([$instansi_id, $nama_skpd, $singkatan, $keywords, $kontak_wa, $email, $status])) {
            $msg = "<div class='alert alert-success alert-dismissible fade show'>Data SKPD berhasil ditambahkan.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
        }
    } elseif (isset($_POST['action']) && $_POST['action'] == 'edit') {
        $id = (int)$_POST['id'];
        $nama_skpd = trim($_POST['nama_skpd']);
        $singkatan = trim($_POST['singkatan']);
        $keywords = trim($_POST['keywords']);
        $kontak_wa = trim($_POST['kontak_wa']);
        $email = trim($_POST['email']);
        $status = $_POST['status'] ?? 'aktif';

        $stmt = $pdo->prepare("UPDATE skpd SET nama_skpd = ?, singkatan = ?, keywords = ?, kontak_wa = ?, email = ?, status = ? WHERE id = ? AND instansi_id = ?");
        if ($stmt->execute([$nama_skpd, $singkatan, $keywords, $kontak_wa, $email, $status, $id, $instansi_id])) {
            $msg = "<div class='alert alert-success alert-dismissible fade show'>Data SKPD berhasil diperbarui.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
        }
    } elseif (isset($_POST['action']) && $_POST['action'] == 'delete') {
        $id = (int)$_POST['id'];
        if ($id > 0) {
            $stmt = $pdo->prepare("DELETE FROM skpd WHERE id = ? AND instansi_id = ?");
            if ($stmt->execute([$id, $instansi_id])) {
                $msg = "<div class='alert alert-success alert-dismissible fade show'>Data SKPD berhasil dihapus.<button type='button' class='btn-close' data-bs-dismiss='alert'></button></div>";
            }
        }
    }
}

// Ambil daftar SKPD
$stmt_skpd = $pdo->prepare("SELECT * FROM skpd WHERE instansi_id = ? ORDER BY nama_skpd ASC");
$stmt_skpd->execute([$instansi_id]);
$skpd_list = $stmt_skpd->fetchAll(PDO::FETCH_ASSOC);

require_once 'layout_header.php';
?>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="row">
            <div class="col-md-12 grid-margin stretch-card">
                <div class="card shadow-sm border-0 rounded-4">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
                            <div>
                                <h4 class="card-title fw-bold text-dark mb-1">
                                    <i class="fa-solid fa-building-flag text-primary me-2"></i>Master Data SKPD (Perangkat Daerah)
                                </h4>
                                <p class="card-description text-muted mb-0">
                                    Kelola daftar SKPD, pemetaan kata kunci pemicu berita negatif, serta kontak penanggung jawab warning.
                                </p>
                            </div>
                            <div class="d-flex gap-2">
                                <a href="seeder_skpd.php" class="btn btn-warning text-white fw-bold rounded-3 px-3 shadow-sm btn-seeder">
                                    <i class="fa-solid fa-bolt me-1"></i> Isi SKPD Standar Pemda
                                </a>
                                <button class="btn btn-primary fw-bold rounded-3 px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#modalAddSKPD">
                                    <i class="fa-solid fa-plus me-1"></i> Tambah SKPD
                                </button>
                            </div>
                        </div>

                        <?= $msg ?>

                        <div class="table-responsive">
                            <table id="tableSKPD" class="table table-hover align-middle">
                                <thead class="table-light">
                                    <tr>
                                        <th style="width: 50px;">No</th>
                                        <th>Nama SKPD</th>
                                        <th>Singkatan</th>
                                        <th>Kata Kunci Pemicu Berita</th>
                                        <th>Kontak WA</th>
                                        <th>Status</th>
                                        <th style="width: 120px;" class="text-center">Aksi</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if(empty($skpd_list)): ?>
                                        <tr>
                                            <td colspan="7" class="text-center py-4 text-muted">
                                                <i class="fa-solid fa-folder-open display-6 d-block mb-2 text-secondary"></i>
                                                Belum ada data SKPD. Klik tombol <strong>"Isi SKPD Standar Pemda"</strong> di atas untuk mengisi 35+ SKPD secara otomatis.
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php $no = 1; foreach($skpd_list as $s): ?>
                                            <tr>
                                                <td><?= $no++ ?></td>
                                                <td>
                                                    <span class="fw-bold text-dark"><?= htmlspecialchars($s['nama_skpd']) ?></span>
                                                </td>
                                                <td>
                                                    <span class="badge bg-secondary rounded-pill px-3"><?= htmlspecialchars($s['singkatan'] ?? '-') ?></span>
                                                </td>
                                                <td>
                                                    <small class="text-muted d-block" style="max-width: 320px; white-space: normal; line-height: 1.4;">
                                                        <?= htmlspecialchars($s['keywords'] ?? '-') ?>
                                                    </small>
                                                </td>
                                                <td>
                                                    <?php if(!empty($s['kontak_wa'])): ?>
                                                        <a href="https://wa.me/<?= preg_replace('/[^0-9]/', '', $s['kontak_wa']) ?>" target="_blank" class="text-success text-decoration-none fw-bold">
                                                            <i class="fa-brands fa-whatsapp me-1"></i><?= htmlspecialchars($s['kontak_wa']) ?>
                                                        </a>
                                                    <?php else: ?>
                                                        <span class="text-muted small">Belum diisi</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if(($s['status'] ?? 'aktif') === 'aktif'): ?>
                                                        <span class="badge bg-success bg-opacity-10 text-success fw-bold rounded-pill px-3">Aktif</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-danger bg-opacity-10 text-danger fw-bold rounded-pill px-3">Nonaktif</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="text-center">
                                                    <button class="btn btn-sm btn-outline-primary rounded-circle p-2 me-1 btn-edit" 
                                                            data-id="<?= $s['id'] ?>"
                                                            data-nama="<?= htmlspecialchars($s['nama_skpd']) ?>"
                                                            data-singkatan="<?= htmlspecialchars($s['singkatan'] ?? '') ?>"
                                                            data-keywords="<?= htmlspecialchars($s['keywords'] ?? '') ?>"
                                                            data-wa="<?= htmlspecialchars($s['kontak_wa'] ?? '') ?>"
                                                            data-email="<?= htmlspecialchars($s['email'] ?? '') ?>"
                                                            data-status="<?= htmlspecialchars($s['status'] ?? 'aktif') ?>"
                                                            title="Edit">
                                                        <i class="fa-solid fa-pen"></i>
                                                    </button>
                                                    <form method="POST" class="d-inline form-delete">
                                                        <input type="hidden" name="action" value="delete">
                                                        <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                                        <button type="button" class="btn btn-sm btn-outline-danger rounded-circle p-2 btn-del-trigger" title="Hapus">
                                                            <i class="fa-solid fa-trash"></i>
                                                        </button>
                                                    </form>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Add SKPD -->
    <div class="modal fade" id="modalAddSKPD" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content rounded-4 border-0">
                <form method="POST">
                    <input type="hidden" name="action" value="add">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold"><i class="fa-solid fa-building-flag me-2 text-primary"></i>Tambah SKPD Baru</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Nama SKPD / Perangkat Daerah</label>
                            <input type="text" name="nama_skpd" class="form-control rounded-3" placeholder="Contoh: Dinas Pekerjaan Umum dan Penataan Ruang" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Singkatan</label>
                            <input type="text" name="singkatan" class="form-control rounded-3" placeholder="Contoh: Dinas PUPR">
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Kata Kunci Pemicu Berita (Pisahkan dengan koma)</label>
                            <textarea name="keywords" class="form-control rounded-3" rows="3" placeholder="Contoh: jalan rusak, drainase, banjir, jembatan"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">No. WhatsApp Admin SKPD</label>
                                <input type="text" name="kontak_wa" class="form-control rounded-3" placeholder="08123456789">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Email Humas SKPD</label>
                                <input type="email" name="email" class="form-control rounded-3" placeholder="humas@skpd.go.id">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light rounded-3" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary fw-bold rounded-3">Simpan SKPD</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Modal Edit SKPD -->
    <div class="modal fade" id="modalEditSKPD" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content rounded-4 border-0">
                <form method="POST">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="modal-header">
                        <h5 class="modal-title fw-bold"><i class="fa-solid fa-pen-to-square me-2 text-primary"></i>Edit Data SKPD</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label fw-bold">Nama SKPD / Perangkat Daerah</label>
                            <input type="text" name="nama_skpd" id="edit_nama_skpd" class="form-control rounded-3" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Singkatan</label>
                            <input type="text" name="singkatan" id="edit_singkatan" class="form-control rounded-3">
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Kata Kunci Pemicu Berita (Pisahkan dengan koma)</label>
                            <textarea name="keywords" id="edit_keywords" class="form-control rounded-3" rows="3"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">No. WhatsApp Admin SKPD</label>
                                <input type="text" name="kontak_wa" id="edit_kontak_wa" class="form-control rounded-3">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-bold">Email Humas SKPD</label>
                                <input type="email" name="email" id="edit_email" class="form-control rounded-3">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-bold">Status SKPD</label>
                            <select name="status" id="edit_status" class="form-select rounded-3">
                                <option value="aktif">Aktif</option>
                                <option value="nonaktif">Nonaktif</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light rounded-3" data-bs-dismiss="modal">Batal</button>
                        <button type="submit" class="btn btn-primary fw-bold rounded-3">Update SKPD</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

<?php require_once 'layout_footer.php'; ?>

<script>
$(document).ready(function() {
    $('#tableSKPD').DataTable({
        "language": {
            "search": "Cari SKPD / Keyword:",
            "lengthMenu": "Tampilkan _MENU_ baris",
            "info": "Menampilkan _START_ sampai _END_ dari _TOTAL_ SKPD",
            "paginate": {
                "next": "<i class='fa-solid fa-chevron-right'></i>",
                "previous": "<i class='fa-solid fa-chevron-left'></i>"
            }
        }
    });

    // Handle Click Edit
    $('.btn-edit').on('click', function() {
        $('#edit_id').val($(this).data('id'));
        $('#edit_nama_skpd').val($(this).data('nama'));
        $('#edit_singkatan').val($(this).data('singkatan'));
        $('#edit_keywords').val($(this).data('keywords'));
        $('#edit_kontak_wa').val($(this).data('wa'));
        $('#edit_email').val($(this).data('email'));
        $('#edit_status').val($(this).data('status'));
        $('#modalEditSKPD').modal('show');
    });

    // Confirm Delete
    $('.btn-del-trigger').on('click', function() {
        const form = $(this).closest('.form-delete');
        Swal.fire({
            title: 'Hapus SKPD?',
            text: "Data SKPD yang dihapus tidak dapat dikembalikan.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Ya, Hapus!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                form.submit();
            }
        });
    });

    // Confirm Seeder Run
    $('.btn-seeder').on('click', function(e) {
        e.preventDefault();
        const targetUrl = $(this).attr('href');
        Swal.fire({
            title: 'Jalankan Seeder SKPD Standar Pemda?',
            text: "Sistem akan memasukkan/memperbarui 35+ daftar SKPD standar beserta kata kunci dasarnya.",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#ffc107',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Jalankan Seeder!',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = targetUrl;
            }
        });
    });
});
</script>
