<?php
// alokasi_mitra.php (Halaman Khusus Alokasi Mitra) - Versi copy-repair + fitur sorting mitra by distance
include_once 'header.php';
include_once 'config/koneksi.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}


// Fungsi getTahunAktifId() diasumsikan ada di file yang di-include
if (!function_exists('getTahunAktifId')) {
    function getTahunAktifId($conn) {
        $result = $conn->query("SELECT id, tahun FROM tahun_aktif WHERE is_aktif = 1 LIMIT 1");
        return $result && $result->num_rows > 0 ? $result->fetch_assoc()['id'] : null;
    }
}

$tahun_aktif_id = getTahunAktifId($conn);

// Menggunakan variabel sesi untuk pesan
if (!isset($_SESSION['msg'])) {
    $_SESSION['msg'] = ['type' => '', 'text' => ''];
}

// --------------------------------------------------------------------------
// --- AMBIL DATA MASTER UNTUK FUNGSI CRUD (HARGA, TANGGAL) ---
// --------------------------------------------------------------------------
$nama_aktivitas_master_data = [];
$nama_aktivitas_options = [];

if ($tahun_aktif_id) {
    $sql_aktivitas_master_all = "
        SELECT
            NAM.id, NAM.nama_aktivitas, NAM.satuan_bayar, NAM.harga_satuan, 
            NAM.jenis_kegiatan, NAM.tgl_mulai, NAM.tgl_selesai 
        FROM 
            nama_aktivitas_master NAM
        JOIN detail_kegiatan DK ON NAM.detail_kegiatan_id = DK.id
        JOIN subkomponen SK ON DK.subkomponen_id = SK.id
        WHERE 
            SK.tahun_aktif_id = ?
        ORDER BY 
            NAM.nama_aktivitas ASC";
    
    $stmt_master = $conn->prepare($sql_aktivitas_master_all);
    $stmt_master->bind_param("i", $tahun_aktif_id);
    $stmt_master->execute();
    $result_aktivitas_master_all = $stmt_master->get_result();
    
    if ($result_aktivitas_master_all) {
        while ($row = $result_aktivitas_master_all->fetch_assoc()) {
            $nama_aktivitas_master_data[$row['id']] = $row;
        }
    }
    $stmt_master->close();
}

$nama_aktivitas_options = array_values($nama_aktivitas_master_data);

function getAktivitasMasterData($id, $data_array) {
    return $data_array[$id] ?? null;
}

// --------------------------------------------------------------------------
// --- 1. FUNGSI CREATE (Tambah Aktivitas) ---
// --------------------------------------------------------------------------
if (isset($_POST['add_aktivitas'])) {
    if (!$tahun_aktif_id) {
        $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Silakan atur Tahun Aktif terlebih dahulu.'];
    } else {
        $mitra_id = intval($_POST['mitra_id']);
        $nama_aktivitas_id = intval($_POST['nama_aktivitas_id']);
        $beban_kerja = intval($_POST['beban_kerja']);    
        $jumlah_honor = floatval($_POST['jumlah_honor']);
        $wilayah_tugas_id = !empty($_POST['wilayah_desa_id']) ? $_POST['wilayah_desa_id'] : NULL;  
        $tahun_aktif_id_insert = $tahun_aktif_id;    

        $master_data = getAktivitasMasterData($nama_aktivitas_id, $nama_aktivitas_master_data);
        
        if ($nama_aktivitas_id <= 0 || $beban_kerja <= 0 || $jumlah_honor < 0 || !$master_data) {
            $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Nama Kegiatan, Beban Kerja, dan Honor wajib diisi dengan benar.'];
        } else {
            $sql = "INSERT INTO aktivitas_kerja (mitra_id, nama_aktivitas_id, beban_kerja, jumlah_honor, wilayah_tugas_id, tahun_aktif_id) VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $param_types = "iiidsi";
            $stmt->bind_param($param_types, $mitra_id, $nama_aktivitas_id, $beban_kerja, $jumlah_honor, $wilayah_tugas_id, $tahun_aktif_id_insert);
            
            if ($stmt->execute()) {
                $_SESSION['msg'] = ['type' => 'success', 'text' => 'Aktivitas kerja berhasil dialokasikan.'];
            } else {
                $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal mengalokasikan aktivitas: ' . $stmt->error];
            }
            $stmt->close();
        }
    }
    header("Location: alokasi_mitra.php");
    exit();
}

// --------------------------------------------------------------------------
// --- 2. FUNGSI UPDATE (Edit Aktivitas) ---
// --------------------------------------------------------------------------
if (isset($_POST['edit_aktivitas'])) {
    $id = intval($_POST['aktivitas_id']);
    $mitra_id = intval($_POST['edit_mitra_id']);
    $nama_aktivitas_id = intval($_POST['edit_nama_aktivitas_id']);
    $beban_kerja = intval($_POST['edit_beban_kerja']);    
    $jumlah_honor = floatval($_POST['edit_jumlah_honor']);
    $wilayah_tugas_id = !empty($_POST['edit_wilayah_desa_id']) ? $_POST['edit_wilayah_desa_id'] : NULL;    

    $sql = "UPDATE aktivitas_kerja SET mitra_id=?, nama_aktivitas_id=?, beban_kerja=?, jumlah_honor=?, wilayah_tugas_id=? WHERE id=?";
    $stmt = $conn->prepare($sql);
    $param_types = "iiidsi";
    $stmt->bind_param($param_types, $mitra_id, $nama_aktivitas_id, $beban_kerja, $jumlah_honor, $wilayah_tugas_id, $id);

    if ($stmt->execute()) {
        $_SESSION['msg'] = ['type' => 'success', 'text' => 'Aktivitas kerja berhasil diperbarui.'];
    } else {
        $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal memperbarui aktivitas: ' . $stmt->error];
    }
    $stmt->close();
    header("Location: alokasi_mitra.php");
    exit();
}

// --------------------------------------------------------------------------
// --- 3. FUNGSI DELETE (Hapus Aktivitas) ---
// --------------------------------------------------------------------------
if (isset($_GET['delete_id'])) {
    $id = intval($_GET['delete_id']);
    $sql = "DELETE FROM aktivitas_kerja WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        $_SESSION['msg'] = ['type' => 'success', 'text' => 'Aktivitas kerja berhasil dihapus.'];
    } else {
        $_SESSION['msg'] = ['type' => 'danger', 'text' => 'Gagal menghapus aktivitas: ' . $stmt->error];
    }
    $stmt->close();
    header("Location: alokasi_mitra.php");
    exit();
}

// --------------------------------------------------------------------------
// --- 4. FUNGSI READ (Ambil Data untuk Dropdown dan Tabel) ---
// --------------------------------------------------------------------------

// --- AMBIL DATA MITRA (DEFAULT) ---
$mitra_options = [];
if ($tahun_aktif_id) {
    $sql_mitra = "SELECT id, nama FROM mitra WHERE tahun_aktif_id = ? ORDER BY nama ASC";
    $stmt_m = $conn->prepare($sql_mitra);
    $stmt_m->bind_param("i", $tahun_aktif_id);
    $stmt_m->execute();
    $res_m = $stmt_m->get_result();
    if ($res_m) {
        while ($row = $res_m->fetch_assoc()) {
            $mitra_options[] = $row;
        }
    }
    $stmt_m->close();
}

// --- AMBIL DATA KECAMATAN (LOGIKA 7 DIGIT ID) ---
$kecamatan_options = [];
$sql_kecamatan = "
    SELECT 
        SUBSTRING(id, 1, 7) AS kode_kecamatan_unik,
        MAX(kecamatan) AS nama_kecamatan,
        MIN(id) AS id_kecamatan_virtual
    FROM 
        wilayahtugas
    GROUP BY 
        kode_kecamatan_unik
    ORDER BY 
        nama_kecamatan ASC";
    
$result_kecamatan = $conn->query($sql_kecamatan);

if ($result_kecamatan) {
    while ($row = $result_kecamatan->fetch_assoc()) {
        $kecamatan_options[] = ['id' => $row['id_kecamatan_virtual'], 'nama_kecamatan' => $row['nama_kecamatan']];
    }
}

// --- AMBIL DATA ALOKASI AKTIVITAS KERJA (dengan JOIN Wilayah) ---
$aktivitas_data = [];
if ($tahun_aktif_id) {
    $sql_aktivitas = "
        SELECT
            ak.id, ak.mitra_id, ak.nama_aktivitas_id, ak.beban_kerja, m.nama AS nama_mitra,
            nam.nama_aktivitas, nam.satuan_bayar, nam.harga_satuan, 
            nam.jenis_kegiatan, nam.tgl_mulai AS tgl_mulai, nam.tgl_selesai AS tgl_selesai, 
            ak.jumlah_honor, 
            ak.wilayah_tugas_id, 
            wt.kelurahan AS nama_desa, 
            wt.kecamatan AS nama_kecamatan, 
            (SELECT MIN(id) FROM wilayahtugas WHERE SUBSTRING(id, 1, 7) = SUBSTRING(wt.id, 1, 7)) AS kecamatan_id
        FROM aktivitas_kerja ak
        JOIN mitra m ON ak.mitra_id = m.id
        JOIN nama_aktivitas_master nam ON ak.nama_aktivitas_id = nam.id
        LEFT JOIN wilayahtugas wt ON ak.wilayah_tugas_id = wt.id 
        WHERE ak.tahun_aktif_id = ? 
        ORDER BY ak.id DESC";

    $stmt_read = $conn->prepare($sql_aktivitas);
    $stmt_read->bind_param("i", $tahun_aktif_id);
    $stmt_read->execute();
    $result_aktivitas = $stmt_read->get_result();

    if ($result_aktivitas) {
        while ($row = $result_aktivitas->fetch_assoc()) {
            $aktivitas_data[] = $row;
        }
    }
    $stmt_read->close();
}

// Ambil pesan dari session dan hapus
$msg_type = $_SESSION['msg']['type'] ?? '';
$msg_content = $_SESSION['msg']['text'] ?? '';
unset($_SESSION['msg']);

// Mendapatkan nilai tahun aktif untuk ditampilkan
$tahun_aktif_display = '';
if ($tahun_aktif_id) {
    $tahun_query = $conn->query("SELECT tahun FROM tahun_aktif WHERE id = {$tahun_aktif_id}");
    if ($tahun_query && $tahun_row = $tahun_query->fetch_assoc()) {
        $tahun_aktif_display = htmlspecialchars($tahun_row['tahun']);
    }
}
?>

<div class="container-fluid pt-3"> 
    <h2 class="mt-0"><i class="bi bi-person-workspace"></i> Alokasi Mitra Kerja</h2>
    <h5 class="text-primary">Tahun Aktif: <?php echo $tahun_aktif_display; ?></h5>
    <hr>

    <?php if ($msg_content): ?>
        <div class="alert alert-<?php echo ($msg_type == 'success' ? 'success' : 'danger'); ?> alert-dismissible fade show" role="alert">
            <?php echo $msg_content; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <div class="card p-4 mb-4 shadow-sm">
        <h4>Input Alokasi Baru</h4>
        <form method="POST" action="alokasi_mitra.php" id="form_alokasi">
            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="nama_aktivitas_id" class="form-label">Aktivitas(Master)</label>
                    <select class="form-select" id="nama_aktivitas_id" name="nama_aktivitas_id" required>
                        <option value="" data-harga="0" data-jenis="" data-mulai="" data-selesai="">-- Pilih Aktivitas --</option>
                        <?php foreach ($nama_aktivitas_options as $akt): ?>
                            <option 
                                value="<?php echo $akt['id']; ?>" 
                                data-harga="<?php echo $akt['harga_satuan']; ?>"
                                data-satuan="<?php echo htmlspecialchars($akt['satuan_bayar']); ?>"
                                data-jenis="<?php echo htmlspecialchars($akt['jenis_kegiatan']); ?>"
                                data-mulai="<?php echo htmlspecialchars($akt['tgl_mulai']); ?>"
                                data-selesai="<?php echo htmlspecialchars($akt['tgl_selesai']); ?>"
                            >
                                <?php echo htmlspecialchars($akt['nama_aktivitas']); ?> (Satuan: <?php echo htmlspecialchars($akt['satuan_bayar']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-muted" id="harga_info">Harga Satuan: Rp 0</small><br>
                    <small class="text-info" id="jenis_info">Jenis: -</small>
                </div>

                <div class="col-md-3">
                    <label for="mitra_id" class="form-label">Pilih Petugas (Mitra)</label>
                    <select class="form-select" id="mitra_id" name="mitra_id" required>
                        <option value="">-- Pilih Mitra --</option>
                        <?php foreach ($mitra_options as $mitra): ?>
                            <option value="<?php echo $mitra['id']; ?>"><?php echo htmlspecialchars($mitra['nama']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <small class="text-muted d-block">Urut default: nama (jika belum pilih desa).</small>
                </div>
                
                <div class="col-md-2">
                    <label for="beban_kerja" class="form-label">Beban Kerja</label>
                    <input type="number" class="form-control" id="beban_kerja" name="beban_kerja" required min="1" value="1">
                    <small class="text-muted" id="satuan_info">Satuan: -</small>
                </div>
                
                <div class="col-md-3">
                    <label for="jumlah_honor" class="form-label">Jumlah Honor (Rp)</label>
                    <input type="number" step="1" class="form-control" id="jumlah_honor" name="jumlah_honor" required min="0" value="0">
                    <small class="text-muted">Nilai otomatis (Harga x Beban)</small>
                </div>
            </div>
            
            <div class="row mb-3 border-top pt-3">
                <div class="col-md-3">
                    <label for="wilayah_kecamatan_id" class="form-label">Kecamatan Tugas</label>
                    <select class="form-select" id="wilayah_kecamatan_id" name="wilayah_kecamatan_id">
                        <option value="">Pilih Kecamatan (opsional)</option>
                        <?php foreach ($kecamatan_options as $kec): ?>
                            <option value="<?php echo $kec['id']; ?>"><?php echo htmlspecialchars($kec['nama_kecamatan']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label for="wilayah_desa_id" class="form-label">Desa Tugas</label>
                    <select class="form-select" id="wilayah_desa_id" name="wilayah_desa_id">  
                        <option value="">Pilih Desa/Kelurahan (opsional)</option>
                    </select>
                </div>
                <div class="col-md-6 text-end d-flex align-items-end justify-content-end">
                    <button type="submit" name="add_aktivitas" class="btn btn-primary"><i class="bi bi-floppy"></i> Simpan Alokasi</button>
                </div>
            </div>
        </form>
    </div>

    <h3>Data Alokasi Aktivitas Kerja</h3>
    <div class="table-responsive">
        <table class="table table-striped table-bordered">
            <thead>
                <tr>
                    <th>No.</th>
                    <th>Mitra</th>
                    <th>Aktivitas</th>
                    <th>Jenis</th> <th>Wilayah Tugas</th> 
                    <th>Harga Satuan (Rp)</th>
                    <th>Beban Kerja</th>
                    <th>Total Honor (Rp)</th>
                    <th>Periode Master</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($aktivitas_data)): ?>
                    <tr><td colspan="10" class="text-center">Belum ada aktivitas kerja yang dialokasikan.</td></tr>
                <?php else: ?>
                    <?php $no = 1; foreach ($aktivitas_data as $akt):  
                        $badge_class = ($akt['jenis_kegiatan'] == 'Pendataan') ? 'bg-success' : 'bg-warning text-dark';
                    ?>
                        <tr
                            data-id="<?php echo $akt['id']; ?>"
                            data-mitra-id="<?php echo $akt['mitra_id']; ?>"
                            data-nama-aktivitas-id="<?php echo $akt['nama_aktivitas_id']; ?>"
                            data-beban-kerja="<?php echo htmlspecialchars($akt['beban_kerja']); ?>"
                            data-honor="<?php echo htmlspecialchars($akt['jumlah_honor']); ?>"
                            data-desa-id="<?php echo htmlspecialchars($akt['wilayah_tugas_id']); ?>"
                            data-kecamatan-id="<?php echo htmlspecialchars($akt['kecamatan_id']); ?>" 
                            data-jenis-kegiatan="<?php echo htmlspecialchars($akt['jenis_kegiatan']); ?>"
                            data-master-mulai="<?php echo htmlspecialchars($akt['tgl_mulai']); ?>"
                            data-master-selesai="<?php echo htmlspecialchars($akt['tgl_selesai']); ?>"
                        >
                            <td><?php echo $no++; ?></td>
                            <td><?php echo htmlspecialchars($akt['nama_mitra']); ?></td>
                            <td>
                                <?php echo htmlspecialchars($akt['nama_aktivitas']); ?> 
                                <span class="badge bg-secondary"><?php echo htmlspecialchars($akt['satuan_bayar']); ?></span>
                            </td>
                            <td>
                                <span class="badge <?php echo $badge_class; ?>"><?php echo htmlspecialchars($akt['jenis_kegiatan']); ?></span>
                            </td>
                            <td>
                                <?php 
                                    if (!empty($akt['nama_desa'])) {
                                        echo "Desa: " . htmlspecialchars($akt['nama_desa']) . "";
                                        echo "<br><small class='text-muted'>(Kec: " . htmlspecialchars($akt['nama_kecamatan']) . ")</small>";
                                    } elseif (!empty($akt['nama_kecamatan'])) {
                                        echo "Kecamatan: " . htmlspecialchars($akt['nama_kecamatan']) . "";
                                    } else {
                                        echo "-";
                                    }
                                ?>
                            </td>
                            <td class="text-end"><?php echo number_format($akt['harga_satuan'], 0, ',', '.'); ?></td>
                            <td class="text-center"><?php echo number_format($akt['beban_kerja'], 0, ',', '.'); ?></td>
                            <td><?php echo "Rp " . number_format($akt['jumlah_honor'], 0, ',', '.'); ?></td>
                            <td>
                                <small class="text-muted">
                                    <?php echo date('d/m/Y', strtotime($akt['tgl_mulai'])) . " - " . date('d/m/Y', strtotime($akt['tgl_selesai'])); ?>
                                </small>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-warning edit-btn" data-bs-toggle="modal" data-bs-target="#editModal"><i class="bi bi-pencil"></i></button>
                                <a href="alokasi_mitra.php?delete_id=<?php echo $akt['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Anda yakin ingin menghapus alokasi aktivitas ini?');"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- EDIT MODAL -->
<div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST" action="alokasi_mitra.php" id="form_edit_alokasi">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel">Edit Alokasi Mitra</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="aktivitas_id" id="edit_aktivitas_id">
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="edit_nama_aktivitas_id" class="form-label">Nama Kegiatan</label>
                            <select class="form-select" id="edit_nama_aktivitas_id" name="edit_nama_aktivitas_id" required>
                                <option value="" data-harga="0" data-jenis="">-- Pilih Nama Kegiatan --</option>
                                <?php foreach ($nama_aktivitas_options as $akt): ?>
                                    <option 
                                        value="<?php echo $akt['id']; ?>"
                                        data-harga="<?php echo $akt['harga_satuan']; ?>"
                                        data-satuan="<?php echo htmlspecialchars($akt['satuan_bayar']); ?>"
                                        data-jenis="<?php echo htmlspecialchars($akt['jenis_kegiatan']); ?>"
                                        data-mulai="<?php echo htmlspecialchars($akt['tgl_mulai']); ?>"
                                        data-selesai="<?php echo htmlspecialchars($akt['tgl_selesai']); ?>"
                                    >
                                        <?php echo htmlspecialchars($akt['nama_aktivitas']); ?> (Satuan: <?php echo htmlspecialchars($akt['satuan_bayar']); ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted" id="edit_harga_info">Harga Satuan: Rp 0</small><br>
                            <small class="text-info" id="edit_jenis_info">Jenis: -</small>
                            <small class="text-danger mt-1" id="edit_tanggal_info">Periode: -</small> 
                        </div>
                        <div class="col-md-6">
                            <label for="edit_mitra_id" class="form-label">Petugas (Mitra)</label>
                            <select class="form-select" id="edit_mitra_id" name="edit_mitra_id" required>
                                <option value="">-- Pilih Mitra --</option>
                                <?php foreach ($mitra_options as $mitra): ?>
                                    <option value="<?php echo $mitra['id']; ?>"><?php echo htmlspecialchars($mitra['nama']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted d-block">Jika ingin urut berdasarkan jarak, pilih Desa pada bagian bawah terlebih dahulu.</small>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="edit_beban_kerja" class="form-label">Beban Kerja</label>
                            <input type="number" class="form-control" id="edit_beban_kerja" name="edit_beban_kerja" required min="1">
                            <small class="text-muted" id="edit_satuan_info">Satuan: -</small>
                        </div>
                        
                        <div class="col-md-4">
                            <label for="edit_jumlah_honor" class="form-label">Jumlah Honor (Rp)</label>
                            <input type="number" step="1" class="form-control" id="edit_jumlah_honor" name="edit_jumlah_honor" required min="0">
                            <small class="text-muted">Nilai otomatis (Harga x Beban)</small>
                        </div>
                    </div>
                    
                    <div class="row mb-3 border-top pt-3">
                        <div class="col-md-4">
                            <label for="edit_wilayah_kecamatan_id" class="form-label">Kecamatan Tugas</label>
                            <select class="form-select" id="edit_wilayah_kecamatan_id" name="edit_wilayah_kecamatan_id">
                                <option value="">Pilih Kecamatan (opsional)</option>
                                <?php foreach ($kecamatan_options as $kec): ?>
                                    <option value="<?php echo $kec['id']; ?>"><?php echo htmlspecialchars($kec['nama_kecamatan']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="edit_wilayah_desa_id" class="form-label">Desa Tugas</label>
                            <select class="form-select" id="edit_wilayah_desa_id" name="edit_wilayah_desa_id">
                                <option value="">Pilih Desa/Kelurahan (opsional)</option>
                            </select>
                        </div>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" name="edit_aktivitas" class="btn btn-warning"><i class="bi bi-save"></i> Simpan Perubahan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
// helper: format rupiah in php if needed elsewhere (keamanan)
function rupiah($val) {
    return 'Rp ' . number_format($val, 0, ',', '.');
}
?>

<script>
// UTILS
function formatRupiah(angka) {
    var reverse = Math.round(angka).toString().split('').reverse().join(''),
        ribuan  = reverse.match(/\d{1,3}/g);
        ribuan  = ribuan.join('.').split('').reverse().join('');
    return 'Rp ' + ribuan;
}

function formatDate(dateString) {
    if (!dateString || dateString === '0000-00-00') return '-';
    const date = new Date(dateString);
    date.setDate(date.getDate() + 1); 
    return date.toLocaleDateString('id-ID', { day: '2-digit', month: '2-digit', year: 'numeric' });
}

// =====================================================
// --- FORM TAMBAH (CREATE) ---
// =====================================================
function updateAddForm() {
    const select = document.getElementById('nama_aktivitas_id');
    const bebanKerjaInput = document.getElementById('beban_kerja');
    const honorInput = document.getElementById('jumlah_honor');
    const selectedOption = select.options[select.selectedIndex];

    const hargaSatuan = parseFloat(selectedOption.dataset.harga || 0);
    const satuanBayar = selectedOption.dataset.satuan || '-';
    const jenisKegiatan = selectedOption.dataset.jenis || '-';

    const bebanKerja = Math.max(1, Math.round(parseFloat(bebanKerjaInput.value) || 1));
    honorInput.value = Math.round(hargaSatuan * bebanKerja);

    document.getElementById('harga_info').textContent = 'Harga Satuan: ' + formatRupiah(hargaSatuan);
    document.getElementById('satuan_info').textContent = 'Satuan: ' + satuanBayar;
    document.getElementById('jenis_info').textContent = 'Jenis: ' + jenisKegiatan;
}

// =====================================================
// --- CASCADING DROPDOWN WILAYAH ---
// =====================================================
function loadDesaOptions(kecamatanId, desaSelectElementId, selectedDesaId = null) {
    const desaSelect = document.getElementById(desaSelectElementId);
    desaSelect.innerHTML = '<option value="">Pilih Desa/Kelurahan (opsional)</option>';

    if (kecamatanId) {
        fetch('get_desa.php?kec_id=' + encodeURIComponent(kecamatanId))
            .then(response => response.json())
            .then(data => {
                data.forEach(desa => {
                    const option = document.createElement('option');
                    option.value = desa.id;
                    option.textContent = desa.nama_desa;
                    if (selectedDesaId && String(desa.id) === String(selectedDesaId)) {
                        option.selected = true;
                    }
                    desaSelect.appendChild(option);
                });
            })
            .catch(error => console.error('Error fetching desa:', error));
    }
}

// =====================================================
// --- DOM CONTENT LOADED ---
// =====================================================
document.addEventListener('DOMContentLoaded', function() {
    // FORM TAMBAH
    const namaAktivitasSelect = document.getElementById('nama_aktivitas_id');
    const bebanKerjaInput = document.getElementById('beban_kerja');
    const kecamatanSelect = document.getElementById('wilayah_kecamatan_id');

    namaAktivitasSelect.addEventListener('change', updateAddForm);
    bebanKerjaInput.addEventListener('input', updateAddForm);
    updateAddForm();

    // Cascading Dropdown Tambah
    kecamatanSelect.addEventListener('change', function() {
        loadDesaOptions(this.value, 'wilayah_desa_id');
    });

    // Jika user memilih desa pada form tambah => panggil get_mitra_by_distance untuk mengurutkan mitra
    const desaSelectTambah = document.getElementById('wilayah_desa_id');
    desaSelectTambah.addEventListener('change', function() {
        const desaId = this.value;
        if (!desaId) return;

        fetch('get_mitra_by_distance.php?desa_id=' + encodeURIComponent(desaId))
            .then(r => r.json())
            .then(data => {
                const mitraSelect = document.getElementById('mitra_id');
                mitraSelect.innerHTML = '<option value="">-- Pilih Mitra --</option>';
                data.forEach(m => {
                    const opt = document.createElement('option');
                    opt.value = m.id;
                    opt.textContent = m.nama + (m.jarak !== null ? ' (Jarak: ' + parseFloat(m.jarak).toFixed(1) + ' km)' : '');
                    mitraSelect.appendChild(opt);
                });
            })
            .catch(err => console.error('Error fetching mitra by distance:', err));
    });

    // =====================================================
    // --- FORM EDIT (UPDATE) --- 
    // =====================================================
    const editModalEl = document.getElementById('editModal');
    const editNamaAktivitasSelect = document.getElementById('edit_nama_aktivitas_id');
    const editBebanKerjaInput = document.getElementById('edit_beban_kerja');
    const editHonorInput = document.getElementById('edit_jumlah_honor');
    const editKecamatanSelect = document.getElementById('edit_wilayah_kecamatan_id');
    const editDesaSelect = document.getElementById('edit_wilayah_desa_id');
    const editMitraSelect = document.getElementById('edit_mitra_id');

    function updateEditForm() {
        const select = editNamaAktivitasSelect;
        const bebanKerja = Math.max(1, Math.round(parseFloat(editBebanKerjaInput.value) || 1));
        const selectedOption = select.options[select.selectedIndex] || {};

        const hargaSatuan = parseFloat(selectedOption.dataset?.harga || 0);
        const satuanBayar = selectedOption.dataset?.satuan || '-';
        const jenisKegiatan = selectedOption.dataset?.jenis || '-';
        const tglMulai = selectedOption.dataset?.mulai || null;
        const tglSelesai = selectedOption.dataset?.selesai || null;

        document.getElementById('edit_harga_info').textContent = 'Harga Satuan: ' + formatRupiah(hargaSatuan);
        document.getElementById('edit_satuan_info').textContent = 'Satuan: ' + satuanBayar;
        document.getElementById('edit_jenis_info').textContent = 'Jenis: ' + jenisKegiatan;
        document.getElementById('edit_tanggal_info').textContent = 'Periode: ' + formatDate(tglMulai) + ' s.d. ' + formatDate(tglSelesai);

        editHonorInput.value = Math.round(hargaSatuan * bebanKerja);
    }

    if (editModalEl) {
        editModalEl.addEventListener('show.bs.modal', function (event) {
            const button = event.relatedTarget;
            const row = button.closest('tr');

            const masterId = row.dataset.namaAktivitasId;
            const kecamatanId = row.dataset.kecamatanId;
            const desaId = row.dataset.desaId;

            document.getElementById('edit_aktivitas_id').value = row.dataset.id;
            editMitraSelect.value = row.dataset.mitraId;
            editNamaAktivitasSelect.value = masterId;
            editBebanKerjaInput.value = row.dataset.bebanKerja;
            editHonorInput.value = row.dataset.honor;

            document.getElementById('edit_beban_kerja').dataset.initialValue = row.dataset.bebanKerja;
            document.getElementById('edit_jumlah_honor').dataset.initialValue = row.dataset.honor;

            editKecamatanSelect.value = kecamatanId || '';
            if (kecamatanId) {
                loadDesaOptions(kecamatanId, 'edit_wilayah_desa_id', desaId);
            } else {
                editDesaSelect.innerHTML = '<option value="">Pilih Desa/Kelurahan (opsional)</option>';
            }

            // tunggu sedikit sampai loadDesaOptions selesai (karena AJAX)
            // lalu update mitra pada modal berdasarkan desa yang sudah dipilih
            setTimeout(function() {
                if (desaId) {
                    fetch('get_mitra_by_distance.php?desa_id=' + encodeURIComponent(desaId))
                        .then(r => r.json())
                        .then(data => {
                            editMitraSelect.innerHTML = '<option value="">-- Pilih Mitra --</option>';
                            data.forEach(m => {
                                const opt = document.createElement('option');
                                opt.value = m.id;
                                opt.textContent = m.nama + (m.jarak !== null ? ' (Jarak: ' + parseFloat(m.jarak).toFixed(1) + ' km)' : '');
                                if (String(m.id) === String(row.dataset.mitraId)) opt.selected = true;
                                editMitraSelect.appendChild(opt);
                            });
                        })
                        .catch(err => console.error('Error fetching mitra by distance (edit):', err));
                }
            }, 300);

            updateEditForm();
        });

        editNamaAktivitasSelect.addEventListener('change', function() {
            editHonorInput.value = 0;
            editBebanKerjaInput.dataset.initialValue = '';
            updateEditForm();
        });

        editBebanKerjaInput.addEventListener('input', function() {
            editBebanKerjaInput.dataset.initialValue = this.value;
            updateEditForm();
        });

        editKecamatanSelect.addEventListener('change', function() {
            loadDesaOptions(this.value, 'edit_wilayah_desa_id');
        });

        // Jika user memilih Desa pada modal edit => update daftar mitra berdasar jarak
        editDesaSelect.addEventListener('change', function() {
            const desaId = this.value;
            if (!desaId) return;
            fetch('get_mitra_by_distance.php?desa_id=' + encodeURIComponent(desaId))
                .then(r => r.json())
                .then(data => {
                    editMitraSelect.innerHTML = '<option value="">-- Pilih Mitra --</option>';
                    data.forEach(m => {
                        const opt = document.createElement('option');
                        opt.value = m.id;
                        opt.textContent = m.nama + (m.jarak !== null ? ' (Jarak: ' + parseFloat(m.jarak).toFixed(1) + ' km)' : '');
                        editMitraSelect.appendChild(opt);
                    });
                })
                .catch(err => console.error('Error fetching mitra by distance (edit onchange):', err));
        });
    }
});
</script>
<script>
/* --- Saat pilih desa, sort dropdown mitra berdasarkan jarak --- */
document.getElementById("wilayah_desa_id").addEventListener("change", function () {
    const desaID = this.value;
    const mitraSelect = document.getElementById("mitra_id");

    if (desaID === "") return;

    fetch("get_mitra_by_distance.php?desa_id=" + desaID)
        .then(res => res.json())
        .then(data => {
            mitraSelect.innerHTML = '<option value="">-- Pilih Mitra (Urut Jarak) --</option>';

            data.forEach(m => {
                let opt = document.createElement("option");
                opt.value = m.id;
                opt.textContent = `${m.nama} ( ${m.jarak.toFixed(1)} km )`;
                mitraSelect.appendChild(opt);
            });
        });
});

/* --- EDIT MODAL versi jarak --- */
document.getElementById("edit_wilayah_desa_id").addEventListener("change", function () {
    const desaID = this.value;
    const mitraSelect = document.getElementById("edit_mitra_id");

    if (desaID === "") return;

    fetch("get_mitra_by_distance.php?desa_id=" + desaID)
        .then(res => res.json())
        .then(data => {
            mitraSelect.innerHTML = '<option value="">-- Pilih Mitra (Urut Jarak) --</option>';

            data.forEach(m => {
                let opt = document.createElement("option");
                opt.value = m.id;
                opt.textContent = `${m.nama} ( ${m.jarak.toFixed(1)} km )`;
                mitraSelect.appendChild(opt);
            });
        });
});
</script>

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