<?php
// mitra.php - Versi Elegan & Full Functional
// Fitur: Tampil, Tambah, Edit, Hapus, Import (.xlsx/.xls), Export, Pagination, Modal, Load desa via AJAX

// ------------------ 1) KONEKSI & LIB ------------------
include_once 'config/koneksi.php';
require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Supress mysqli warnings to avoid noise in UI
mysqli_report(MYSQLI_REPORT_OFF);

// ROLE / PERMISSION (sesuaikan session)
$is_admin = (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1) ? true : false;

// ------------------ 2) TAHUN AKTIF & FILTER ------------------
$result_t = $conn->query("SELECT id FROM tahun_aktif WHERE is_aktif = 1 LIMIT 1");
$tahun_aktif_id = ($result_t && $row_t = $result_t->fetch_assoc()) ? (int)$row_t['id'] : 0;
$filter_tahun = isset($_GET['f_tahun']) ? (int)$_GET['f_tahun'] : $tahun_aktif_id;
$allow_modify = ($filter_tahun == $tahun_aktif_id);

// ------------------ Pagination defaults ------------------
$per_page_default = 25;
$per_page_opts = [10,25,50,100, 'All'];
$per_page_raw = isset($_GET['per_page']) ? $_GET['per_page'] : $per_page_default;
if (in_array($per_page_raw, $per_page_opts, true)) {
    $per_page = ($per_page_raw === 'All') ? 0 : (int)$per_page_raw;
} else {
    $per_page = is_numeric($per_page_raw) ? (int)$per_page_raw : $per_page_default;
    if ($per_page < 0) $per_page = $per_page_default;
}
$page = isset($_GET['page']) && is_numeric($_GET['page']) && (int)$_GET['page'] > 0 ? (int)$_GET['page'] : 1;

// ------------------ 3) PROSES POST (CRUD, IMPORT, EXPORT) ------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {

    // ---- DOWNLOAD TEMPLATE ----
    if ($_POST['action'] === 'download_template') {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $headers = ['Nama', 'NIK', 'Email', 'No HP', 'ID Desa (Cek tabel wilayah)'];
        $col = 'A';
        foreach ($headers as $h) {
            $sheet->setCellValue($col . '1', $h);
            $sheet->getStyle($col . '1')->getFont()->setBold(true);
            $sheet->getColumnDimension($col)->setAutoSize(true);
            $col++;
        }
        
        $filename = "Template_Import_Mitra.xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit();
    }

    // ---- EXPORT ----
    if ($_POST['action'] === 'export') {
        $sql_ex = "SELECT m.*, w.kecamatan, w.kelurahan
                   FROM mitra m LEFT JOIN wilayahtugas w ON m.domisili_wilayah_id = w.id
                   WHERE m.tahun_aktif_id = $filter_tahun ORDER BY m.nama ASC";
        $res_ex = $conn->query($sql_ex);

        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        $headers = ['Nama', 'NIK', 'Email', 'No HP', 'Kecamatan', 'Kelurahan'];
        $col = 'A';
        foreach ($headers as $h) {
            $sheet->setCellValue($col . '1', $h);
            $sheet->getStyle($col . '1')->getFont()->setBold(true);
            $col++;
        }

        $row_num = 2;
        while ($r = $res_ex->fetch_assoc()) {
            $sheet->setCellValue('A' . $row_num, $r['nama']);
            $sheet->setCellValue('B' . $row_num, "'" . $r['nik']);
            $sheet->setCellValue('C' . $row_num, $r['alamat']); 
            $sheet->setCellValue('D' . $row_num, $r['no_hp']);
            $sheet->setCellValue('E' . $row_num, $r['kecamatan']);
            $sheet->setCellValue('F' . $row_num, $r['kelurahan']);
            $row_num++;
        }

        $filename = "Export_Mitra_" . date('Ymd') . ".xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit();
    }

    if ($is_admin) {
        // ----- ADD -----
        if ($_POST['action'] === 'add') {
            if (!$allow_modify) {
                $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Tahun bukan aktif!'];
            } else {
                $nama = isset($_POST['nama']) ? trim($conn->real_escape_string($_POST['nama'])) : '';
                $nik  = isset($_POST['nik']) ? trim($conn->real_escape_string($_POST['nik'])) : '';
                $alamat = isset($_POST['alamat']) ? trim($conn->real_escape_string($_POST['alamat'])) : '';
                $no_hp  = isset($_POST['no_hp']) ? trim($conn->real_escape_string($_POST['no_hp'])) : '';
                $desa_id = isset($_POST['domisili_wilayah_id']) ? (int)$_POST['domisili_wilayah_id'] : 0;

                if ($nama === '' || $nik === '') {
                    $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Nama dan NIK wajib diisi.'];
                } else {
                    $cek = $conn->query("SELECT id FROM mitra WHERE nik = '{$nik}' AND tahun_aktif_id = $tahun_aktif_id");
                    if ($cek->num_rows > 0) {
                        $_SESSION['msg'] = ['type' => 'danger', 'text' => "NIK $nik sudah terdaftar!"];
                    } else {
                        $stmt = $conn->prepare("INSERT INTO mitra (nama, nik, alamat, no_hp, domisili_wilayah_id, tahun_aktif_id) VALUES (?, ?, ?, ?, ?, ?)");
                        $ta = $tahun_aktif_id;
                        $stmt->bind_param("ssssii", $nama, $nik, $alamat, $no_hp, $desa_id, $ta);
                        if (@$stmt->execute()) {
                            $_SESSION['msg'] = ['type' => 'success', 'text' => 'Mitra ditambahkan.'];
                        } else {
                            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'DB error saat tambah.'];
                        }
                        $stmt->close();
                    }
                }
            }
        }

        // ----- EDIT -----
        if ($_POST['action'] === 'edit') {
            if (!$allow_modify) {
                $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Edit hanya tahun aktif!'];
            } else {
                $id = isset($_POST['mitra_id']) ? (int)$_POST['mitra_id'] : 0;
                $nama = isset($_POST['nama']) ? trim($_POST['nama']) : '';
                $nik  = isset($_POST['nik']) ? trim($_POST['nik']) : '';
                $alamat = isset($_POST['alamat']) ? trim($_POST['alamat']) : '';
                $no_hp  = isset($_POST['no_hp']) ? trim($_POST['no_hp']) : '';
                $desa_id = isset($_POST['domisili_wilayah_id']) ? (int)$_POST['domisili_wilayah_id'] : 0;
                $ta = $tahun_aktif_id;

                if ($id <= 0 || $nama === '' || $nik === '') {
                    $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Data tidak lengkap untuk update.'];
                } else {
                    $stmt = $conn->prepare("UPDATE mitra SET nama=?, nik=?, alamat=?, no_hp=?, domisili_wilayah_id=? WHERE id=? AND tahun_aktif_id=?");
                    $stmt->bind_param("ssssiii", $nama, $nik, $alamat, $no_hp, $desa_id, $id, $ta);
                    if (@$stmt->execute()) {
                        $_SESSION['msg'] = ['type' => 'success', 'text' => 'Mitra diperbarui.'];
                    } else {
                        $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal edit (DB error).'];
                    }
                    $stmt->close();
                }
            }
        }

        // ----- DELETE -----
        if ($_POST['action'] === 'delete') {
            if (!$allow_modify) {
                $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Hapus hanya tahun aktif!'];
            } else {
                $mid = isset($_POST['mitra_id']) ? (int)$_POST['mitra_id'] : 0;
                if ($mid > 0) {
                    $conn->query("DELETE FROM mitra WHERE id = $mid");
                    $_SESSION['msg'] = ['type' => 'success', 'text' => 'Mitra dihapus'];
                } else {
                    $_SESSION['msg'] = ['type' => 'danger', 'text' => 'ID mitra tidak valid'];
                }
            }
        }

        // ----- IMPORT -----
        if ($_POST['action'] === 'import') {
            if (!$allow_modify) {
                $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Import hanya tahun aktif!'];
            } else {
                if (!empty($_FILES['file_excel']['name'])) {
                    try {
                        $spreadsheet = IOFactory::load($_FILES['file_excel']['tmp_name']);
                        $data = $spreadsheet->getActiveSheet()->toArray();
                        $success = 0;
                        $failed_logs = [];

                        foreach ($data as $i => $row) {
                            if ($i == 0) continue; 
                            $nama = isset($row[0]) ? trim($conn->real_escape_string($row[0])) : '';
                            $nik  = isset($row[1]) ? trim($row[1]) : '';
                            $email = isset($row[2]) ? trim($conn->real_escape_string($row[2])) : '';
                            $nohp = isset($row[3]) ? trim($row[3]) : '';
                            $desa_id = (isset($row[4]) && $row[4] !== '' && $row[4] !== null) ? (int)$row[4] : 0;

                            if ($nama === '' || $nik === '' || $email === '' || $nohp === '') {
                                $failed_logs[] = ($nama ?: "TANPA_NAMA") . " (NIK: " . ($nik ?: "TANPA_NIK") . ") - data wajib kurang";
                                continue;
                            }

                            $cek = $conn->query("SELECT id FROM mitra WHERE nik = '" . $conn->real_escape_string($nik) . "' AND tahun_aktif_id = $tahun_aktif_id");
                            if ($cek->num_rows > 0) {
                                $failed_logs[] = "$nama (NIK:$nik) - duplikat";
                                continue;
                            }

                            $sql_ins = "INSERT INTO mitra (nama, nik, alamat, no_hp, domisili_wilayah_id, tahun_aktif_id)
                                        VALUES ('" . $conn->real_escape_string($nama) . "', '" . $conn->real_escape_string($nik) . "', 
                                        '" . $conn->real_escape_string($email) . "', '" . $conn->real_escape_string($nohp) . "', 
                                        $desa_id, $tahun_aktif_id)";
                            if (@$conn->query($sql_ins)) { $success++; } else { $failed_logs[] = "$nama (NIK:$nik) - db_error"; }
                        }
                        $_SESSION['msg'] = ['type' => 'info', 'text' => "Import selesai: Berhasil $success, Gagal " . count($failed_logs)];
                        $_SESSION['import_failed_logs'] = $failed_logs;
                    } catch (Exception $ex) {
                        $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Error: ' . $ex->getMessage()];
                    }
                }
            }
        }
    } 

    $qs = http_build_query(['f_tahun' => $filter_tahun, 'per_page' => ($per_page === 0 ? 'All' : $per_page), 'page' => 1]);
    header("Location: mitra.php?$qs");
    exit();
}

// ------------------ 4) AMBIL DATA UNTUK UI ------------------
$res_tahun_list = $conn->query("SELECT * FROM tahun_aktif ORDER BY tahun DESC");
$res_kec = $conn->query("SELECT kecamatan, MIN(id) as id_virtual FROM wilayahtugas GROUP BY kecamatan ORDER BY kecamatan ASC");

// Logic Pagination & Search
$where = "m.tahun_aktif_id = $filter_tahun";
$count_res = $conn->query("SELECT COUNT(*) AS cnt FROM mitra m WHERE $where");
$total_rows = $count_res->fetch_assoc()['cnt'];
$total_pages = $per_page > 0 ? ceil($total_rows / $per_page) : 1;
$offset = ($page - 1) * max(1, $per_page);
$limit_sql = $per_page > 0 ? " LIMIT $offset, $per_page" : "";

$sql = "SELECT m.*, w.kecamatan, w.kelurahan, (SELECT MIN(id) FROM wilayahtugas WHERE kecamatan = w.kecamatan) as kec_id_v 
        FROM mitra m LEFT JOIN wilayahtugas w ON m.domisili_wilayah_id = w.id 
        WHERE $where ORDER BY m.nama ASC $limit_sql";
$res = $conn->query($sql);

include_once 'header.php';
?>

<style>
    :root { --soft-bg: #f8f9fa; --border-color: #f1f1f1; }
    .card-modern { border: none; box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); border-radius: 0.75rem; }
    .table thead th { 
        background-color: var(--soft-bg); color: #6c757d; font-weight: 600; 
        text-transform: uppercase; font-size: 0.75rem; letter-spacing: 0.025em;
        border-top: none; padding: 12px 15px; 
    }
    .table tbody td { padding: 15px; vertical-align: middle; border-color: var(--border-color); }
    .table-hover tbody tr:hover { background-color: #fcfcfc; transition: 0.2s; }
    .btn-action { width: 32px; height: 32px; padding: 0; display: inline-flex; align-items: center; justify-content: center; border-radius: 0.5rem; transition: 0.2s; }
    .info-label { font-size: 0.7rem; color: #adb5bd; font-weight: bold; margin-bottom: -2px; }
    .badge-domisili { background-color: #f8f9fa; border: 1px solid #dee2e6; color: #495057; font-weight: 400; padding: 5px 10px; border-radius: 6px; font-size: 0.85rem; }
</style>

<div class="container-fluid py-4">
    <?php if (isset($_SESSION['msg'])): ?>
        <div class="alert alert-<?= $_SESSION['msg']['type'] ?> alert-dismissible fade show shadow-sm border-0" role="alert">
            <?= $_SESSION['msg']['text'] ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['msg']); ?>
    <?php endif; ?>

    <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center mb-4 gap-3">
        <div>
            <h4 class="fw-bold mb-0 text-dark">Database Mitra</h4>
            <p class="text-muted small mb-0">Manajemen data mitra tahun anggaran aktif</p>
        </div>
        <div class="d-flex gap-2">
            <form method="POST" class="d-inline">
                <input type="hidden" name="action" value="export">
                <button type="submit" class="btn btn-white border shadow-sm btn-sm px-3"><i class="bi bi-download me-1"></i> Ekspor</button>
            </form>
            <?php if ($is_admin && $allow_modify): ?>
                <button class="btn btn-info text-white shadow-sm btn-sm px-3" data-bs-toggle="modal" data-bs-target="#importModal"><i class="bi bi-file-earmark-arrow-up me-1"></i> Impor</button>
                <button class="btn btn-primary shadow-sm btn-sm px-3" data-bs-toggle="modal" data-bs-target="#addModal"><i class="bi bi-plus-lg me-1"></i> Tambah</button>
            <?php endif; ?>
        </div>
    </div>

    <div class="card card-modern mb-3">
        <div class="card-body p-3">
            <form method="GET" class="row g-2 align-items-center">
                <div class="col-auto d-flex align-items-center">
                    <label class="small fw-bold text-muted me-2">TAHUN:</label>
                    <select name="f_tahun" class="form-select form-select-sm border-0 bg-light px-3" onchange="this.form.submit()" style="width: 150px;">
                        <?php while ($t = $res_tahun_list->fetch_assoc()): ?>
                            <option value="<?= $t['id'] ?>" <?= ($t['id'] == $filter_tahun) ? 'selected' : '' ?>>
                                <?= $t['tahun'] ?> <?= ($t['is_aktif'] ? '(Aktif)' : '') ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-auto ms-auto d-flex align-items-center">
                    <label class="small fw-bold text-muted me-2">TAMPILKAN:</label>
                    <select name="per_page" class="form-select form-select-sm border-0 bg-light px-3" onchange="this.form.submit()">
                        <?php foreach ($per_page_opts as $opt): ?>
                            <option value="<?= $opt ?>" <?= ($per_page_raw == $opt) ? 'selected' : '' ?>><?= $opt ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>
        </div>
    </div>

    <div class="card card-modern">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th class="ps-4">Nama Mitra</th>
                        <th>Identitas (NIK)</th>
                        <th>Kontak & Email</th>
                        <th>Domisili Tugas</th>
                        <?php if ($is_admin): ?><th class="text-center pe-4">Aksi</th><?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($res && $res->num_rows > 0): ?>
                        <?php while ($row = $res->fetch_assoc()): ?>
                        <tr>
                            <td class="ps-4">
                                <div class="fw-bold text-dark"><?= htmlspecialchars($row['nama']) ?></div>
                                <div class="text-muted" style="font-size: 0.75rem;">ID Mitra: #<?= $row['id'] ?></div>
                            </td>
                            <td><code class="text-dark fw-bold" style="font-size: 0.9rem;"><?= htmlspecialchars($row['nik']) ?></code></td>
                            <td>
                                <div class="info-label">EMAIL</div>
                                <div class="small mb-1 text-dark"><?= htmlspecialchars($row['alamat']) ?></div>
                                <div class="info-label">NO. WHATSAPP</div>
                                <div class="small text-dark"><?= htmlspecialchars($row['no_hp']) ?></div>
                            </td>
                            <td>
                                <?php if($row['kecamatan']): ?>
                                    <div class="badge-domisili">
                                        <i class="bi bi-geo-alt-fill text-danger me-1 small"></i>
                                        Kec. <?= htmlspecialchars($row['kecamatan']) ?> - <?= htmlspecialchars($row['kelurahan']) ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted small italic">Belum ditentukan</span>
                                <?php endif; ?>
                            </td>
                            <?php if ($is_admin): ?>
                            <td class="text-center pe-4">
                                <?php if ($allow_modify): ?>
                                    <button class="btn btn-outline-warning btn-action edit-btn me-1" 
                                        data-bs-toggle="modal" data-bs-target="#editModal"
                                        data-id="<?= $row['id'] ?>" 
                                        data-nama="<?= htmlspecialchars($row['nama']) ?>"
                                        data-nik="<?= htmlspecialchars($row['nik']) ?>" 
                                        data-alamat="<?= htmlspecialchars($row['alamat']) ?>"
                                        data-nohp="<?= htmlspecialchars($row['no_hp']) ?>" 
                                        data-desa="<?= $row['domisili_wilayah_id'] ?>"
                                        data-kec="<?= $row['kec_id_v'] ?>">
                                        <i class="bi bi-pencil-square"></i>
                                    </button>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Hapus mitra <?= htmlspecialchars($row['nama']) ?>?')">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="mitra_id" value="<?= $row['id'] ?>">
                                        <button type="submit" class="btn btn-outline-danger btn-action"><i class="bi bi-trash"></i></button>
                                    </form>
                                <?php else: ?>
                                    <span class="badge bg-light text-muted fw-normal border">Read Only</span>
                                <?php endif; ?>
                            </td>
                            <?php endif; ?>
                        </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr><td colspan="5" class="text-center py-5 text-muted">Tidak ada data mitra untuk tahun ini.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php if ($total_pages > 1): ?>
        <div class="card-footer bg-white border-0 py-3">
            <nav aria-label="Page navigation">
                <ul class="pagination pagination-sm justify-content-center mb-0">
                    <?php for($i=1; $i<=$total_pages; $i++): ?>
                        <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                            <a class="page-link" href="?f_tahun=<?= $filter_tahun ?>&per_page=<?= $per_page_raw ?>&page=<?= $i ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="POST" class="modal-content border-0 shadow">
            <input type="hidden" name="action" value="add">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold">Tambah Mitra Baru</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Nama Lengkap</label>
                        <input type="text" name="nama" class="form-control" placeholder="Nama sesuai KTP" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">NIK</label>
                        <input type="text" name="nik" class="form-control" placeholder="16 Digit Nomor Induk" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Email</label>
                        <input type="email" name="alamat" class="form-control" placeholder="alamat@email.com">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">No. HP / WhatsApp</label>
                        <input type="text" name="no_hp" class="form-control" placeholder="08xxxxxxxx">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Kecamatan Domisili</label>
                        <select id="add_kec" class="form-select bg-light border-0">
                            <option value="">-- Pilih Kecamatan --</option>
                            <?php 
                            $res_kec->data_seek(0);
                            while($rk = $res_kec->fetch_assoc()): ?>
                                <option value="<?= $rk['id_virtual'] ?>"><?= $rk['kecamatan'] ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Desa/Kelurahan</label>
                        <select name="domisili_wilayah_id" id="add_desa" class="form-select bg-light border-0">
                            <option value="0">-- Pilih Kecamatan Dahulu --</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                <button type="submit" class="btn btn-primary px-4">Simpan Data</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="POST" class="modal-content border-0 shadow">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" name="mitra_id" id="e_id">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title fw-bold">Update Data Mitra</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="row g-3">
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Nama Lengkap</label>
                        <input type="text" name="nama" id="e_nama" class="form-control" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">NIK</label>
                        <input type="text" name="nik" id="e_nik" class="form-control" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Email</label>
                        <input type="email" name="alamat" id="e_alamat" class="form-control">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">No. HP / WhatsApp</label>
                        <input type="text" name="no_hp" id="e_nohp" class="form-control">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Kecamatan</label>
                        <select id="e_kec" class="form-select bg-light border-0">
                            <option value="">-- Pilih Kecamatan --</option>
                            <?php 
                            $res_kec->data_seek(0);
                            while($rk = $res_kec->fetch_assoc()): ?>
                                <option value="<?= $rk['id_virtual'] ?>"><?= $rk['kecamatan'] ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label small fw-bold">Desa/Kelurahan</label>
                        <select name="domisili_wilayah_id" id="e_desa" class="form-select bg-light border-0">
                            <option value="0">-- Pilih Desa --</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="modal-footer border-0">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                <button type="submit" class="btn btn-warning px-4">Update Data</button>
            </div>
        </form>
    </div>
</div>

<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-bold">Impor via Excel</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body px-4">
                <div class="p-3 bg-light rounded-3 mb-4">
                    <h6 class="fw-bold small mb-2"><i class="bi bi-info-circle me-1"></i> Instruksi:</h6>
                    <p class="small text-muted mb-3">Gunakan template resmi untuk menghindari error format kolom.</p>
                    <form method="POST">
                        <input type="hidden" name="action" value="download_template">
                        <button type="submit" class="btn btn-sm btn-outline-primary w-100">
                            <i class="bi bi-file-earmark-excel me-1"></i> Download Template .xlsx
                        </button>
                    </form>
                </div>
                
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="import">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Pilih File Excel</label>
                        <input type="file" name="file_excel" class="form-control" accept=".xlsx,.xls" required>
                    </div>
                    <button type="submit" class="btn btn-info text-white w-100 py-2">Mulai Impor Data</button>
                </form>
            </div>
            <div class="modal-footer border-0"></div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    function loadDesa(kecId, targetId, selectedId = null) {
        const el = document.getElementById(targetId);
        if (!el) return;
        el.innerHTML = '<option value="">Memuat...</option>';
        
        fetch('get_desa.php?kec_id=' + encodeURIComponent(kecId))
            .then(r => r.json())
            .then(data => {
                el.innerHTML = '<option value="0">-- Pilih Desa --</option>';
                if (Array.isArray(data) && data.length > 0) {
                    data.forEach(d => {
                        const opt = document.createElement('option');
                        opt.value = d.id;
                        opt.text = d.nama_desa || d.nama || d.kelurahan || 'Desa';
                        if (selectedId && String(d.id) === String(selectedId)) opt.selected = true;
                        el.appendChild(opt);
                    });
                } else {
                    el.innerHTML = '<option value="0">-- Tidak ada data desa --</option>';
                }
            })
            .catch(err => {
                el.innerHTML = '<option value="0">-- Gagal memuat --</option>';
            });
    }

    const addKec = document.getElementById('add_kec');
    if (addKec) {
        addKec.addEventListener('change', function() { loadDesa(this.value, 'add_desa'); });
    }

    const eKec = document.getElementById('e_kec');
    if (eKec) {
        eKec.addEventListener('change', function() { loadDesa(this.value, 'e_desa'); });
    }

    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const ds = this.dataset;
            document.getElementById('e_id').value = ds.id;
            document.getElementById('e_nama').value = ds.nama;
            document.getElementById('e_nik').value = ds.nik;
            document.getElementById('e_alamat').value = ds.alamat;
            document.getElementById('e_nohp').value = ds.nohp;

            if (ds.kec) {
                document.getElementById('e_kec').value = ds.kec;
                loadDesa(ds.kec, 'e_desa', ds.desa);
            }
        });
    });
});
</script>

<?php include_once 'footer.php'; ?>