<?php
$page_title = "Data Pengajuan";
include 'layout/header.php';
include 'layout/sidebar.php';
require_once '../config.php';

// Proses Update Status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id_pengajuan'])) {
    $id_pengajuan = $_POST['id_pengajuan'];
    $status_baru = $_POST['status'];
    $keterangan_admin = trim($_POST['keterangan_admin']);

    $stmt_get = $pdo->prepare("SELECT * FROM tbl_pengajuan WHERE id = ?");
    $stmt_get->execute([$id_pengajuan]);
    $data = $stmt_get->fetch();

    if ($data) {
        $surat_balasan_query = "";
        $params = [$status_baru, $keterangan_admin];

        // Handle File Upload Surat Balasan
        if (isset($_FILES['surat_balasan']) && $_FILES['surat_balasan']['error'] == 0) {
            $allowed = ['pdf', 'jpg', 'jpeg', 'png'];
            $filename = $_FILES['surat_balasan']['name'];
            $file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
            if (in_array($file_ext, $allowed)) {
                $new_filename = time() . '_surat_' . bin2hex(random_bytes(4)) . '.' . $file_ext;
                if (move_uploaded_file($_FILES['surat_balasan']['tmp_name'], '../uploads/' . $new_filename)) {
                    $surat_balasan_query = ", surat_balasan = ?";
                    $params[] = $new_filename;
                    $data->surat_balasan = $new_filename; // Update current object for notification
                }
            }
        }

        $params[] = $id_pengajuan;
        $stmt_up = $pdo->prepare("UPDATE tbl_pengajuan SET status = ?, keterangan_admin = ? {$surat_balasan_query} WHERE id = ?");
        $stmt_up->execute($params);

        $link_track = base_url("track.php?tiket=$data->no_tiket");
        $link_surat = !empty($data->surat_balasan) ? base_url("uploads/".$data->surat_balasan) : '-';
        $link_surat_html = !empty($data->surat_balasan) ? "<a href='{$link_surat}' style='padding: 8px 16px; background-color: #0d6efd; color: #ffffff; text-decoration: none; border-radius: 5px; display: inline-block; font-weight: bold;'>Unduh Surat Balasan</a>" : '-';

        // Notifikasi WA
        $tpl_wa = getSetting($pdo, 'tpl_wa_update');
        if (!empty($tpl_wa)) {
            $tpl_wa = str_replace('[NAMA]', $data->nama_lengkap, $tpl_wa);
            $tpl_wa = str_replace('[TIKET]', $data->no_tiket, $tpl_wa);
            $tpl_wa = str_replace('[STATUS]', strtoupper($status_baru), $tpl_wa);
            $tpl_wa = str_replace('[CATATAN]', empty($keterangan_admin) ? '-' : $keterangan_admin, $tpl_wa);
            $tpl_wa = str_replace('[LINK_TRACKING]', $link_track, $tpl_wa);
            $tpl_wa = str_replace('[LINK_SURAT]', '', $tpl_wa); // Dihapus karena dilampirkan langsung
            
            $file_url_wa = isset($new_filename) ? base_url("uploads/".$new_filename) : '';
            @sendWhatsApp($data->no_telp, $tpl_wa, $file_url_wa);
        }

        // Notifikasi Email
        $tpl_email = getSetting($pdo, 'tpl_email_update');
        if (!empty($tpl_email)) {
            $tpl_email = str_replace('[NAMA]', htmlspecialchars($data->nama_lengkap), $tpl_email);
            $tpl_email = str_replace('[TIKET]', htmlspecialchars($data->no_tiket), $tpl_email);
            $tpl_email = str_replace('[STATUS]', strtoupper($status_baru), $tpl_email);
            $tpl_email = str_replace('[CATATAN]', empty($keterangan_admin) ? '-' : nl2br(htmlspecialchars($keterangan_admin)), $tpl_email);
            $tpl_email = str_replace('[LINK_TRACKING]', $link_track, $tpl_email);
            $tpl_email = str_replace('[LINK_SURAT]', '', $tpl_email); // Dihapus karena dilampirkan langsung
            
            $file_path_email = isset($new_filename) ? '../uploads/'.$new_filename : '';
            $em_subj = "Update Status - $data->no_tiket";
            @sendEmail($data->email, $em_subj, $tpl_email, $file_path_email);
        }

        echo "<script>
            document.addEventListener('DOMContentLoaded', function() {
                Swal.fire({
                    icon: 'success',
                    title: 'Berhasil!',
                    text: 'Status berhasil diperbarui & notifikasi terkirim.',
                    timer: 2000,
                    showConfirmButton: false,
                    position: 'center'
                }).then(() => { window.location.href='data_pengajuan2.php'; });
            });
        </script>";
    }
}

// Ambil Data
$stmt = $pdo->query("SELECT * FROM tbl_pengajuan ORDER BY created_at DESC");
$pengajuan = $stmt->fetchAll();
?>

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <h1 class="m-0">Kelola Data Pengajuan</h1>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped datatable align-middle">
                            <thead class="bg-navy text-white">
                                <tr>
                                    <th>No. Tiket</th>
                                    <th>Tanggal</th>
                                    <th>Nama Pemohon</th>
                                    <th>Kontak (WA & Email)</th>
                                    <th>Asal Instansi & Kota</th>
                                    <th>Tujuan</th>
                                    <th>Status</th>
                                    <th class="text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($pengajuan as $row): ?>
                                <tr>
                                    <td class="font-weight-bold"><?= htmlspecialchars($row->no_tiket) ?></td>
                                    <td><?= date('d/m/Y H:i', strtotime($row->created_at)) ?></td>
                                    <td><?= htmlspecialchars($row->nama_lengkap) ?></td>
                                    <td>
                                        <small>
                                            <i class="fab fa-whatsapp text-success"></i> <?= htmlspecialchars($row->no_telp) ?><br>
                                            <i class="far fa-envelope text-primary"></i> <?= htmlspecialchars($row->email) ?>
                                        </small>
                                    </td>
                                    <td>
                                        <?= htmlspecialchars($row->asal_instansi) ?><br>
                                        <small class="text-muted"><i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($row->kota) ?></small>
                                    </td>
                                    <td><?= htmlspecialchars($row->tujuan) ?></td>
                                    <td>
                                        <?php if($row->status == 'diterima'): ?>
                                            <span class="badge badge-secondary">Diterima</span>
                                        <?php elseif($row->status == 'diverifikasi'): ?>
                                            <span class="badge badge-primary">Diverifikasi</span>
                                        <?php elseif($row->status == 'diproses'): ?>
                                            <span class="badge badge-warning">Diproses</span>
                                        <?php elseif($row->status == 'selesai'): ?>
                                            <span class="badge badge-success">Selesai</span>
                                        <?php else: ?>
                                            <span class="badge badge-danger">Ditolak</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <div class="btn-group">
                                            <?php if($row->status == 'selesai' || $row->status == 'ditolak'): ?>
                                                <button class="btn btn-sm btn-info" onclick='lihatDetail(<?= htmlspecialchars(json_encode($row), ENT_QUOTES, "UTF-8") ?>)'><i class="fas fa-eye"></i> Detail</button>
                                            <?php else: ?>
                                                <button class="btn btn-sm btn-primary" onclick='lihatDetail(<?= htmlspecialchars(json_encode($row), ENT_QUOTES, "UTF-8") ?>)'><i class="fas fa-search"></i> Proses</button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- Modal Detail & Update -->
<div class="modal fade" id="modalDetail" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form action="data_pengajuan2.php" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="id_pengajuan" id="m_id_pengajuan">
                <div class="modal-header bg-navy text-white">
                    <h5 class="modal-title">Detail & Proses Pengajuan</h5>
                    <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>No. Tiket:</strong> <span id="m_tiket" class="text-primary font-weight-bold"></span></p>
                            <p><strong>Waktu Masuk:</strong> <span id="m_tgl"></span></p>
                            <p><strong>Nama:</strong> <span id="m_nama"></span></p>
                            <p><strong>Instansi:</strong> <span id="m_instansi"></span></p>
                            <p><strong>Tujuan:</strong> <span id="m_tujuan"></span></p>
                            <p><strong>Kontak:</strong> <span id="m_wa"></span> / <span id="m_email"></span></p>
                        </div>
                        <div class="col-md-6">
                            <p><strong>Alamat:</strong> <br><span id="m_alamat"></span></p>
                            <p><strong>Catatan User:</strong> <br><span id="m_catatan" class="text-muted"></span></p>
                            <p>
                                <strong>File Lampiran:</strong><br>
                                <a href="#" id="m_file_link" target="_blank" class="btn btn-sm btn-outline-info"><i class="fas fa-download"></i> Unduh File</a>
                            </p>
                        </div>
                    </div>
                    <hr>
                    <div class="form-group">
                        <label>Update Status</label>
                        <select name="status" id="m_status" class="form-control" required>
                            <option value="diterima">Diterima</option>
                            <option value="diverifikasi">Diverifikasi</option>
                            <option value="diproses">Diproses</option>
                            <option value="selesai">Selesai</option>
                            <option value="ditolak">Ditolak</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Upload Surat Balasan (Opsional)</label>
                        <input type="file" name="surat_balasan" class="form-control" accept=".pdf,.jpg,.jpeg,.png">
                        <small class="text-muted">Jika pengajuan selesai/disetujui, Anda dapat melampirkan surat balasan (PDF/Gambar).</small>
                    </div>
                    <div class="form-group">
                        <label>Catatan Admin (Akan dikirim ke WA/Email user)</label>
                        <textarea name="keterangan_admin" id="m_ket_admin" class="form-control" rows="3" placeholder="Tambahkan alasan penolakan atau instruksi selanjutnya..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
                    <button type="submit" class="btn btn-primary" id="btn_simpan_modal"><i class="fas fa-save"></i> Simpan & Kirim Notifikasi</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function lihatDetail(data) {
    // Prevent XSS when inserting into DOM by using innerText
    document.getElementById('m_id_pengajuan').value = data.id;
    document.getElementById('m_tiket').innerText = data.no_tiket;
    document.getElementById('m_tgl').innerText = data.created_at;
    document.getElementById('m_nama').innerText = data.nama_lengkap;
    document.getElementById('m_instansi').innerText = data.asal_instansi;
    document.getElementById('m_tujuan').innerText = data.tujuan;
    document.getElementById('m_wa').innerText = data.no_telp;
    document.getElementById('m_email').innerText = data.email;
    document.getElementById('m_alamat').innerText = data.alamat + ', ' + data.kota + ', ' + data.provinsi;
    document.getElementById('m_catatan').innerText = data.catatan ? data.catatan : '-';
    
    document.getElementById('m_file_link').href = 'preview.php?f=' + data.file_lampiran;
    
    document.getElementById('m_status').value = data.status;
    document.getElementById('m_ket_admin').value = data.keterangan_admin ? data.keterangan_admin : '';

    let isLocked = (data.status === 'selesai' || data.status === 'ditolak');
    document.getElementById('m_status').disabled = isLocked;
    document.getElementById('m_ket_admin').disabled = isLocked;
    document.querySelector('input[name="surat_balasan"]').disabled = isLocked;
    
    let btnSimpan = document.getElementById('btn_simpan_modal');
    if(isLocked) {
        btnSimpan.disabled = true;
        btnSimpan.innerHTML = '<i class="fas fa-lock"></i> Terkunci';
        btnSimpan.classList.remove('btn-primary');
        btnSimpan.classList.add('btn-secondary');
    } else {
        btnSimpan.disabled = false;
        btnSimpan.innerHTML = '<i class="fas fa-save"></i> Simpan & Kirim Notifikasi';
        btnSimpan.classList.remove('btn-secondary');
        btnSimpan.classList.add('btn-primary');
    }

    $('#modalDetail').modal('show');
}
</script>

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