<?php
// alokasi_mitra.php
include_once 'header.php';
include_once 'config/koneksi.php';

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

// 1. Ambil Tahun Aktif
$tahun_aktif_id = null;
$result_tahun = $conn->query("SELECT id FROM tahun_aktif WHERE is_aktif = 1 LIMIT 1");
if ($result_tahun && $result_tahun->num_rows > 0) {
    $tahun_aktif_id = $result_tahun->fetch_assoc()['id'];
}

// 2. LOGIKA DELETE
if (isset($_GET['delete_id'])) {
    $id_hapus = intval($_GET['delete_id']);
    $sql_del = "DELETE FROM aktivitas_kerja WHERE id = ? AND tahun_aktif_id = ?";
    $stmt_del = $conn->prepare($sql_del);
    $stmt_del->bind_param("ii", $id_hapus, $tahun_aktif_id);
    $stmt_del->execute();
    header("Location: alokasi_mitra.php" . (isset($_GET['akt_focus']) ? "?akt_focus=".$_GET['akt_focus'] : ""));
    exit();
}

$akt_focus = $_GET['akt_focus'] ?? ($_POST['nama_aktivitas_id'] ?? null);

// 3. Ambil Master Data
$nama_aktivitas_options = [];
if ($tahun_aktif_id) {
    $sql_master = "SELECT NAM.id, NAM.nama_aktivitas, NAM.satuan_bayar, NAM.harga_satuan 
                   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_m = $conn->prepare($sql_master); 
    $stmt_m->bind_param("i", $tahun_aktif_id); 
    $stmt_m->execute();
    $nama_aktivitas_options = $stmt_m->get_result()->fetch_all(MYSQLI_ASSOC);
}

$current_akt = null;
if ($akt_focus) {
    foreach ($nama_aktivitas_options as $a) { if ($a['id'] == $akt_focus) { $current_akt = $a; break; } }
}

$kecamatan_options = [];
$res_kec = $conn->query("SELECT SUBSTRING(id, 1, 7) AS kode, MAX(kecamatan) AS nama, MIN(id) AS id_virtual FROM wilayahtugas GROUP BY kode ORDER BY nama ASC");
while ($row = $res_kec->fetch_assoc()) { $kecamatan_options[] = $row; }

$all_mitra = [];
if ($tahun_aktif_id) {
    $sql_m = "SELECT id, nama FROM mitra WHERE tahun_aktif_id = ? ORDER BY nama ASC";
    $stmt_m = $conn->prepare($sql_m); $stmt_m->bind_param("i", $tahun_aktif_id); $stmt_m->execute();
    $all_mitra = $stmt_m->get_result()->fetch_all(MYSQLI_ASSOC);
}

// 4. LOGIKA SIMPAN & EDIT
if (isset($_POST['add_aktivitas']) || isset($_POST['edit_aktivitas'])) {
    $mitra_id = intval($_POST['mitra_id'] ?? $_POST['edit_mitra_id']);
    $nama_id = intval($_POST['nama_aktivitas_id'] ?? $_POST['edit_nama_aktivitas_id']);
    $beban = intval($_POST['beban_kerja'] ?? $_POST['edit_beban_kerja']);
    $honor = floatval($_POST['jumlah_honor'] ?? $_POST['edit_jumlah_honor']);
    $desa_id = !empty($_POST['wilayah_desa_id']) ? $_POST['wilayah_desa_id'] : (!empty($_POST['edit_wilayah_desa_id']) ? $_POST['edit_wilayah_desa_id'] : NULL);

    if (isset($_POST['add_aktivitas'])) {
        $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);
        $stmt->bind_param("iiidsi", $mitra_id, $nama_id, $beban, $honor, $desa_id, $tahun_aktif_id);
    } else {
        $id = intval($_POST['aktivitas_id']);
        $sql = "UPDATE aktivitas_kerja SET mitra_id=?, nama_aktivitas_id=?, beban_kerja=?, jumlah_honor=?, wilayah_tugas_id=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iiidsi", $mitra_id, $nama_id, $beban, $honor, $desa_id, $id);
    }
    $stmt->execute();
    header("Location: alokasi_mitra.php?akt_focus=".$nama_id); exit();
}

$aktivitas_data = [];
if ($tahun_aktif_id && $akt_focus) {
    $sql_read = "SELECT ak.*, m.nama AS nama_mitra, nam.nama_aktivitas, nam.satuan_bayar, nam.harga_satuan, 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 = ? AND ak.nama_aktivitas_id = ? ORDER BY ak.id DESC";
    $stmt_r = $conn->prepare($sql_read); $stmt_r->bind_param("ii", $tahun_aktif_id, $akt_focus); $stmt_r->execute();
    $aktivitas_data = $stmt_r->get_result()->fetch_all(MYSQLI_ASSOC);
}
?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<div class="container-fluid pt-4 pb-5 bg-light min-vh-100">
    <?php if (!$akt_focus): ?>
        <div class="card p-5 text-center shadow-sm border-0">
            <h4 class="fw-bold mb-3">Pilih Aktivitas Terlebih Dahulu</h4>
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <form method="GET">
                        <select class="form-select form-select-lg" name="akt_focus" onchange="this.form.submit()" required>
                            <option value="">-- Pilih Aktivitas --</option>
                            <?php foreach ($nama_aktivitas_options as $akt): ?>
                                <option value="<?= $akt['id'] ?>"><?= htmlspecialchars($akt['nama_aktivitas']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                </div>
            </div>
        </div>
    <?php else: ?>
        <div class="card p-4 mb-4 border-start border-4 border-primary shadow-sm bg-white">
            <h5 class="text-primary fw-bold mb-3">Input Alokasi: <?= htmlspecialchars($current_akt['nama_aktivitas']) ?></h5>
            <form method="POST">
                <input type="hidden" id="nama_aktivitas_id" name="nama_aktivitas_id" value="<?= $current_akt['id'] ?>" data-harga="<?= $current_akt['harga_satuan'] ?>">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label small fw-bold">Wilayah</label>
                        <select class="form-select mb-2" id="wilayah_kecamatan_id">
                            <option value="">-- Kecamatan --</option>
                            <?php foreach ($kecamatan_options as $kec): ?>
                                <option value="<?= $kec['id_virtual'] ?>"><?= $kec['nama'] ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select class="form-select" id="wilayah_desa_id" name="wilayah_desa_id">
                            <option value="">-- Desa --</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label small fw-bold">Pilih Mitra (Bisa Ketik Nama)</label>
                        <select class="form-select" id="mitra_id" name="mitra_id" required>
                            <option value="">-- Pilih Mitra --</option>
                            <?php foreach ($all_mitra as $m): ?>
                                <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['nama']) ?></option>
                            <?php endforeach; ?>
                        </select>
                        <div id="distance_msg" class="mt-2 small text-muted">* Urutan abjad</div>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label small fw-bold">Beban</label>
                        <div class="input-group">
                            <input type="number" class="form-control" id="beban_kerja" name="beban_kerja" value="1" min="1">
                            <span class="input-group-text small"><?= $current_akt['satuan_bayar'] ?></span>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label small fw-bold">Total Honor</label>
                        <input type="number" class="form-control bg-light fw-bold text-success mb-2" id="jumlah_honor" name="jumlah_honor" readonly>
                        <button type="submit" name="add_aktivitas" class="btn btn-primary w-100 shadow-sm">Simpan</button>
                    </div>
                </div>
            </form>
        </div>

        <div class="table-responsive bg-white rounded shadow-sm">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-primary">
                    <tr>
                        <th class="text-center">No</th>
                        <th>Nama Mitra</th>
                        <th>Wilayah Tugas</th>
                        <th class="text-center">Beban</th>
                        <th>Honor</th>
                        <th class="text-center">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $no=1; foreach ($aktivitas_data as $row): ?>
                        <tr data-id="<?= $row['id'] ?>" data-mitra-id="<?= $row['mitra_id'] ?>" data-nama-aktivitas-id="<?= $row['nama_aktivitas_id'] ?>" data-beban-kerja="<?= $row['beban_kerja'] ?>" data-honor="<?= $row['jumlah_honor'] ?>" data-kecamatan-id="<?= $row['kecamatan_id'] ?>" data-desa-id="<?= $row['wilayah_tugas_id'] ?>">
                            <td class="text-center"><?= $no++ ?></td>
                            <td class="fw-bold"><?= htmlspecialchars($row['nama_mitra']) ?></td>
                            <td><small><?= $row['nama_desa'] ?: '-' ?> (<?= $row['nama_kecamatan'] ?>)</small></td>
                            <td class="text-center"><?= $row['beban_kerja'] ?></td>
                            <td class="text-success fw-bold">Rp <?= number_format($row['jumlah_honor'], 0, ',', '.') ?></td>
                            <td class="text-center">
                                <button class="btn btn-sm btn-outline-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=<?= $row['id'] ?>&akt_focus=<?= $akt_focus ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Hapus?')"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content shadow">
            <form method="POST">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title fw-bold">Edit Alokasi</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" name="aktivitas_id" id="edit_aktivitas_id">
                    <input type="hidden" name="edit_nama_aktivitas_id" id="edit_nama_aktivitas_id" data-harga="<?= $current_akt['harga_satuan'] ?? 0 ?>">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Wilayah</label>
                        <select class="form-select mb-2" id="edit_wilayah_kecamatan_id">
                            <?php foreach ($kecamatan_options as $kec): ?>
                                <option value="<?= $kec['id_virtual'] ?>"><?= $kec['nama'] ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select class="form-select" id="edit_wilayah_desa_id" name="edit_wilayah_desa_id">
                            <option value="">-- Pilih Desa --</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Mitra (Search)</label>
                        <select class="form-select" id="edit_mitra_id" name="edit_mitra_id" required style="width: 100%"></select>
                    </div>
                    <div class="row">
                        <div class="col-6">
                            <label class="form-label small fw-bold">Beban</label>
                            <input type="number" class="form-control" id="edit_beban_kerja" name="edit_beban_kerja" min="1">
                        </div>
                        <div class="col-6">
                            <label class="form-label small fw-bold">Honor</label>
                            <input type="number" class="form-control bg-light fw-bold text-success" id="edit_jumlah_honor" name="edit_jumlah_honor" readonly>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" name="edit_aktivitas" class="btn btn-warning fw-bold w-100">Update Data</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
const backupMitra = <?php echo json_encode($all_mitra); ?>;

function initSelect2() {
    $('#mitra_id').select2({ theme: 'bootstrap-5', placeholder: '-- Cari Mitra --' });
    $('#edit_mitra_id').select2({ 
        theme: 'bootstrap-5', 
        placeholder: '-- Cari Mitra --',
        dropdownParent: $('#editModal') 
    });
}

function renderMitra(data, targetEl, selectedId = null) {
    const el = document.getElementById(targetEl);
    el.innerHTML = '<option value="">-- Pilih Mitra --</option>';
    data.forEach(m => {
        const opt = document.createElement('option');
        opt.value = m.id;
        let d = (m.jarak !== null && m.jarak !== undefined) ? ` (${parseFloat(m.jarak).toFixed(1)} km)` : '';
        opt.textContent = m.nama + d;
        if(selectedId && m.id == selectedId) opt.selected = true;
        el.appendChild(opt);
    });
    $(el).trigger('change'); // Update Select2
}

function loadMitra(desaId, targetEl, msgEl, selectedId = null) {
    if(!desaId) {
        renderMitra(backupMitra, targetEl, selectedId);
        if(msgEl) document.getElementById(msgEl).textContent = "* Urutan abjad";
        return;
    }
    fetch(`get_mitra_by_distance.php?desa_id=${desaId}`)
        .then(r => r.json())
        .then(data => {
            renderMitra(data, targetEl, selectedId);
            if(msgEl) document.getElementById(msgEl).textContent = "* Urutan abjad dengan info jarak";
        }).catch(() => renderMitra(backupMitra, targetEl, selectedId));
}

function loadDesa(kecId, targetEl, selectedId = null) {
    const el = document.getElementById(targetEl);
    if(!kecId) return;
    fetch(`get_desa.php?kec_id=${kecId}`).then(r => r.json()).then(data => {
        el.innerHTML = '<option value="">-- Pilih Desa --</option>';
        data.forEach(d => {
            const opt = document.createElement('option');
            opt.value = d.id; opt.textContent = d.nama_desa;
            if(selectedId && d.id == selectedId) opt.selected = true;
            el.appendChild(opt);
        });
    });
}

function hitungHonor(hiddenId, bebanId, resultId) {
    const harga = parseFloat(document.getElementById(hiddenId).dataset.harga || 0);
    const beban = parseFloat(document.getElementById(bebanId).value || 0);
    document.getElementById(resultId).value = Math.round(harga * beban);
}

$(document).ready(function() {
    initSelect2();
    
    // Form Tambah
    $('#wilayah_kecamatan_id').on('change', function() { loadDesa(this.value, 'wilayah_desa_id'); });
    $('#wilayah_desa_id').on('change', function() { loadMitra(this.value, 'mitra_id', 'distance_msg'); });
    $('#beban_kerja').on('input', function() { hitungHonor('nama_aktivitas_id', 'beban_kerja', 'jumlah_honor'); });
    hitungHonor('nama_aktivitas_id', 'beban_kerja', 'jumlah_honor');

    // Modal Edit
    const editModal = document.getElementById('editModal');
    if(editModal) {
        editModal.addEventListener('show.bs.modal', function(e) {
            const row = e.relatedTarget.closest('tr').dataset;
            $('#edit_aktivitas_id').val(row.id);
            $('#edit_nama_aktivitas_id').val(row.namaAktivitasId);
            $('#edit_beban_kerja').val(row.bebanKerja);
            $('#edit_wilayah_kecamatan_id').val(row.kecamatanId);
            
            loadDesa(row.kecamatanId, 'edit_wilayah_desa_id', row.desaId);
            loadMitra(row.desaId, 'edit_mitra_id', null, row.mitraId);
            setTimeout(() => hitungHonor('edit_nama_aktivitas_id', 'edit_beban_kerja', 'edit_jumlah_honor'), 500);
        });
        $('#edit_wilayah_kecamatan_id').on('change', function() { loadDesa(this.value, 'edit_wilayah_desa_id'); });
        $('#edit_wilayah_desa_id').on('change', function() { loadMitra(this.value, 'edit_mitra_id', null); });
        $('#edit_beban_kerja').on('input', function() { hitungHonor('edit_nama_aktivitas_id', 'edit_beban_kerja', 'edit_jumlah_honor'); });
    }
});
</script>

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