<?php
// aktivitas_kerja.php
include_once 'header.php';

// Fungsi ambil ID tahun
function getTahunIdByTahun($conn, $tahun) {
    $sql = "SELECT id FROM tahun_aktif WHERE tahun = ?";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("i", $tahun);
        $stmt->execute();
        $result = $stmt->get_result();
        return ($result && $row = $result->fetch_assoc()) ? $row['id'] : null;
    }
    return null;
}

// --- PERBAIKAN: AMBIL DAFTAR TAHUN DARI DATABASE ---
$tahun_options = [];
$res_tahun = $conn->query("SELECT tahun FROM tahun_aktif ORDER BY tahun DESC");
if ($res_tahun) {
    while ($row_t = $res_tahun->fetch_assoc()) {
        $tahun_options[] = $row_t['tahun'];
    }
}
// Jika database kosong, gunakan tahun sekarang sebagai fallback
if (empty($tahun_options)) { $tahun_options[] = date('Y'); }

// 1. PENENTUAN FILTER DEFAULT
$current_year = date('Y');
$filter_status = isset($_GET['filter_status']) ? $_GET['filter_status'] : 'sudah';
$selected_bulan = isset($_GET['filter_bulan']) ? intval($_GET['filter_bulan']) : 0;
// Default tahun diambil dari tahun terbaru di database
$selected_tahun = isset($_GET['filter_tahun']) ? intval($_GET['filter_tahun']) : $tahun_options[0];
$search_nama = isset($_GET['search_nama']) ? $_GET['search_nama'] : '';
$sort_order = isset($_GET['sort_order']) ? $_GET['sort_order'] : 'ASC';

$selected_tahun_id = getTahunIdByTahun($conn, $selected_tahun);

$rekap_data = [];
$mitra_belum = [];

$bulan_array = [
    0 => 'Setahun Penuh', 1 => 'Januari', 2 => 'Februari', 3 => 'Maret', 4 => 'April', 
    5 => 'Mei', 6 => 'Juni', 7 => 'Juli', 8 => 'Agustus', 
    9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Desember'
];

// 2. LOGIKA PENGAMBILAN DATA
if ($selected_tahun_id) {
    $search_param = "%$search_nama%";
    
    if ($filter_status == 'sudah') {
        $bulan_sql = ($selected_bulan > 0) ? "AND MONTH(nam.tgl_mulai) = ?" : "";
        $sql = "SELECT m.id, m.nama, COUNT(ak.id) as jml_keg, SUM(ak.jumlah_honor) as total_honor,
                GROUP_CONCAT(CONCAT(nam.nama_aktivitas, ' (', DATE_FORMAT(nam.tgl_mulai, '%b'), ')') SEPARATOR ' | ') as kegiatan_detail
                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
                WHERE ak.tahun_aktif_id = ? AND YEAR(nam.tgl_mulai) = ? $bulan_sql AND m.nama LIKE ?
                GROUP BY m.id, m.nama ORDER BY m.nama $sort_order";
        
        $stmt = $conn->prepare($sql);
        if($selected_bulan > 0) $stmt->bind_param("iiis", $selected_tahun_id, $selected_tahun, $selected_bulan, $search_param);
        else $stmt->bind_param("iis", $selected_tahun_id, $selected_tahun, $search_param);
        $stmt->execute();
        $rekap_data = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    } else {
        $bulan_sub = ($selected_bulan > 0) ? "AND MONTH(nam2.tgl_mulai) = $selected_bulan" : "";
        $sql = "SELECT id, nama FROM mitra 
                WHERE tahun_aktif_id = ? AND nama LIKE ?
                AND id NOT IN (
                    SELECT ak2.mitra_id FROM aktivitas_kerja ak2 
                    JOIN nama_aktivitas_master nam2 ON ak2.nama_aktivitas_id = nam2.id
                    WHERE ak2.tahun_aktif_id = ? AND YEAR(nam2.tgl_mulai) = ? $bulan_sub
                ) ORDER BY nama $sort_order";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("isii", $selected_tahun_id, $search_param, $selected_tahun_id, $selected_tahun);
        $stmt->execute();
        $mitra_belum = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }
}
?>

<style>
    .filter-box { background: #f0f7ff; border: 1px solid #cfe2ff; border-radius: 12px; padding: 25px; margin-bottom: 20px; }
    .search-area { background: white; border: 1px solid #dee2e6; border-radius: 10px; padding: 15px; margin-bottom: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
    .mitra-link { color: #0d6efd; text-decoration: none; font-weight: 600; cursor: pointer; border-bottom: 1px dashed #0d6efd; padding-bottom: 2px; }
    .mitra-link:hover { color: #0a58ca; background-color: #f8f9fa; }
    .modal-header { background: #0d6efd; color: white; border-top-left-radius: 10px; border-top-right-radius: 10px; }
    .detail-label { font-weight: 600; color: #495057; width: 140px; display: inline-block; }
    .list-kegiatan { background: #f8f9fa; padding: 12px; border-radius: 8px; border: 1px solid #e9ecef; }
</style>

<div class="container-fluid py-4">
    <div class="d-flex align-items-center mb-3">
        <h2 class="mb-0"><i class="bi bi-person-lines-fill me-2"></i>Rekapitulasi Alokasi Mitra</h2>
    </div>
    <hr>

    <div class="filter-box shadow-sm">
        <form method="GET" class="row g-3">
            <div class="col-md-4">
                <label class="form-label fw-bold">Pengalokasian</label>
                <select name="filter_status" class="form-select border-primary shadow-sm">
                    <option value="sudah" <?php echo $filter_status == 'sudah' ? 'selected' : ''; ?>>Sudah Dialokasi</option>
                    <option value="belum" <?php echo $filter_status == 'belum' ? 'selected' : ''; ?>>Belum Dialokasi</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label fw-bold">Bulan</label>
                <select name="filter_bulan" class="form-select shadow-sm">
                    <?php foreach($bulan_array as $n => $m): ?>
                        <option value="<?php echo $n; ?>" <?php echo $selected_bulan == $n ? 'selected' : ''; ?>><?php echo $m; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label fw-bold">Tahun</label>
                <select name="filter_tahun" class="form-select shadow-sm">
                    <?php foreach($tahun_options as $th): ?>
                        <option value="<?php echo $th; ?>" <?php echo $selected_tahun == $th ? 'selected' : ''; ?>><?php echo $th; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100 shadow-sm">Tampilkan</button>
            </div>
        </form>
    </div>

    <div class="search-area">
        <form method="GET" class="row g-2">
            <input type="hidden" name="filter_status" value="<?php echo $filter_status; ?>">
            <input type="hidden" name="filter_bulan" value="<?php echo $selected_bulan; ?>">
            <input type="hidden" name="filter_tahun" value="<?php echo $selected_tahun; ?>">
            <div class="col-md-9">
                <input type="text" name="search_nama" class="form-control" placeholder="Cari nama mitra..." value="<?php echo htmlspecialchars($search_nama); ?>">
            </div>
            <div class="col-md-2">
                <select name="sort_order" class="form-select">
                    <option value="ASC" <?php echo $sort_order == 'ASC' ? 'selected' : ''; ?>>A-Z</option>
                    <option value="DESC" <?php echo $sort_order == 'DESC' ? 'selected' : ''; ?>>Z-A</option>
                </select>
            </div>
            <div class="col-md-1">
                <button type="submit" class="btn btn-outline-primary w-100">Cari</button>
            </div>
        </form>
    </div>

    <div class="card shadow-sm border-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="text-center" width="60">No</th>
                        <th>Nama Mitra (Klik untuk Detail)</th>
                        <?php if($filter_status == 'sudah'): ?>
                            <th class="text-center">Jml Kegiatan</th>
                            <th class="text-end" width="200">Total Honor</th>
                        <?php else: ?>
                            <th class="text-center">Status</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $data_loop = ($filter_status == 'sudah') ? $rekap_data : $mitra_belum;
                    if(empty($data_loop)): 
                    ?>
                        <tr><td colspan="4" class="text-center py-5 text-muted">Data tidak ditemukan.</td></tr>
                    <?php else: $no=1; foreach($data_loop as $row): ?>
                        <tr>
                            <td class="text-center"><?php echo $no++; ?></td>
                            <td>
                                <span class="mitra-link" onclick="showDetail('<?php echo addslashes($row['nama'] ?? $row['nama_mitra']); ?>', '<?php echo $row['jml_keg'] ?? 0; ?>', '<?php echo addslashes($row['kegiatan_detail'] ?? '-'); ?>', '<?php echo number_format($row['total_honor'] ?? 0, 0, ',', '.'); ?>')">
                                    <?php echo htmlspecialchars($row['nama'] ?? $row['nama_mitra']); ?>
                                </span>
                            </td>
                            <?php if($filter_status == 'sudah'): ?>
                                <td class="text-center"><?php echo $row['jml_keg']; ?></td>
                                <td class="text-end fw-bold text-success">Rp <?php echo number_format($row['total_honor'], 0, ',', '.'); ?></td>
                            <?php else: ?>
                                <td class="text-center"><span class="badge bg-danger">Belum Alokasi</span></td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="modalDetail" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">Informasi Aktivitas</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="mb-3"><span class="detail-label">Nama</span>: <span id="detNama" class="fw-bold text-primary"></span></div>
                <div class="mb-3"><span class="detail-label">Jumlah Kegiatan</span>: <span id="detJml" class="badge bg-secondary"></span></div>
                <div class="mb-3">
                    <span class="detail-label d-block mb-2">Rincian Kegiatan:</span>
                    <div id="detKegiatan" class="list-kegiatan"></div>
                </div>
                <hr>
                <div class="d-flex justify-content-between align-items-center">
                    <span class="detail-label">Total Honor</span>
                    <h4 class="text-success fw-bold mb-0">Rp <span id="detHonor"></span></h4>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function showDetail(nama, jml, kegiatan, honor) {
    document.getElementById('detNama').innerText = nama;
    document.getElementById('detJml').innerText = jml + ' Aktivitas';
    let kegArray = kegiatan.split(' | ');
    let kegHtml = '<ul class="mb-0 ps-3">';
    kegArray.forEach(function(item) {
        if(item.trim() !== '-' && item.trim() !== '') kegHtml += '<li class="mb-1">' + item + '</li>';
    });
    kegHtml += '</ul>';
    document.getElementById('detKegiatan').innerHTML = kegHtml;
    document.getElementById('detHonor').innerText = honor;
    new bootstrap.Modal(document.getElementById('modalDetail')).show();
}
</script>

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