<?php
session_start();
include 'config/koneksi.php';

// CEK ROLE ADMIN
$isAdmin = (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1);

// --- FUNGSI-FUNGSI PEMBANTU ---
if (!function_exists('getTahunAktifId')) {
    function getTahunAktifId($conn) {
        $sql = "SELECT id FROM tahun_aktif WHERE is_aktif = 1 LIMIT 1";
        $result = $conn->query($sql);
        return ($result && $result->num_rows > 0) ? $result->fetch_assoc()['id'] : 0;
    }
}

function getAktivitasById($conn, $id) {
    $id = $conn->real_escape_string($id);
    $sql = "SELECT * FROM nama_aktivitas_master WHERE id = '$id'";
    $res = $conn->query($sql);
    return ($res) ? $res->fetch_assoc() : null;
}

function getDetailKegiatan($conn, $tahun_id) {
    $sql = "SELECT dk.id, dk.nama_detail, p.nama_program, kg.nama_kegiatan
            FROM detail_kegiatan dk
            JOIN subkomponen sk ON dk.subkomponen_id = sk.id
            JOIN komponen k ON sk.komponen_id = k.id
            JOIN subkegiatan skg ON k.subkegiatan_id = skg.id
            JOIN kegiatan kg ON skg.kegiatan_id = kg.id
            JOIN program p ON kg.program_id = p.id
            WHERE p.tahun_aktif_id = ? ORDER BY dk.nama_detail";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $tahun_id);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

function getMasterAktivitasList($conn, $tahun_id) {
    $sql = "SELECT nam.*, dk.nama_detail 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
            JOIN komponen k ON sk.komponen_id = k.id
            JOIN subkegiatan skg ON k.subkegiatan_id = skg.id
            JOIN kegiatan kg ON skg.kegiatan_id = kg.id
            JOIN program p ON kg.program_id = p.id
            WHERE p.tahun_aktif_id = ? ORDER BY nam.id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $tahun_id);
    $stmt->execute();
    return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
}

// --- LOGIKA HALAMAN ---
$default_tahun_aktif_id = getTahunAktifId($conn); 
$selected_tahun_id = isset($_GET['tahun']) ? intval($_GET['tahun']) : $default_tahun_aktif_id;

if (isset($_GET['action']) && $_GET['action'] == 'hapus' && isset($_GET['id'])) {
    $id_hapus = $conn->real_escape_string($_GET['id']);
    if (!$isAdmin) {
        $cek = getAktivitasById($conn, $id_hapus);
        if ($cek && $cek['harga_satuan'] > 0) {
            header("Location: input_master_aktivitas.php?status=error_hapus&tahun=" . $selected_tahun_id);
            exit();
        }
    }
    $conn->query("DELETE FROM nama_aktivitas_master WHERE id = '$id_hapus'");
    header("Location: input_master_aktivitas.php?status=hapus&tahun=" . $selected_tahun_id);
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id_post = $_POST['id_aktivitas'] ?? '';
    $tahun_redirect = intval($_POST['redirect_tahun']);
    $detail_id = intval($_POST['detail_kegiatan_id']);
    $nama = $_POST['nama_aktivitas'];
    $jenis = $_POST['jenis_kegiatan'];
    $satuan = $_POST['satuan_bayar']; 
    $tgl_m = !empty($_POST['tgl_mulai']) ? $_POST['tgl_mulai'] : '0000-00-00';
    $tgl_s = !empty($_POST['tgl_selesai']) ? $_POST['tgl_selesai'] : '0000-00-00';

    if ($isAdmin) {
        $harga = $_POST['harga_satuan'];
    } else {
        $old = (!empty($id_post)) ? getAktivitasById($conn, $id_post) : null;
        $harga = $old['harga_satuan'] ?? 0;
    }

    try {
        if (empty($id_post)) {
            $stmt = $conn->prepare("INSERT INTO nama_aktivitas_master (detail_kegiatan_id, jenis_kegiatan, nama_aktivitas, satuan_bayar, harga_satuan, tgl_mulai, tgl_selesai) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("isssdss", $detail_id, $jenis, $nama, $satuan, $harga, $tgl_m, $tgl_s);
            $stat = "tambah";
        } else {
            $stmt = $conn->prepare("UPDATE nama_aktivitas_master SET detail_kegiatan_id=?, jenis_kegiatan=?, nama_aktivitas=?, satuan_bayar=?, harga_satuan=?, tgl_mulai=?, tgl_selesai=? WHERE id=?");
            $stmt->bind_param("isssdssi", $detail_id, $jenis, $nama, $satuan, $harga, $tgl_m, $tgl_s, $id_post);
            $stat = "update";
        }
        if ($stmt->execute()) {
            header("Location: input_master_aktivitas.php?status=$stat&tahun=" . $tahun_redirect);
        } else {
            throw new Exception($stmt->error);
        }
        exit();
    } catch (Exception $e) {
        die("Error Simpan: " . $e->getMessage());
    }
}

$data_edit = [];
$isEditBiaya = false;
if (isset($_GET['id'])) {
    $data_edit = getAktivitasById($conn, $_GET['id']);
    if (isset($_GET['action']) && $_GET['action'] == 'edit_biaya') { $isEditBiaya = true; }
}

$detail_kegiatan_list = getDetailKegiatan($conn, $default_tahun_aktif_id);
$master_aktivitas_list = getMasterAktivitasList($conn, $selected_tahun_id);

include 'header.php';
?>

<style>
    .card-container { background: #fff; padding: 25px; margin-bottom: 25px; border-radius: 8px; border: 1px solid #e0e0e0; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
    .form-group label { font-weight: 600; display: block; margin-bottom: 5px; }
    .form-group input, .form-group select { width: 100%; padding: 10px; margin-bottom: 5px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
    .date-group { display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 10px; }
    .date-group .form-group { flex: 1; min-width: 150px; }
    .styled-table { width: 100%; border-collapse: collapse; margin-top: 15px; font-size: 0.9em; }
    .styled-table thead { background: #007bff; color: white; }
    .styled-table th, .styled-table td { padding: 12px; border: 1px solid #ddd; text-align: left; }
    .btn-primary { background: #007bff; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; font-weight: bold; }
    .locked-bg { background-color: #f1f3f5 !important; color: #6c757d; cursor: not-allowed; }
    .alert { padding: 15px; margin-bottom: 20px; border-radius: 4px; font-weight: bold; }
    .alert-success { color: #155724; background-color: #d4edda; border-color: #c3e6cb; }
    .alert-danger { color: #721c24; background-color: #f8d7da; border-color: #f5c6cb; }
    
    /* STYLE IKON AKSI BARU */
    .action-btn { 
        text-decoration: none; 
        font-size: 1.1rem; 
        padding: 4px 8px; 
        border-radius: 4px; 
        display: inline-flex; 
        align-items: center; 
        justify-content: center;
        border: 1px solid transparent;
        transition: 0.2s;
        font-weight: bold;
    }
    .btn-edit { color: #007bff; border-color: #007bff; }
    .btn-edit:hover { background: #007bff; color: #fff; }
    
    .btn-biaya { color: #28a745; border-color: #28a745; }
    .btn-biaya:hover { background: #28a745; color: #fff; }
    
    .btn-delete { color: #dc3545; border-color: #dc3545; }
    .btn-delete:hover { background: #dc3545; color: #fff; }
</style>

<?php if (isset($_GET['status'])): ?>
    <div class="alert <?php echo (in_array($_GET['status'], ['hapus','error_hapus'])) ? 'alert-danger' : 'alert-success'; ?>">
        <?php 
            if($_GET['status'] == 'tambah') echo "✓ Berhasil disimpan.";
            if($_GET['status'] == 'update') echo "✓ Berhasil diperbarui.";
            if($_GET['status'] == 'hapus') echo "🗑 Data berhasil dihapus.";
            if($_GET['status'] == 'error_hapus') echo "⚠ Gagal! Data sudah terkunci.";
        ?>
    </div>
<?php endif; ?>

<?php if (!$isAdmin || ($isAdmin && $isEditBiaya)): ?>
<div class="card-container">
    <form method="POST">
        <h2><?php echo $isEditBiaya ? 'Input Harga Satuan' : 'Detail Aktivitas'; ?></h2>
        <input type="hidden" name="id_aktivitas" value="<?php echo $data_edit['id'] ?? ''; ?>">
        <input type="hidden" name="redirect_tahun" value="<?php echo $selected_tahun_id; ?>">

        <div class="form-group">
            <label>Pilih Detail Kegiatan</label>
            <select name="detail_kegiatan_id" required <?php echo $isAdmin ? 'disabled class="locked-bg"' : ''; ?>>
                <option value="">-- Pilih Kegiatan --</option>
                <?php foreach ($detail_kegiatan_list as $dk): ?>
                    <option value="<?php echo $dk['id']; ?>" <?php echo (isset($data_edit['detail_kegiatan_id']) && $data_edit['detail_kegiatan_id'] == $dk['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($dk['nama_detail']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <?php if($isAdmin && isset($data_edit['detail_kegiatan_id'])): ?> 
                <input type="hidden" name="detail_kegiatan_id" value="<?php echo $data_edit['detail_kegiatan_id']; ?>"> 
            <?php endif; ?>
        </div>

        <div class="form-group">
            <label>Nama Aktivitas</label>
            <input type="text" name="nama_aktivitas" required value="<?php echo htmlspecialchars($data_edit['nama_aktivitas'] ?? ''); ?>" <?php echo $isAdmin ? 'readonly class="locked-bg"' : ''; ?>>
        </div>

        <div class="date-group">
            <div class="form-group">
                <label>Jenis</label>
                <select name="jenis_kegiatan" <?php echo $isAdmin ? 'disabled class="locked-bg"' : ''; ?>>
                    <option value="Pendataan" <?php echo (isset($data_edit['jenis_kegiatan']) && $data_edit['jenis_kegiatan'] == 'Pendataan') ? 'selected' : ''; ?>>Pendataan</option>
                    <option value="Pengolahan" <?php echo (isset($data_edit['jenis_kegiatan']) && $data_edit['jenis_kegiatan'] == 'Pengolahan') ? 'selected' : ''; ?>>Pengolahan</option>
                </select>
                <?php if($isAdmin && isset($data_edit['jenis_kegiatan'])): ?> 
                    <input type="hidden" name="jenis_kegiatan" value="<?php echo $data_edit['jenis_kegiatan']; ?>"> 
                <?php endif; ?>
            </div>
            <div class="form-group">
                <label>Satuan Bayar <span style="color:red;">*</span></label>
                <input type="text" name="satuan_bayar" required value="<?php echo htmlspecialchars($data_edit['satuan_bayar'] ?? ''); ?>" <?php echo $isAdmin ? 'readonly class="locked-bg"' : ''; ?>>
            </div>
            <div class="form-group">
                <label>Harga Satuan (Rp)</label>
                <input type="number" name="harga_satuan" value="<?php echo $data_edit['harga_satuan'] ?? ''; ?>" <?php echo (!$isAdmin) ? 'readonly class="locked-bg"' : 'required'; ?>>
            </div>
        </div>

        <div class="date-group">
            <div class="form-group">
                <label>Tgl Mulai (Opsional)</label>
                <?php $tm = (isset($data_edit['tgl_mulai']) && $data_edit['tgl_mulai'] != '0000-00-00') ? $data_edit['tgl_mulai'] : ''; ?>
                <input type="date" name="tgl_mulai" value="<?php echo $tm; ?>" <?php echo $isAdmin ? 'readonly class="locked-bg"' : ''; ?>>
            </div>
            <div class="form-group">
                <label>Tgl Selesai (Opsional)</label>
                <?php $ts = (isset($data_edit['tgl_selesai']) && $data_edit['tgl_selesai'] != '0000-00-00') ? $data_edit['tgl_selesai'] : ''; ?>
                <input type="date" name="tgl_selesai" value="<?php echo $ts; ?>" <?php echo $isAdmin ? 'readonly class="locked-bg"' : ''; ?>>
            </div>
        </div>

        <button type="submit" class="btn-primary">Simpan Data</button>
        <?php if(isset($_GET['id'])): ?> <a href="input_master_aktivitas.php" style="margin-left:10px;">Batal</a> <?php endif; ?>
    </form>
</div>
<?php endif; ?>

<div class="card-container">
    <h2>Daftar Master Aktivitas</h2>
    <table class="styled-table">
        <thead>
            <tr>
                <th>Kegiatan</th>
                <th>Aktivitas</th>
                <th>Rentang Tanggal</th>
                <th>Biaya</th>
                <th width="90px" style="text-align:center;">Aksi</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($master_aktivitas_list as $row): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['nama_detail']); ?></td>
                    <td><?php echo htmlspecialchars($row['nama_aktivitas']); ?></td>
                    <td align="center">
                        <?php 
                        if (!empty($row['tgl_mulai']) && $row['tgl_mulai'] != '0000-00-00') {
                            echo "<b>".date('d/m/y', strtotime($row['tgl_mulai'])) . "</b> - <b>" . date('d/m/y', strtotime($row['tgl_selesai'])) . "</b>";
                        } else {
                            echo "<span style='color:#ccc;'>-</span>";
                        }
                        ?>
                    </td>
                    <td><b>Rp <?php echo number_format($row['harga_satuan']); ?></b><br><small>/ <?php echo $row['satuan_bayar']; ?></small></td>
                    <td align="center" style="white-space:nowrap;">
                        <?php if ($isAdmin): ?>
                            <?php if ($row['harga_satuan'] <= 0): ?>
                                <a href="?action=edit_biaya&id=<?php echo $row['id']; ?>&tahun=<?php echo $selected_tahun_id; ?>" class="action-btn btn-biaya" title="Input Biaya">Rp</a>
                            <?php endif; ?>
                            <a href="?action=hapus&id=<?php echo $row['id']; ?>" class="action-btn btn-delete" title="Hapus" onclick="return confirm('Hapus data ini?')">✕</a>
                        <?php else: ?>
                            <a href="?action=edit&id=<?php echo $row['id']; ?>&tahun=<?php echo $selected_tahun_id; ?>" class="action-btn btn-edit" title="Edit">✎</a>
                            <?php if ($row['harga_satuan'] <= 0): ?>
                                <a href="?action=hapus&id=<?php echo $row['id']; ?>" class="action-btn btn-delete" title="Hapus" onclick="return confirm('Hapus data ini?')">✕</a>
                            <?php endif; ?>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

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