<?php
/**
 * Halaman Member - Bebas Pustaka
 * Version: 2.0.0 - Alur baru 3 status (pending, revision, done)
 */

use SLiMS\DB;

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

// ============================================================
// 1. PASTIKAN MEMBER LOGIN
// ============================================================
if (!isset($_SESSION['mid']) && !isset($_SESSION['m_id'])) {
    echo '<div class="alert alert-danger">' . __('Silakan login terlebih dahulu.') . '</div>';
    return;
}

// ============================================================
// 2. AMBIL LIBRARY DARI URL / SESSION
// ============================================================
$lib_slug = $_GET['lib'] ?? $_SESSION['multi_opac']['last_library_slug'] ?? $_SESSION['multi_opac']['library_slug'] ?? '';
if (!empty($lib_slug)) {
    $_SESSION['multi_opac']['last_library_slug'] = $lib_slug;
}

// ============================================================
// 3. LOAD HELPERS
// ============================================================
require_once dirname(__DIR__) . '/src/helper.php';

$member_id = $_SESSION['mid'] ?? $_SESSION['m_id'];
$db = DB::getInstance();

// ============================================================
// 4. AMBIL DATA
// ============================================================
$allowedLibs = getAllowedLibraries($member_id);
$histories = getPengajuanMember($member_id);
$myLib = bpGetLibraryId();
$keperluanList = getKeperluanList($myLib);

// ============================================================
// 5. CEK PINJAMAN AKTIF (untuk tampilan awal)
// ============================================================
$pinjamanAktif = getPinjamanAktifMember($member_id, $myLib);
$denda = getDendaMember($member_id, $myLib);
$bisaMengajukan = (empty($pinjamanAktif) && $denda['total'] == 0);

// ============================================================
// 6. HANDLER SUBMIT PENGAJUAN
// ============================================================
if (isset($_POST['submitPengajuan'])) {
    $keperluan = trim($_POST['keperluan']);
    $tujuan = (int)$_POST['tujuan'];
    $keterangan = trim($_POST['keterangan'] ?? '');
    
    if (empty($keperluan) || empty($tujuan)) {
        echo '<div class="alert alert-danger">' . __('Semua field wajib diisi!') . '</div>';
    } else {
        if (!in_array($tujuan, $allowedLibs)) {
            echo '<div class="alert alert-danger">' . __('Tujuan pengajuan tidak diizinkan.') . '</div>';
        } else {
            // Cek duplikat pengajuan aktif (pending atau revision)
            if (cekDuplikatPengajuan($member_id, $tujuan)) {
                echo '<div class="alert alert-warning">' . __('Anda masih memiliki pengajuan aktif untuk perpustakaan ini. Tunggu review admin atau selesaikan revisi.') . '</div>';
            } else {
                $result = submitPengajuan($member_id, $keperluan, $tujuan, $keterangan);
                if ($result['ok']) {
                    echo '<div class="alert alert-success">' . __('Pengajuan berhasil dikirim! Tunggu review dari pustakawan.') . '</div>';
                    $histories = getPengajuanMember($member_id);
                } else {
                    echo '<div class="alert alert-danger">' . $result['message'] . '</div>';
                }
            }
        }
    }
}

// ============================================================
// 7. HANDLER AJUKAN KEMBALI (UNTUK REVISION)
// ============================================================
if (isset($_GET['ajukan_kembali']) && !empty($_GET['ajukan_kembali'])) {
    $id = (int)$_GET['ajukan_kembali'];
    $lib_slug = $_GET['lib'] ?? 'pusat';
    
    // Cek kepemilikan dan status
    $st = $db->prepare("SELECT * FROM bebas_pustaka_history WHERE id = ? AND member_id = ? AND status = 'revision'");
    $st->execute([$id, $member_id]);
    $history = $st->fetch(PDO::FETCH_ASSOC);
    
    if ($history) {
        // Update status menjadi pending
        $st = $db->prepare("
            UPDATE bebas_pustaka_history 
            SET status = 'pending', 
                rejected_reason = NULL,
                updated_at = NOW() 
            WHERE id = ?
        ");
        $result = $st->execute([$id]);
        
        if ($result) {
            echo '<div class="alert alert-success">' . __('Pengajuan dikirim ulang untuk review.') . '</div>';
            echo '<script>setTimeout(function(){ window.location.href = "?p=bebas_pustaka&lib=' . urlencode($lib_slug) . '"; }, 1500);</script>';
            $histories = getPengajuanMember($member_id);
        } else {
            echo '<div class="alert alert-danger">' . __('Gagal memperbarui pengajuan. Silakan coba lagi.') . '</div>';
        }
    } else {
        echo '<div class="alert alert-danger">' . __('Data tidak ditemukan atau tidak dapat diajukan kembali.') . '</div>';
    }
}

// ============================================================
// 8. TAMPILAN
// ============================================================
?>
<div class="bebas-container">
    <!-- Informasi Perpustakaan -->
    <?php if (!empty($lib_slug)): ?>
    <div class="alert alert-info">
        <i class="fa fa-info-circle"></i> 
        <?= __('Perpustakaan') ?>: <strong>
        <?php 
            $libData = getLibraryBySlug($lib_slug);
            echo htmlspecialchars($libData['library_name'] ?? $lib_slug);
        ?>
        </strong>
        <br>
        <small><?= __('Anda dapat mengajukan bebas pustaka ke perpustakaan yang terdaftar di member type Anda.') ?></small>
    </div>
    <?php endif; ?>

    <div class="row">
        <!-- SISI KIRI: FORM PENGAJUAN -->
        <div class="col-md-6">
            <div class="bebas-card">
                <div class="card-header">
                    <h4><i class="fa fa-file-text me-2"></i><?= __('Ajukan Bebas Pustaka') ?></h4>
                </div>
                <div class="card-body">
                    <?php if (!empty($pinjamanAktif) || $denda['total'] > 0): ?>
                        <!-- KONDISI 1: Ada pinjaman aktif atau denda -->
                        <div class="alert alert-danger">
                            <strong><?= __('❌ Belum Bisa Mengajukan') ?></strong>
                            <p><?= __('Anda masih memiliki tanggungan:') ?></p>
                            <?php if (!empty($pinjamanAktif)): ?>
                                <p><strong>📖 Pinjaman Aktif:</strong></p>
                                <ul>
                                    <?php foreach ($pinjamanAktif as $p): ?>
                                    <li><?= htmlspecialchars($p['title']) ?> (<?= htmlspecialchars($p['item_code']) ?>) - Jatuh Tempo: <?= htmlspecialchars($p['due_date']) ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php endif; ?>
                            <?php if ($denda['total'] > 0): ?>
                                <p><strong>💰 Sisa Denda: Rp <?= number_format($denda['total'], 0, ',', '.') ?></strong></p>
                            <?php endif; ?>
                            <p class="mt-2"><em><?= __('Silakan kembalikan semua pinjaman dan lunasi denda terlebih dahulu.') ?></em></p>
                            <a href="?p=member&lib=<?= urlencode($lib_slug) ?>&sec=loan" class="btn btn-outline-primary btn-sm">
                                <i class="fa fa-book"></i> Lihat Peminjaman Saya
                            </a>
                            <a href="?p=member&lib=<?= urlencode($lib_slug) ?>&sec=my_account" class="btn btn-outline-success btn-sm">
                                <i class="fa fa-money"></i> Lihat Denda
                            </a>
                        </div>
                        <!-- Tombol Ajukan disable -->
                        <button class="btn btn-secondary" disabled>
                            <i class="fa fa-paper-plane"></i> <?= __('Ajukan (Tidak Aktif)') ?>
                        </button>
                    <?php else: ?>
                        <!-- KONDISI 2: Tidak ada pinjaman aktif -->
                        <div class="alert alert-success">
                            <strong><?= __('✅ Tidak Ada Tanggungan') ?></strong>
                            <p><?= __('Anda tidak memiliki pinjaman aktif dan denda. Silakan ajukan bebas pustaka.') ?></p>
                        </div>
                        
                        <form method="post" action="">
                            <div class="form-group mb-3">
                                <label><?= __('Keperluan') ?> <span class="text-danger">*</span></label>
                                <select name="keperluan" class="form-control" required>
                                    <option value="">-- Pilih Keperluan --</option>
                                    <?php foreach ($keperluanList as $k): ?>
                                    <option value="<?= htmlspecialchars($k['keperluan']) ?>">
                                        <?= htmlspecialchars($k['keperluan']) ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label><?= __('Tujuan Pengajuan') ?> <span class="text-danger">*</span></label>
                                <select name="tujuan" class="form-control" required>
                                    <option value="">-- Pilih Tujuan --</option>
                                    <?php
                                    $libNames = [];
                                    foreach ($allowedLibs as $libId) {
                                        $libData = getLibraryData($libId);
                                        if ($libData) {
                                            $libNames[$libId] = $libData['library_name'];
                                        }
                                    }
                                    asort($libNames);
                                    foreach ($libNames as $libId => $libName):
                                    ?>
                                    <option value="<?= $libId ?>">
                                        <?= htmlspecialchars($libName) ?>
                                        <?php if ($libId == $myLib): ?> (Asal)<?php endif; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <small class="text-muted">Anda dapat mengajukan ke perpustakaan yang terdaftar di member type Anda.</small>
                            </div>
                            
                            <div class="form-group mb-3">
                                <label><?= __('Keterangan (Opsional)') ?></label>
                                <input type="text" name="keterangan" class="form-control" placeholder="Catatan tambahan...">
                            </div>
                            
                            <button type="submit" name="submitPengajuan" class="btn btn-primary btn-primary-custom">
                                <i class="fa fa-paper-plane"></i> <?= __('Ajukan') ?>
                            </button>
                            <a href="?p=member&lib=<?= urlencode($lib_slug) ?>" class="btn btn-secondary">
                                <i class="fa fa-times"></i> <?= __('Batal') ?>
                            </a>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- SISI KANAN: RIWAYAT PENGAJUAN -->
        <div class="col-md-6">
            <div class="bebas-card">
                <div class="card-header">
                    <h4><i class="fa fa-history me-2"></i><?= __('Riwayat Pengajuan') ?></h4>
                </div>
                <div class="card-body">
                    <?php if (empty($histories)): ?>
                    <div class="alert alert-info">
                        <?= __('Belum ada riwayat pengajuan.') ?>
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered">
                            <thead>
                                <tr>
                                    <th><?= __('No Surat') ?></th>
                                    <th><?= __('Keperluan') ?></th>
                                    <th><?= __('Tujuan') ?></th>
                                    <th><?= __('Status') ?></th>
                                    <th><?= __('Aksi') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($histories as $h): ?>
                                <tr>
                                    <td><?= htmlspecialchars($h['surat_no'] ?? '-') ?></td>
                                    <td><?= htmlspecialchars($h['keperluan']) ?></td>
                                    <td><?= htmlspecialchars($h['library_name'] ?? '-') ?></td>
                                    <td>
                                        <?php
                                        $badges = [
                                            'pending' => '<span class="badge badge-status badge-pending">⏳ Pending</span>',
                                            'revision' => '<span class="badge badge-status" style="background:#ff9800;color:#fff;">🔄 Revisi</span>',
                                            'done' => '<span class="badge badge-status badge-printed">✅ Selesai</span>'
                                        ];
                                        echo $badges[$h['status']] ?? $h['status'];
                                        ?>
                                        <?php if (!empty($h['rejected_reason']) && $h['status'] == 'revision'): ?>
                                        <br><small class="text-danger"><strong>Alasan:</strong> <?= htmlspecialchars($h['rejected_reason']) ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($h['status'] == 'done' && !empty($h['surat_no']) && !empty($h['file_path'])): ?>
                                            <a href="/download_bebas_pustaka.php?id=<?= $h['id'] ?>" class="btn btn-sm btn-success">
                                                <i class="fa fa-download"></i> Download PDF
                                            </a>
                                        <?php elseif ($h['status'] == 'revision'): ?>
                                            <a href="?p=bebas_pustaka&ajukan_kembali=<?= $h['id'] ?>&lib=<?= urlencode($lib_slug) ?>" 
                                               class="btn btn-sm btn-warning" 
                                               onclick="return confirm('Kirim ulang pengajuan setelah revisi?')">
                                                <i class="fa fa-refresh"></i> Ajukan Kembali
                                            </a>
                                        <?php elseif ($h['status'] == 'pending'): ?>
                                            <span class="text-muted">Menunggu review</span>
                                        <?php else: ?>
                                            <span class="text-muted">-</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.bebas-container { max-width: 1200px; margin: 0 auto; padding: 20px; }
.bebas-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.08);
    padding: 24px;
    margin-bottom: 20px;
}
.bebas-card .card-header {
    background: #f8f9fa;
    padding: 16px 24px;
    border-bottom: 2px solid #e9ecef;
    border-radius: 8px 8px 0 0;
    margin: -24px -24px 20px -24px;
}
.badge-status { font-size: 12px; padding: 4px 10px; border-radius: 20px; }
.badge-pending { background: #ffc107; color: #000; }
.badge-printed { background: #28a745; color: #fff; }
.btn-primary-custom {
    background-color: <?= $primaryColor ?? '#0d6efd' ?>;
    border-color: <?= $primaryColor ?? '#0d6efd' ?>;
}
.btn-primary-custom:hover {
    background-color: <?= $primaryColor ?? '#0d6efd' ?>dd;
}
</style>