<?php
/**
 * Halaman Pop Up Review Bebas Pustaka
 * Path: plugins/bebas_pustaka/pages/verifikasi_popup.php
 * Version: 2.0.0 - Alur baru 3 status (pending, revision, done)
 */

require_once SB . 'sysconfig.inc.php';
require_once LIB . 'ip_based_access.inc.php';
do_checkIP('smc');
do_checkIP('smc-reporting');

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

use SLiMS\DB;

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

// ============================================================
// AMBIL LIBRARY ID DARI SESSION
// ============================================================
$current_library_id = isset($_SESSION['library_id']) ? (int)$_SESSION['library_id'] : 1;

$id = isset($_GET['id_pengajuan']) ? (int)$_GET['id_pengajuan'] : 0;
if (!$id) {
    die('<div class="alert alert-danger">ID pengajuan tidak valid!</div>');
}

$db = DB::getInstance();

// ============================================================
// AMBIL DATA PENGAJUAN
// ============================================================
$st = $db->prepare("
    SELECT h.*, m.member_name, l.library_name 
    FROM 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
    WHERE h.id = ?
      AND h.library_id = ?
");
$st->execute([$id, $current_library_id]);
$data = $st->fetch(PDO::FETCH_ASSOC);

if (!$data) {
    die('<div class="alert alert-danger">Data pengajuan tidak ditemukan atau anda tidak memiliki akses!</div>');
}

// ============================================================
// CEK SYARAT (PINJAMAN + DENDA)
// ============================================================
$syarat = cekSyaratBebasPustaka($data['member_id'], $data['library_id']);

// ============================================================
// HANDLER REVIEW
// ============================================================
if (isset($_POST['reviewAction'])) {
    $action = $_POST['reviewAction'];
    $reason = trim($_POST['reason'] ?? '');
    $uid = $_SESSION['uid'] ?? 0;
    
    if ($action == 'approve') {
        // Approve → status menjadi done
        $result = updateStatusPengajuan($id, 'done', '', $uid);
        $msg = 'Pengajuan disetujui dan surat berhasil dibuat.';
    } elseif ($action == 'revision') {
        if (empty($reason)) {
            echo '<div class="alert alert-danger">Alasan revisi harus diisi!</div>';
            exit;
        }
        $result = updateStatusPengajuan($id, 'revision', $reason, $uid);
        $msg = 'Pengajuan dikembalikan untuk revisi.';
    } elseif ($action == 'batal') {
        // Batal → tidak ada perubahan, tutup popup
        echo '<script>parent.jQuery.colorbox.close();</script>';
        exit;
    } else {
        echo '<div class="alert alert-danger">Aksi tidak dikenal!</div>';
        exit;
    }
    
    if ($result) {
        echo '<div class="alert alert-success">' . $msg . ' <strong>Klik Tutup untuk refresh halaman.</strong></div>';
        echo '<script>
            setTimeout(function() {
                parent.jQuery.colorbox.close();
                parent.location.reload();
            }, 1500);
        </script>';
    } else {
        echo '<div class="alert alert-danger">Gagal memproses!</div>';
    }
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Review Pengajuan Bebas Pustaka</title>
    <link href="<?= SWB ?>template/default/assets/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <style>
        body { padding: 20px; background: #f8f9fa; }
        .card { margin-bottom: 15px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        .card-header { background: #fff; font-weight: bold; border-bottom: 2px solid #eee; }
        .table { font-size: 13px; }
        .table th { background: #f1f3f5; }
        .badge { font-size: 12px; padding: 4px 8px; }
        .btn { padding: 8px 20px; }
        .container-fluid { max-width: 850px; margin: 0 auto; }
        .library-info { background: #e7f3ff; padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; }
        .btn-warning-custom { background: #ff9800; border-color: #ff9800; color: #fff; }
        .btn-warning-custom:hover { background: #e68900; border-color: #e68900; color: #fff; }
    </style>
</head>
<body>
<div class="container-fluid">
    
    <!-- INFO PERPUSTAKAAN -->
    <div class="library-info">
        <i class="fa fa-building"></i> 
        <strong><?= __('Perpustakaan') ?>:</strong> 
        <?= htmlspecialchars(getLibraryNameById($current_library_id)) ?>
        <span class="text-muted small">| <?= __('Hanya data dari perpustakaan ini yang ditampilkan.') ?></span>
    </div>

    <h4 class="mb-3">📋 Review Pengajuan</h4>
    
    <!-- DATA MEMBER -->
    <div class="card">
        <div class="card-header">👤 Data Member</div>
        <div class="card-body">
            <table class="table table-bordered table-sm mb-0">
                <tr><td style="width:120px;font-weight:bold;">Member ID</td><td><strong><?= htmlspecialchars($data['member_id']) ?></strong></td></tr>
                <tr><td style="font-weight:bold;">Nama</td><td><strong><?= htmlspecialchars($data['member_name']) ?></strong></td></tr>
                <tr><td style="font-weight:bold;">Keperluan</td><td><?= htmlspecialchars($data['keperluan']) ?></td></tr>
                <tr><td style="font-weight:bold;">Tujuan</td><td><?= htmlspecialchars($data['library_name']) ?></td></tr>
            </table>
        </div>
    </div>
    
    <!-- STATUS SYARAT -->
    <div class="card">
        <div class="card-header">📊 Status Member</div>
        <div class="card-body">
            <div class="alert alert-<?= $syarat['ok'] ? 'success' : 'danger' ?>">
                <strong><?= $syarat['ok'] ? '✅ Member BERSIH' : '❌ Member BERMASALAH' ?></strong><br>
                <?= htmlspecialchars($syarat['message']) ?>
                <?php if (!$syarat['ok']): ?>
                <br><small><?= __('Pastikan semua pinjaman telah dikembalikan dan denda telah lunas.') ?></small>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- PINJAMAN AKTIF -->
    <div class="card">
        <div class="card-header">📖 Pinjaman Aktif</div>
        <div class="card-body">
            <?php if (!empty($syarat['pinjam'])): ?>
                <table class="table table-sm table-bordered mb-0">
                    <tr><th>Judul</th><th>Kode Item</th><th>Tanggal Pinjam</th><th>Jatuh Tempo</th></tr>
                    <?php foreach ($syarat['pinjam'] as $p): ?>
                    <tr>
                        <td><?= htmlspecialchars($p['title']) ?></td>
                        <td><?= htmlspecialchars($p['item_code']) ?></td>
                        <td><?= htmlspecialchars($p['loan_date']) ?></td>
                        <td class="text-danger"><?= htmlspecialchars($p['due_date']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
                <small class="text-danger mt-2 d-block">⚠️ Member harus mengembalikan semua pinjaman terlebih dahulu.</small>
            <?php else: ?>
                <div class="text-success">✅ Tidak ada pinjaman aktif</div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- DENDA -->
    <div class="card">
        <div class="card-header">💰 Denda / Sisa Hutang</div>
        <div class="card-body">
            <?php if (!empty($syarat['denda_detail'])): ?>
                <table class="table table-sm table-bordered mb-0">
                    <tr><th>Tanggal</th><th>Deskripsi</th><th>Sisa</th><th>Status</th></tr>
                    <?php foreach ($syarat['denda_detail'] as $d): ?>
                    <tr>
                        <td><?= htmlspecialchars($d['fines_date']) ?></td>
                        <td><?= htmlspecialchars($d['description'] ?? '-') ?></td>
                        <td class="text-danger font-weight-bold">Rp <?= number_format($d['remaining'], 0, ',', '.') ?></td>
                        <td><span class="badge badge-<?= $d['status'] == 'paid' ? 'success' : ($d['status'] == 'partial' ? 'warning' : 'danger') ?>"><?= htmlspecialchars($d['status']) ?></span></td>
                    </tr>
                    <?php endforeach; ?>
                </table>
                <div class="mt-2"><strong class="text-danger">Total Sisa Hutang: Rp <?= number_format($syarat['denda_total'], 0, ',', '.') ?></strong></div>
                <small class="text-danger d-block">⚠️ Member harus melunasi semua denda terlebih dahulu.</small>
            <?php else: ?>
                <div class="text-success">✅ Tidak ada denda / sisa hutang</div>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- KESIMPULAN -->
    <div class="card">
        <div class="card-header">📌 Kesimpulan</div>
        <div class="card-body">
            <?php if ($syarat['ok']): ?>
                <div class="text-success font-weight-bold">✅ Member LAYAK untuk diterbitkan surat bebas pustaka.</div>
            <?php else: ?>
                <div class="text-danger font-weight-bold">❌ Member TIDAK LAYAK untuk diterbitkan surat bebas pustaka.</div>
                <?php if (!empty($syarat['pinjam'])): ?>
                    <div>📖 <?= count($syarat['pinjam']) ?> buku belum dikembalikan.</div>
                <?php endif; ?>
                <?php if ($syarat['denda_total'] > 0): ?>
                    <div>💰 Sisa hutang Rp <?= number_format($syarat['denda_total'], 0, ',', '.') ?></div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- ============================================================
    AKSI REVIEW - 3 OPSI: Approve, Revisi, Batal
    ============================================================ -->
    <div class="card">
        <div class="card-header">⚡ Aksi</div>
        <div class="card-body">
            <form method="post" id="reviewForm">
                <!-- Textarea untuk revisi -->
                <div id="reasonContainer" style="display:none; margin-bottom:10px;">
                    <textarea name="reason" id="reasonText" class="form-control" rows="2" placeholder="Masukkan alasan revisi..."></textarea>
                </div>
                
                <div class="row">
                    <!-- Opsi 1: Approve (LANGSUNG SUBMIT) -->
                    <div class="col-md-4">
                        <?php if ($syarat['ok']): ?>
                            <button type="button" class="btn btn-success btn-block" style="width:100%;" onclick="submitApprove()">
                                ✅ Approve
                            </button>
                        <?php else: ?>
                            <button type="button" class="btn btn-secondary btn-block" style="width:100%;" disabled>
                                ✅ Approve (Tidak Lolos)
                            </button>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Opsi 2: Revisi -->
                    <div class="col-md-4">
                        <button type="button" class="btn btn-warning btn-block" style="width:100%;background:#ff9800;border-color:#ff9800;color:#fff;" onclick="showReason()">
                            🔄 Revisi
                        </button>
                        <div id="submitContainer" style="display:none; margin-top:10px;">
                            <button type="button" id="submitBtn" class="btn btn-warning btn-block" style="width:100%;background:#ff9800;border-color:#ff9800;color:#fff;" onclick="submitRevision()">
                                Kirim Revisi
                            </button>
                            <button type="button" class="btn btn-secondary btn-block" onclick="cancelReason()">
                                Batal
                            </button>
                        </div>
                    </div>
                    
                    <!-- Opsi 3: Batal -->
                    <div class="col-md-4">
                        <button type="button" class="btn btn-secondary btn-block" style="width:100%;" onclick="submitBatal()">
                            ❌ Batal
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <div class="text-center mt-3">
        <button class="btn btn-secondary" onclick="parent.jQuery.colorbox.close()">Tutup</button>
    </div>
</div>

<script>
// ============================================================
// FUNGSI UNTUK APPROVE (LANGSUNG SUBMIT, TANPA TEXTAREA)
// ============================================================
function submitApprove() {
    var form = document.getElementById('reviewForm');
    
    // Hapus hidden action lama jika ada
    var oldHidden = form.querySelector('input[name="reviewAction"]');
    if (oldHidden) {
        oldHidden.remove();
    }
    
    // Tambahkan hidden input untuk action
    var hiddenAction = document.createElement('input');
    hiddenAction.type = 'hidden';
    hiddenAction.name = 'reviewAction';
    hiddenAction.value = 'approve';
    form.appendChild(hiddenAction);
    
    // Submit form
    form.submit();
}

// ============================================================
// FUNGSI UNTUK REVISI (TAMPILKAN TEXTAREA)
// ============================================================
function showReason() {
    document.getElementById('reasonContainer').style.display = 'block';
    document.getElementById('submitContainer').style.display = 'block';
    document.getElementById('reasonText').value = '';
    document.getElementById('reasonText').focus();
}

function cancelReason() {
    document.getElementById('reasonContainer').style.display = 'none';
    document.getElementById('submitContainer').style.display = 'none';
    document.getElementById('reasonText').value = '';
}

function submitRevision() {
    var textarea = document.getElementById('reasonText');
    var reason = textarea.value.trim();
    
    if (reason === '') {
        alert('Alasan revisi harus diisi!');
        textarea.focus();
        return false;
    }
    
    var form = document.getElementById('reviewForm');
    
    // Hapus hidden action lama jika ada
    var oldHidden = form.querySelector('input[name="reviewAction"]');
    if (oldHidden) {
        oldHidden.remove();
    }
    
    // Tambahkan hidden input untuk action
    var hiddenAction = document.createElement('input');
    hiddenAction.type = 'hidden';
    hiddenAction.name = 'reviewAction';
    hiddenAction.value = 'revision';
    form.appendChild(hiddenAction);
    
    // Submit form
    form.submit();
}

// ============================================================
// FUNGSI UNTUK BATAL
// ============================================================
function submitBatal() {
    var form = document.getElementById('reviewForm');
    
    // Hapus hidden action lama jika ada
    var oldHidden = form.querySelector('input[name="reviewAction"]');
    if (oldHidden) {
        oldHidden.remove();
    }
    
    var hiddenAction = document.createElement('input');
    hiddenAction.type = 'hidden';
    hiddenAction.name = 'reviewAction';
    hiddenAction.value = 'batal';
    form.appendChild(hiddenAction);
    
    form.submit();
}
</script>

</body>
</html>