<?php
/**
 * Halaman Bebas Pustaka - Admin
 * Versi 2.0 - Alur baru 3 status (pending, revision, done)
 */

use SLiMS\DB;

defined('INDEX_AUTH') OR die('Direct access not allowed!');

require SB . 'admin/default/session.inc.php';
require SB . 'admin/default/session_check.inc.php';
require SIMBIO . 'simbio_GUI/table/simbio_table.inc.php';
require SIMBIO . 'simbio_GUI/form_maker/simbio_form_table_AJAX.inc.php';
require SIMBIO . 'simbio_GUI/paging/simbio_paging.inc.php';
require SIMBIO . 'simbio_DB/datagrid/simbio_dbgrid.inc.php';

require_once dirname(__DIR__) . '/src/helper.php';

$can_read = utility::havePrivilege('circulation', 'r');
if (!$can_read) die('<div class="errorBox">' . __('Anda tidak memiliki akses!') . '</div>');

$myLib = bpGetLibraryId();
$setting = getSetting($myLib);
$libData = getLibraryData($myLib);
$isSuper = isSuperadmin();
$GLOBALS['myLib'] = $myLib;
$plugin_id = $_GET['id'] ?? '';
$GLOBALS['plugin_id'] = $plugin_id;

$activeTab = isset($_GET['tab']) ? $_GET['tab'] : 'verifikasi';
// ============================================================
// ON THE SPOT - Cetak Langsung
// ============================================================
if (isset($_POST['cetakOnSpot'])) {
    $member_id = trim($_POST['member_id']);
    $keperluan = trim($_POST['keperluan']);
    $library_id = (int)$_POST['library_id'];
    $keterangan = trim($_POST['keterangan'] ?? '');
    $uid = $_SESSION['uid'] ?? 0;
    
    if (empty($member_id) || empty($keperluan) || empty($library_id)) {
        utility::jsToastr('Error', 'Data tidak lengkap!', 'error');
        exit;
    }
    
    // Cek syarat dengan fungsi baru
    $syarat = cekSyaratBebasPustaka($member_id, $library_id);
    if (!$syarat['ok']) {
        utility::jsToastr('Error', 'Member tidak memenuhi syarat: ' . $syarat['message'], 'error');
        exit;
    }
    
    // Cek duplikat pengajuan aktif
    if (cekDuplikatPengajuan($member_id, $library_id)) {
        utility::jsToastr('Error', 'Member masih memiliki pengajuan aktif untuk perpustakaan ini.', 'error');
        exit;
    }
    
    // Submit pengajuan langsung
    $result = submitPengajuan($member_id, $keperluan, $library_id, $keterangan);
    if (!$result['ok']) {
        utility::jsToastr('Error', $result['message'], 'error');
        exit;
    }
    
    // Langsung approve (generate PDF)
    $update = updateStatusPengajuan($result['id'], 'done', '', $uid);
    if ($update) {
        utility::jsToastr('Sukses', 'Surat berhasil dicetak!', 'success');
    } else {
        utility::jsToastr('Error', 'Gagal mencetak surat!', 'error');
    }
    exit;
}
// ============================================================
// PROSES CETAK (Download PDF untuk yang sudah done)
// ============================================================
if (isset($_GET['action']) && $_GET['action'] === 'download_pdf' && isset($_GET['id_pengajuan'])) {
    $id = (int)$_GET['id_pengajuan'];
    
    $st = DB::getInstance()->prepare("
        SELECT file_path FROM bebas_pustaka_history 
        WHERE id = ? AND status = 'done'
    ");
    $st->execute([$id]);
    $history = $st->fetch(PDO::FETCH_ASSOC);
    
    if (!$history || empty($history['file_path']) || !file_exists($history['file_path'])) {
        die('File PDF tidak ditemukan.');
    }
    
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . basename($history['file_path']) . '"');
    header('Content-Length: ' . filesize($history['file_path']));
    readfile($history['file_path']);
    exit;
}

// ============================================================
// CEK MEMBER (untuk On The Spot)
// ============================================================
if (isset($_GET['action']) && $_GET['action'] === 'cekMember' && isset($_GET['member_id'])) {
    $member_id = trim($_GET['member_id']);
    $lib_id = isset($_GET['library_id']) ? (int)$_GET['library_id'] : $myLib;
    
    $db = DB::getInstance();
    
    // Cari member
    $st = $db->prepare("
        SELECT m.member_id, m.member_name, m.inst_name
        FROM member m 
        WHERE m.member_id LIKE ? OR m.member_name LIKE ?
        LIMIT 1
    ");
    $st->execute(["%$member_id%", "%$member_id%"]);
    $member = $st->fetch(PDO::FETCH_ASSOC);
    
    if (!$member) {
        echo json_encode(['ok' => false, 'message' => 'Member tidak ditemukan.']);
        exit;
    }
    
    // Cek syarat dengan fungsi baru
    $syarat = cekSyaratBebasPustaka($member['member_id'], $lib_id);
    $keperluanList = getKeperluanList($lib_id);
    
    // Cek duplikat
    $duplikat = cekDuplikatPengajuan($member['member_id'], $lib_id);
    
    echo json_encode([
        'ok' => true,
        'member' => $member,
        'syarat' => $syarat,
        'keperluan' => $keperluanList,
        'lib_id' => $lib_id,
        'duplikat' => $duplikat
    ]);
    exit;
}
// ============================================================
// REVIEW POPUP
// ============================================================
if (isset($_GET['action']) && $_GET['action'] === 'review_popup' && isset($_GET['id_pengajuan'])) {
    include dirname(__FILE__) . '/verifikasi_popup.php';
    exit;
}

// ============================================================
// DELETE PENGAJUAN (hanya pending atau revision)
// ============================================================
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    $db = DB::getInstance();
    
    $st = $db->prepare("DELETE FROM bebas_pustaka_history WHERE id = ? AND status IN ('pending', 'revision')");
    $st->execute([$id]);
    
    utility::jsToastr('Sukses', 'Pengajuan dihapus.', 'success');
    exit;
}

?>
<div class="menuBox">
    <div class="menuBoxInner memberIcon">
        <div class="per_title"><h2><?= __('Bebas Pustaka') ?></h2></div>
        <div class="sub_section">
            <p><strong><?= $libData['library_name'] ?? 'Perpustakaan' ?></strong> | Mode: <strong>B (Per Perpustakaan)</strong></p>
            
            <ul class="nav nav-tabs" style="margin-bottom:15px;">
                <li class="nav-item">
                    <a class="nav-link <?= $activeTab == 'verifikasi' ? 'active' : '' ?>" 
                       href="plugin_container.php?mod=circulation&id=<?= $_GET['id'] ?? '' ?>&tab=verifikasi">
                        📋 Pengajuan Member
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link <?= $activeTab == 'onspot' ? 'active' : '' ?>" 
                       href="plugin_container.php?mod=circulation&id=<?= $_GET['id'] ?? '' ?>&tab=onspot">
                        ⚡ Cetak Langsung (On The Spot)
                    </a>
                </li>
            </ul>
            
            <?php if ($activeTab == 'verifikasi'): ?>
            <?php
            $table_spec = 'bebas_pustaka_history h 
                LEFT JOIN member m ON h.member_id = m.member_id 
                LEFT JOIN mst_library l ON h.library_id = l.library_id';
            
            $datagrid = new simbio_datagrid();
$datagrid->setSQLColumn(
    'h.id AS `ID`',
    'h.member_id AS `Member ID`',
    'm.member_name AS `Nama`',
    'h.keperluan AS `Keperluan`',
    'l.library_name AS `Tujuan`',
    'h.library_id AS `LibID`',
    'h.status AS `Status`',
    'h.status AS `StatusRaw`',
    'DATE_FORMAT(h.created_at, "%d-%m-%Y") AS `Tanggal`',
    'h.id AS `Aksi`',
    'h.file_path AS `FilePath`'  // 🔥 TAMBAHKAN INI!
);
            $datagrid->setSQLorder('h.created_at DESC');
            
            $criteria = '1=1';
            if ($isSuper) {
                if (isset($_GET['library_id']) && $_GET['library_id'] !== '') {
                    $criteria .= ' AND h.library_id = ' . (int)$_GET['library_id'];
                }
            } else {
                $criteria .= ' AND h.library_id = ' . $myLib;
            }
            if (isset($_GET['status']) && $_GET['status'] !== '') {
                $criteria .= " AND h.status = '" . $dbs->escape_string($_GET['status']) . "'";
            }
            $datagrid->setSQLCriteria($criteria);
            $datagrid->table_attr = 'id="dataList" class="s-table table"';
            $datagrid->table_header_attr = 'class="dataListHeader" style="font-weight: bold;"';
            $datagrid->edit_property = false;
            
            // ============================================================
            // STATUS BADGE - HANYA 3 STATUS
            // ============================================================
            function statusBadge($db, $row) {
                $status = is_array($row) ? $row[6] : $row;
                $badges = [
                    'pending' => '<span class="badge badge-warning">⏳ Pending</span>',
                    'revision' => '<span class="badge" style="background:#ff9800;color:#fff;">🔄 Revisi</span>',
                    'done' => '<span class="badge badge-success">✅ Selesai</span>'
                ];
                return $badges[$status] ?? $status;
            }
            
            // ============================================================
            // TOMBOL AKSI - HANYA 3 STATUS
            // ============================================================
function aksiButton($db, $row) {
    $id = is_array($row) ? $row[9] : $row;
    $status = is_array($row) ? $row[7] : '';
    $library_id = is_array($row) ? (int)$row[5] : 0;
    $file_path = is_array($row) ? ($row[10] ?? '') : ''; // 🔥 Index 10 = file_path
    
    // 🔥 AMBIL FILE_PATH dari row (kolom ke-5 adalah file_path)
    $file_path = '';
    if (is_array($row) && isset($row[5])) {
        // Kolom ke-5 di SQL adalah file_path? Cek setSQLColumn
        // Di setSQLColumn, urutan: ID, member_id, nama, keperluan, tujuan, LibID, status, statusRaw, tanggal, aksi
        // Index 0=ID, 1=member_id, 2=nama, 3=keperluan, 4=tujuan, 5=LibID, 6=status, 7=statusRaw, 8=tanggal, 9=aksi
        // file_path tidak ada di SELECT! Kita perlu tambahkan.
        $file_path = $row[5] ?? ''; // Ini sebenarnya LibID, bukan file_path
    }
    
    // 🔥 CARA LAIN: Ambil file_path dari database langsung
    if ($status == 'done') {
        $db = DB::getInstance();
        $st = $db->prepare("SELECT file_path FROM bebas_pustaka_history WHERE id = ?");
        $st->execute([$id]);
        $result = $st->fetch(PDO::FETCH_ASSOC);
        $file_path = $result['file_path'] ?? '';
    }
    
    $myLib = bpGetLibraryId();
    $isSuper = isSuperadmin();
    $isPusat = ($myLib == 1);
    $plugin_id = $GLOBALS['plugin_id'] ?? '';
    
    $hasAccess = false;
    if ($isSuper || $isPusat || $myLib == $library_id) {
        $hasAccess = true;
    }
    if (!$hasAccess) {
        return '<span class="text-muted">Tidak ada akses</span>';
    }
    
    $html = '';
    
    // ============================================================
    // STATUS PENDING: Review
    // ============================================================
    if ($status == 'pending') {
        $html .= '<button class="btn btn-sm btn-primary" onclick="reviewModal(' . $id . ')">📋 Review</button> ';
        $html .= '<button class="btn btn-sm btn-danger" onclick="deletePengajuan(' . $id . ')">🗑️ Hapus</button>';
    } 
    // ============================================================
    // STATUS REVISION: Review
    // ============================================================
    elseif ($status == 'revision') {
        $html .= '<button class="btn btn-sm btn-primary" onclick="reviewModal(' . $id . ')">📋 Review</button> ';
        $html .= '<button class="btn btn-sm btn-danger" onclick="deletePengajuan(' . $id . ')">🗑️ Hapus</button>';
    } 
    // ============================================================
    // STATUS DONE: Download PDF
    // ============================================================
    elseif ($status == 'done') {
        if (!empty($file_path) && file_exists($file_path)) {
            $html .= '<a href="plugin_container.php?mod=circulation&id=' . $plugin_id . '&action=download_pdf&id_pengajuan=' . $id . '" class="btn btn-sm btn-success" target="_blank">📥 Download PDF</a>';
        } else {
            $html .= '<span class="text-muted">PDF tidak tersedia</span>';
        }
    }
    
    return $html;
}
            
            $datagrid->modifyColumnContent(6, 'callback{statusBadge}');
            $datagrid->modifyColumnContent(9, 'callback{aksiButton}');
            
            // ============================================================
            // FILTER - HANYA 3 STATUS
            // ============================================================
            echo '<div class="form-inline mb-3">';
            echo '<label class="mr-2">Filter Status:</label>';
            echo '<select class="form-control mr-2" onchange="filterStatus(this.value)">';
            echo '<option value="">Semua</option>';
            echo '<option value="pending" ' . (isset($_GET['status']) && $_GET['status'] == 'pending' ? 'selected' : '') . '>Pending</option>';
            echo '<option value="revision" ' . (isset($_GET['status']) && $_GET['status'] == 'revision' ? 'selected' : '') . '>Revisi</option>';
            echo '<option value="done" ' . (isset($_GET['status']) && $_GET['status'] == 'done' ? 'selected' : '') . '>Selesai</option>';
            echo '</select>';
            
            if ($isSuper) {
                echo '<label class="ml-3 mr-2">Perpustakaan:</label>';
                echo '<select class="form-control mr-2" onchange="filterLibrary(this.value)">';
                echo '<option value="">Semua</option>';
                $libOptions = $dbs->query('SELECT library_id, library_name FROM mst_library ORDER BY library_name');
                while ($l = $libOptions->fetch_assoc()) {
                    $selected = (isset($_GET['library_id']) && $_GET['library_id'] == $l['library_id']) ? 'selected' : '';
                    echo '<option value="' . $l['library_id'] . '" ' . $selected . '>' . $l['library_name'] . '</option>';
                }
                echo '</select>';
            }
            echo '<button class="btn btn-sm btn-secondary ml-2" onclick="resetFilter()">Reset</button>';
            echo '</div>';
            
            echo '<script>
            function filterStatus(val) {
                var url = window.location.href.split("?")[0] + "?mod=circulation&id=' . $_GET['id'] . '&tab=verifikasi&status=" + val;
                parent.jQuery("#mainContent").simbioAJAX(url);
            }
            function filterLibrary(val) {
                var url = window.location.href.split("?")[0] + "?mod=circulation&id=' . $_GET['id'] . '&tab=verifikasi&library_id=" + val;
                parent.jQuery("#mainContent").simbioAJAX(url);
            }
            function resetFilter() {
                var url = window.location.href.split("?")[0] + "?mod=circulation&id=' . $_GET['id'] . '&tab=verifikasi";
                parent.jQuery("#mainContent").simbioAJAX(url);
            }
            </script>';
            
            echo $datagrid->createDataGrid($dbs, $table_spec, 20, true);
            ?>
            
            <script>
            function reviewModal(id) {
                var popupUrl = 'plugin_container.php?mod=circulation&id=<?= $_GET['id'] ?? '' ?>&action=review_popup&id_pengajuan=' + id;
                $.colorbox({
                    href: popupUrl,
                    iframe: true,
                    width: '90%',
                    height: '90%',
                    maxWidth: '850px',
                    maxHeight: '700px',
                    title: 'Review Pengajuan Bebas Pustaka',
                    onClosed: function() {
                        location.reload();
                    }
                });
            }
            
            function deletePengajuan(id) {
                if (confirm('Hapus pengajuan ini?')) {
                    var url = 'plugin_container.php?mod=circulation&id=<?= $_GET['id'] ?? '' ?>&action=delete&id=' + id;
                    parent.jQuery("#mainContent").simbioAJAX(url);
                }
            }
            </script>
            
            <?php elseif ($activeTab == 'onspot'): ?>
            <!-- ONS POT SECTION (sama seperti sebelumnya) -->
            <div class="infoBox">
                <strong>⚡ Cetak Langsung (On The Spot)</strong><br>
                <small>Untuk member yang datang langsung ke perpustakaan.</small>
            </div>
            <div style="padding:15px 0;">
                <div class="form-inline">
                    <label class="mr-2">Cari Member:</label>
                    <input type="text" id="onspotSearch" class="form-control mr-2" placeholder="ID atau Nama" style="width:250px;">
                    <?php if ($isSuper || bpGetLibraryId() == 1): ?>
                    <label class="ml-2 mr-2">Tujuan:</label>
                    <select id="onspotLib" class="form-control mr-2">
                        <?php
                        $libOptions = $dbs->query('SELECT library_id, library_name FROM mst_library ORDER BY library_name');
                        while ($l = $libOptions->fetch_assoc()):
                        ?>
                        <option value="<?= $l['library_id'] ?>" <?= ($l['library_id'] == $myLib) ? 'selected' : '' ?>>
                            <?= $l['library_name'] ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                    <?php else: ?>
                    <input type="hidden" id="onspotLib" value="<?= $myLib ?>">
                    <?php endif; ?>
                    <button class="btn btn-primary" onclick="cekMemberOnSpot()">🔍 Cek</button>
                </div>
            </div>
            <div id="onspotResult" style="display:none; padding:15px; border:1px solid #ddd; border-radius:5px; margin-top:10px;">
                <div id="onspotMemberInfo"></div>
                <div id="onspotSyarat"></div>
                <div id="onspotForm" style="display:none;"></div>
            </div>
            <script>
function cekMemberOnSpot() {
    var search = document.getElementById('onspotSearch').value.trim();
    var libId = document.getElementById('onspotLib').value;
    if (!search) { alert('Masukkan ID atau Nama Member!'); return; }
    
    var baseUrl = 'plugin_container.php?mod=circulation&id=<?= $_GET['id'] ?? '' ?>';
    var url = baseUrl + '&action=cekMember&member_id=' + encodeURIComponent(search) + '&library_id=' + libId;
    
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            var resultDiv = document.getElementById('onspotResult');
            resultDiv.style.display = 'block';
            if (!response.ok) {
                document.getElementById('onspotMemberInfo').innerHTML = '<div class="alert alert-danger">' + response.message + '</div>';
                document.getElementById('onspotSyarat').innerHTML = '';
                document.getElementById('onspotForm').style.display = 'none';
                return;
            }
            var m = response.member;
            var syarat = response.syarat;
            var duplikat = response.duplikat || false;
            
            var html = '<table class="table table-sm">';
            html += '<tr><td>Member ID</td><td><strong>' + m.member_id + '</strong></td></tr>';
            html += '<tr><td>Nama</td><td><strong>' + m.member_name + '</strong></td></tr>';
            html += '</table>';
            document.getElementById('onspotMemberInfo').innerHTML = html;
            
            var syaratHtml = '<div class="alert alert-' + (syarat.ok ? 'success' : 'danger') + '">';
            syaratHtml += '<strong>' + (syarat.ok ? '✅ Member Bersih' : '❌ Member Bermasalah') + '</strong><br>';
            syaratHtml += syarat.message;
            if (!syarat.ok && syarat.pinjam && syarat.pinjam.length > 0) {
                syaratHtml += '<br><small><ul>';
                syarat.pinjam.forEach(function(p) {
                    syaratHtml += '<li>' + p.title + ' (' + p.item_code + ') - Due: ' + p.due_date + '</li>';
                });
                syaratHtml += '</ul></small>';
            }
            syaratHtml += '</div>';
            document.getElementById('onspotSyarat').innerHTML = syaratHtml;
            
            if (syarat.ok && !duplikat) {
                var baseUrl = 'plugin_container.php?mod=circulation&id=<?= $_GET['id'] ?? '' ?>';
                var formHtml = '<form id="onspotFormData" method="post" action="' + baseUrl + '">';
                formHtml += '<input type="hidden" name="member_id" value="' + m.member_id + '">';
                formHtml += '<input type="hidden" name="library_id" value="' + response.lib_id + '">';
                formHtml += '<div class="form-group">';
                formHtml += '<label>Keperluan:</label>';
                formHtml += '<select name="keperluan" class="form-control">';
                response.keperluan.forEach(function(k) {
                    formHtml += '<option value="' + k.keperluan + '">' + k.keperluan + '</option>';
                });
                formHtml += '</select>';
                formHtml += '</div>';
                formHtml += '<div class="form-group">';
                formHtml += '<label>Keterangan (opsional):</label>';
                formHtml += '<input type="text" name="keterangan" class="form-control" placeholder="Catatan tambahan...">';
                formHtml += '</div>';
                formHtml += '<button type="button" class="btn btn-primary" onclick="cetakOnSpot()">🖨️ Cetak Surat</button>';
                formHtml += '</form>';
                document.getElementById('onspotForm').innerHTML = formHtml;
                document.getElementById('onspotForm').style.display = 'block';
            } else if (duplikat) {
                document.getElementById('onspotForm').innerHTML = '<div class="alert alert-warning">Member masih memiliki pengajuan aktif untuk perpustakaan ini.</div>';
                document.getElementById('onspotForm').style.display = 'block';
            } else {
                document.getElementById('onspotForm').style.display = 'none';
            }
        }
    });
}

function cetakOnSpot() {
    var form = document.getElementById('onspotFormData');
    var formData = new FormData(form);
    formData.append('cetakOnSpot', 1);
    
    var baseUrl = 'plugin_container.php?mod=circulation&id=<?= $_GET['id'] ?? '' ?>';
    
    $.ajax({
        url: baseUrl,
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function() { 
            location.reload(); 
        },
        error: function() {
            alert('Gagal mencetak surat. Silakan coba lagi.');
        }
    });
}
            </script>
            <?php endif; ?>
        </div>
    </div>
</div>