<?php
/**
 * Settings Tampilan Librarian OPAC
 * Path: plugins/multi_opac/pages/librarian_setting.php
 */

if (!defined('INDEX_AUTH')) {
    die("Direct access not allowed");
}

$db = \SLiMS\DB::getInstance();

// ============================================================
// 1. AUTO MIGRASI
// ============================================================
try {
    $check = $db->query("SHOW COLUMNS FROM user LIKE 'show_in_opac'");
    if ($check->rowCount() == 0) {
        $db->exec("ALTER TABLE user ADD COLUMN show_in_opac TINYINT(1) NOT NULL DEFAULT 0");
    }
} catch (Exception $e) {
    // Ignore
}

// ============================================================
// 2. HANDLER SIMPAN (FIXED FILTER-SAFE)
// ============================================================
$msg = '';
if (isset($_POST['save_librarians'])) {
    $showUsers = $_POST['show_user'] ?? [];
    $selectedLib = isset($_GET['library_id']) && $_GET['library_id'] !== '' ? (int)$_GET['library_id'] : null;
    
    try {
        // Reset status HANYA untuk perpustakaan yang sedang dipilih (atau semua jika tidak ada filter)
        if ($selectedLib) {
            $stmtReset = $db->prepare("UPDATE user SET show_in_opac = 0 WHERE library_id = ?");
            $stmtReset->execute([$selectedLib]);
        } else {
            $db->exec("UPDATE user SET show_in_opac = 0");
        }
        
        // Update user pilihan yang dicentang
        if (!empty($showUsers) && is_array($showUsers)) {
            $cleanIds = array_map('intval', $showUsers);
            $inClause = implode(',', $cleanIds);
            if (!empty($inClause)) {
                $db->exec("UPDATE user SET show_in_opac = 1 WHERE user_id IN ($inClause)");
            }
        }
        
        $msg = '<div class="alert alert-success">✅ ' . __('Pengaturan berhasil disimpan!') . '</div>';
    } catch (Exception $e) {
        $msg = '<div class="alert alert-danger">❌ ' . __('Gagal menyimpan: ') . htmlspecialchars($e->getMessage()) . '</div>';
    }
}

// ============================================================
// 3. FILTER & QUERY DATA (KEAMANAN: TANPA SUPERADMIN)
// ============================================================
$libFilter = '';
$searchFilter = '';

if (isset($_GET['library_id']) && $_GET['library_id'] !== '') {
    $libFilter = ' AND u.library_id = ' . (int)$_GET['library_id'];
}

if (isset($_GET['keywords']) && $_GET['keywords'] !== '') {
    $kw = $db->quote('%' . $_GET['keywords'] . '%');
    $searchFilter = " AND (u.realname LIKE $kw OR u.email LIKE $kw OR u.username LIKE $kw)";
}

// QUERY DIPERBAIKI:
// 1. Mengabaikan user_type = 1 (Superadmin), user_id = 1, dan username = 'admin' demi keamanan.
// 2. Mengakomodasi user_type yang NULL, bernilai 0, atau bernilai 2 (Librarian/Staff).
$sql = "SELECT 
            u.user_id, 
            u.username, 
            u.realname, 
            u.email, 
            u.user_type, 
            u.library_id,
            lib.library_name, 
            COALESCE(u.show_in_opac, 0) as show_in_opac
        FROM user u
        LEFT JOIN mst_library lib ON u.library_id = lib.library_id
        WHERE (u.user_type IS NULL OR u.user_type != 1)
          AND u.user_id != 1
          AND LOWER(u.username) != 'admin'
          $libFilter 
          $searchFilter
        ORDER BY lib.library_name ASC, u.realname ASC";

$query = $db->query($sql);
$librarians = $query->fetchAll(PDO::FETCH_ASSOC);

// Ambil daftar perpustakaan untuk dropdown filter
$libs = $db->query("SELECT library_id, library_name FROM mst_library ORDER BY library_name ASC")->fetchAll(PDO::FETCH_ASSOC);

// Ambil URL lengkap saat ini
$currentUrl = $_SERVER['REQUEST_URI'];
?>

<div class="menuBox">
    <div class="menuBoxInner systemIcon">
        <div class="per_title">
            <h2><?= __('Settings Tampilan Librarian OPAC') ?></h2>
        </div>
        <div class="sub_section">
            <div class="alert alert-info">
                📌 <strong><?= __('Centang') ?></strong> = <?= __('User/Pustakawan ditampilkan di halaman Librarian OPAC') ?> 
                (<a href="<?= SWB ?>index.php?p=librarian" target="_blank">index.php?p=librarian</a>)
            </div>

            <?= $msg ?>
            
            <!-- Form Filter AJAX (Menggunakan current URL) -->
            <form method="get" action="<?= htmlspecialchars($currentUrl) ?>" id="filterLibrarianForm" class="form-inline mb-3">
                <?php 
                // Copy semua query string bawaan SLiMS agar route tidak terlempar ke Home
                foreach ($_GET as $key => $val) {
                    if (!in_array($key, ['library_id', 'keywords', '_'])) {
                        echo '<input type="hidden" name="' . htmlspecialchars($key) . '" value="' . htmlspecialchars($val) . '">';
                    }
                }
                ?>
                
                <select name="library_id" class="form-control mr-2" onchange="$('#filterLibrarianForm').submit()">
                    <option value=""><?= __('Semua Perpustakaan') ?></option>
                    <?php foreach ($libs as $l): ?>
                        <option value="<?= $l['library_id'] ?>" <?= (isset($_GET['library_id']) && $_GET['library_id'] == $l['library_id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($l['library_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                
                <input type="text" name="keywords" class="form-control mr-2" placeholder="<?= __('Cari Nama / Email...') ?>" value="<?= htmlspecialchars($_GET['keywords'] ?? '') ?>">
                <button type="submit" class="btn btn-default"><?= __('Filter') ?></button>
            </form>
        </div>
    </div>
</div>

<!-- Form Simpan Data -->
<form method="post" action="<?= htmlspecialchars($currentUrl) ?>" id="saveLibrarianForm">
    <?php if (function_exists('renderCSRFToken')): ?>
        <?= renderCSRFToken() ?>
    <?php endif; ?>

    <input type="hidden" name="save_librarians" value="1">

    <table id="dataList" class="s-table table table-striped">
        <thead>
            <tr>
                <th width="80" class="text-center"><?= __('Tampil') ?></th>
                <th><?= __('Nama Pustakawan') ?></th>
                <th><?= __('Tipe User') ?></th>
                <th><?= __('Perpustakaan') ?></th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($librarians) > 0): ?>
                <?php foreach ($librarians as $row): ?>
                <tr>
                    <td class="text-center">
                        <input type="checkbox" name="show_user[]" value="<?= $row['user_id'] ?>" <?= $row['show_in_opac'] ? 'checked' : '' ?>>
                    </td>
                    <td>
                        <strong><?= htmlspecialchars($row['realname'] ?: $row['username']) ?></strong>
                        <br><small class="text-muted"><?= htmlspecialchars($row['email'] ?: '-') ?></small>
                    </td>
                    <td>
                        <span class="badge <?= $row['user_type'] == 1 ? 'badge-danger' : 'badge-info' ?>">
                            <?= $row['user_type'] == 1 ? 'Super Admin' : 'Librarian' ?>
                        </span>
                    </td>
                    <td><?= htmlspecialchars($row['library_name'] ?? '-') ?></td>
                </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="4" class="text-center text-muted"><?= __('Tidak ada data pustakawan/user ditemukan.') ?></td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
    
    <div class="p-3">
        <button type="submit" class="btn btn-primary">💾 <?= __('Simpan Pengaturan') ?></button>
    </div>
</form>

<script>
// Event handler universal untuk Form Filter & Form Simpan SLiMS Admin
$(document).off('submit', '#filterLibrarianForm, #saveLibrarianForm').on('submit', '#filterLibrarianForm, #saveLibrarianForm', function(e) {
    e.preventDefault();
    var form = this;
    var isPost = form.method.toLowerCase() === 'post';
    var rawAction = form.getAttribute('action') || window.location.href;
    var cleanAction = rawAction.replace(/&_=\d+/g, '');

    var options = {
        method: isPost ? 'POST' : 'GET',
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
    };

    if (isPost) {
        options.body = new FormData(form);
    } else {
        var params = new URLSearchParams(new FormData(form)).toString();
        cleanAction = cleanAction.split('?')[0] + '?' + params;
    }

    fetch(cleanAction, options)
    .then(response => response.text())
    .then(html => {
        var $target = $('#mainContent').length ? $('#mainContent') : $('#subContent');
        if ($target.length) {
            $target.html(html);
        } else if (document.querySelector('.mainContent')) {
            document.querySelector('.mainContent').innerHTML = html;
        } else {
            $(form).closest('.menuBox').parent().html(html);
        }
    })
    .catch(err => {
        alert('Gagal memproses data.');
    });
});
</script>