<?php
/**
 * Plugin Name: Multi OPAC Path
 * Plugin URI: https://github.com/yourname/slims-multi-opac
 * Description: Plugin untuk OPAC Multi-Perpustakaan dengan tema dinamis per perpustakaan
 * Version: 1.3.0 (Slug-Agnostic / Decoupled Portal Architecture)
 * Author: Your Name
 */

use SLiMS\Plugins;
use SLiMS\DB;

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

// LOAD HELPERS
require_once __DIR__ . '/src/helpers.php';

// ============================================================
// FUNGSI AUTO CREATE TABLES
// ============================================================
function createMultiOpacTables()
{
    $db = DB::getInstance();
    
    $check = $db->query("SHOW TABLES LIKE 'multi_opac_config'");
    if ($check->rowCount() > 0) {
        return;
    }
    
    // Tambah kolom di mst_library
    try {
        $checkSlug = $db->query("SHOW COLUMNS FROM mst_library LIKE 'url_slug'");
        if ($checkSlug->rowCount() == 0) {
            $db->exec("ALTER TABLE mst_library ADD COLUMN url_slug VARCHAR(50) UNIQUE");
            $db->exec("UPDATE mst_library SET url_slug = LOWER(library_code) WHERE url_slug IS NULL");
        }
        
        $checkTheme = $db->query("SHOW COLUMNS FROM mst_library LIKE 'opac_theme'");
        if ($checkTheme->rowCount() == 0) {
            $db->exec("ALTER TABLE mst_library ADD COLUMN opac_theme VARCHAR(50) DEFAULT 'default'");
        }
    } catch (Exception $e) {
        error_log("❌ [Multi OPAC] Error: " . $e->getMessage());
    }
    
    // Tambah kolom di content
    try {
        $checkContent = $db->query("SHOW COLUMNS FROM content LIKE 'library_id'");
        if ($checkContent->rowCount() == 0) {
            $db->exec("ALTER TABLE content ADD COLUMN library_id INT(11) DEFAULT NULL");
            $db->exec("ALTER TABLE content ADD INDEX (library_id)");
        }
    } catch (Exception $e) {
        error_log("❌ [Multi OPAC] Error: " . $e->getMessage());
    }
    
    // Tambah kolom show_in_opac di user
    try {
        $checkShow = $db->query("SHOW COLUMNS FROM user LIKE 'show_in_opac'");
        if ($checkShow->rowCount() == 0) {
            $db->exec("ALTER TABLE user ADD COLUMN show_in_opac TINYINT(1) DEFAULT 0");
            error_log("✅ [Multi OPAC] Added show_in_opac column to user");
        }
    } catch (Exception $e) {
        error_log("❌ [Multi OPAC] Error adding show_in_opac to user: " . $e->getMessage());
    }
    
    // Buat tabel multi_opac_theme_settings
    $db->exec("
        CREATE TABLE IF NOT EXISTS `multi_opac_theme_settings` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `library_id` int(11) NOT NULL,
            `primary_color` varchar(7) DEFAULT '#0d6efd',
            `secondary_color` varchar(7) DEFAULT '#212529',
            `header_text` varchar(255) DEFAULT NULL,
            `footer_text` varchar(255) DEFAULT NULL,
            `logo` varchar(255) DEFAULT NULL,
            `created_at` datetime DEFAULT NULL,
            `updated_at` datetime DEFAULT NULL,
            PRIMARY KEY (`id`),
            UNIQUE KEY `library_id` (`library_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
    
    // Buat tabel multi_opac_config
    $db->exec("
        CREATE TABLE IF NOT EXISTS `multi_opac_config` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `library_id` int(11) DEFAULT NULL,
            `auto_create_theme` tinyint(1) DEFAULT 1,
            `default_theme` varchar(50) DEFAULT 'default',
            `enable_library_switcher` tinyint(1) DEFAULT 1,
            `base_path` varchar(100) DEFAULT '/opac/',
            `show_library_badge` tinyint(1) DEFAULT 1,
            `created_at` datetime DEFAULT NULL,
            `updated_at` datetime DEFAULT NULL,
            PRIMARY KEY (`id`),
            KEY `library_id` (`library_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
    
    // Insert config default
    $checkConfig = $db->query("SELECT COUNT(*) FROM multi_opac_config WHERE library_id IS NULL");
    if ($checkConfig->fetchColumn() == 0) {
        $db->exec("
            INSERT INTO multi_opac_config 
            (library_id, auto_create_theme, default_theme, enable_library_switcher, base_path, show_library_badge, created_at) 
            VALUES (NULL, 1, 'default', 1, '/opac/', 1, NOW())
        ");
    }
}

// EKSEKUSI SCHEMA CHECK
createMultiOpacTables();

// ============================================================
// DAFTARKAN HALAMAN OPAC
// ============================================================
$plugins = Plugins::getInstance();
$pluginPages = ['multi-opac', 'detail', 'libinfo', 'help', 'librarian', 'member-login', 'member'];

foreach ($pluginPages as $page) {
    $plugins->registerMenu('opac', $page, __DIR__ . '/pages/opac_handler.php');
}

// ============================================================
// MENU ADMIN
// ============================================================
Plugins::menu('system', 'Multi OPAC Settings', __DIR__ . '/pages/settings.php');
Plugins::menu('system', 'Librarian Management', __DIR__ . '/pages/librarian_setting.php');
Plugins::menu('system', 'Theme Editor', __DIR__ . '/pages/theme_editor.php');

// ============================================================
// HOOK: CONTENT_BEFORE_LOAD (SESSION & ROUTING MANAGEMENT)
// ============================================================
\SLiMS\Plugins::getInstance()->register('content_before_load', function() {
    
    // 1. CEK AJAX REQUEST
    $isAjax = (
        isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
        strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
    ) || isset($_GET['ajax']) || isset($_POST['ajax']);
    
    if ($isAjax) {
        return;
    }
    
    // 2. CEK ADMIN AREA
    $isAdmin = (
        isset($_GET['mod']) || 
        isset($_GET['module']) || 
        defined('IN_ADMIN') ||
        strpos($_SERVER['REQUEST_URI'], '/admin/') !== false
    );
    
    if ($isAdmin) {
        return;
    }
    
    // 3. START SESSION
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    // 4. INISIALISASI SESSION ARRAY (SLUG-AGNOSTIC DEFAULT = NULL)
    if (!isset($_SESSION['multi_opac'])) {
        $_SESSION['multi_opac'] = [
            'library_id'     => null,
            'library_slug'   => null,
            'search_library' => null,
            'filter'         => []
        ];
    }
    
    // 5. REDIRECT HOMEPAGE SLiMS KE MULTI-OPAC
    $isHomepage = (
        empty($_GET['p']) && 
        empty($_GET['q']) && 
        empty($_GET['page']) && 
        empty($_GET['mod']) && 
        empty($_GET['module']) && 
        empty($_GET['id']) &&
        empty($_GET['_']) &&
        basename($_SERVER['PHP_SELF']) == 'index.php'
    );
    
    if ($isHomepage) {
        header('Location: index.php?p=multi-opac');
        exit;
    }
    
    // 6. SINKRONISASI SESSION BERDASARKAN PARAMETER 'lib' DI URL
    if (isset($_GET['lib']) && !empty($_GET['lib'])) {
        $lib_slug = trim($_GET['lib']);
        
        $db = DB::getInstance();
        $stmt = $db->prepare("SELECT library_id, url_slug FROM mst_library WHERE url_slug = ? OR library_id = ?");
        $stmt->execute([$lib_slug, $lib_slug]);
        $library = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($library) {
            $_SESSION['multi_opac']['library_id']   = $library['library_id'];
            $_SESSION['multi_opac']['library_slug'] = $library['url_slug'];
        } else {
            $_SESSION['multi_opac']['library_id']   = null;
            $_SESSION['multi_opac']['library_slug'] = null;
        }
    } else {
        // Jika diakses tanpa parameter 'lib' (Global Portal context)
        // Kosongkan session unit agar tidak mengunci landing page ke unit tertentu
        if (isset($_GET['p']) && $_GET['p'] === 'multi-opac') {
            $_SESSION['multi_opac']['library_id']   = null;
            $_SESSION['multi_opac']['library_slug'] = null;
            $_SESSION['multi_opac']['search_library'] = null;
        }
    }
    
    // 7. ROUTING INFORMASI & BANTUAN (libinfo & help)
    $navbarPages = ['libinfo', 'help'];
    if (isset($_GET['p']) && in_array($_GET['p'], $navbarPages)) {
        $page = $_GET['p'];
        $lib_slug = $_GET['lib'] ?? null;
        
        $library = null;
        if ($lib_slug) {
            $db = DB::getInstance();
            $stmt = $db->prepare("SELECT * FROM mst_library WHERE url_slug = ? OR library_id = ?");
            $stmt->execute([$lib_slug, $lib_slug]);
            $library = $stmt->fetch(PDO::FETCH_ASSOC);
        }
        
        $contentTypeMap = [
            'libinfo' => 'information',
            'help'    => 'help'
        ];
        $content_type = $contentTypeMap[$page] ?? $page;
        
        if ($library) {
            $theme    = getTheme($library['library_id']);
            $contents = getContentByLibraryAndType($library['library_id'], $content_type, 10);
            
            $data = [
                'title'        => ($page == 'libinfo' ? 'Informasi' : 'Bantuan') . ' - ' . $library['library_name'],
                'page_title'   => ($page == 'libinfo' ? 'Informasi Perpustakaan' : 'Bantuan OPAC'),
                'content_type' => $content_type,
                'contents'     => $contents,
                'theme'        => $theme,
                'library'      => $library
            ];
        } else {
            // Global Content Context (Tanpa Unit Spesifik / Portal Utama)
            $contents = getContentByLibraryAndType(null, $content_type, 10);
            $data = [
                'title'        => ($page == 'libinfo' ? 'Informasi Portal' : 'Bantuan Portal'),
                'page_title'   => ($page == 'libinfo' ? 'Informasi Multi-OPAC' : 'Bantuan OPAC'),
                'content_type' => $content_type,
                'contents'     => $contents,
                'theme'        => null,
                'library'      => null
            ];
        }
        
        require_once __DIR__ . '/template/page_content.tpl';
        exit;
    }
});

// ============================================================
// HOOK: DROPDOWN PERPUSTAKAAN DI HEADER SLiMS (GLOBAL HEADER)
// ============================================================
\SLiMS\Plugins::getInstance()->register('template_after_header', function() {
    if (defined('IN_ADMIN') || isset($_GET['mod'])) {
        return;
    }
    
    $libraries = getAllLibraries();
    if (empty($libraries)) {
        return;
    }
    
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    
    $currentLibSlug = $_GET['lib'] ?? $_SESSION['multi_opac']['library_slug'] ?? '';
    $currentLibName = '';
    
    if ($currentLibSlug) {
        $lib = getLibraryBySlug($currentLibSlug);
        if ($lib) {
            $currentLibName = $lib['library_name'];
        }
    }
    
    $config = getMultiOpacConfig();
    $enableSwitcher = $config['enable_library_switcher'] ?? 1;
    
    if (!$enableSwitcher) {
        return;
    }
    ?>
    
    <style>
        .multi-opac-switcher {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 8px 0;
            border-bottom: 2px solid #0d6efd;
            margin-bottom: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .multi-opac-switcher .switcher-container {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            flex-wrap: wrap;
        }
        .multi-opac-switcher .switcher-label {
            font-weight: 600;
            color: #212529;
            font-size: 0.9rem;
            margin: 0;
        }
        .multi-opac-switcher .switcher-label i {
            color: #0d6efd;
        }
        .multi-opac-switcher .switcher-select {
            min-width: 200px;
            border-radius: 30px;
            border: 2px solid #0d6efd;
            padding: 6px 16px;
            font-size: 0.9rem;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .multi-opac-switcher .switcher-select:hover,
        .multi-opac-switcher .switcher-select:focus {
            border-color: #0a58ca;
            box-shadow: 0 0 0 3px rgba(13, 110, 253, 0.25);
            outline: none;
        }
        .multi-opac-switcher .switcher-badge {
            background: #0d6efd;
            color: white;
            padding: 2px 14px;
            border-radius: 20px;
            font-size: 0.78rem;
            font-weight: 600;
        }
        .multi-opac-switcher .switcher-link {
            color: #0d6efd;
            text-decoration: none;
            font-weight: 500;
            font-size: 0.85rem;
            transition: color 0.2s;
        }
        .multi-opac-switcher .switcher-link:hover {
            color: #0a58ca;
            text-decoration: underline;
        }
        
        body.plugin-page .multi-opac-switcher {
            display: none !important;
        }
        
        @media (max-width: 768px) {
            .multi-opac-switcher .switcher-container {
                flex-direction: column;
                gap: 6px;
                padding: 4px 0;
            }
            .multi-opac-switcher .switcher-select {
                min-width: 100%;
                max-width: 280px;
            }
            .multi-opac-switcher .switcher-label {
                font-size: 0.8rem;
            }
        }
    </style>
    
    <div class="multi-opac-switcher">
        <div class="container">
            <div class="switcher-container">
                <span class="switcher-label">
                    <i class="fa-solid fa-building-columns"></i>
                    Pilih Perpustakaan:
                </span>
                
                <select class="switcher-select" id="librarySwitcher" 
                        onchange="if(this.value){ window.location='index.php?p=multi-opac&lib='+this.value; } else { window.location='index.php?p=multi-opac'; }">
                    <option value="">-- Semua Perpustakaan (Portal Induk) --</option>
                    <?php foreach ($libraries as $lib): ?>
                        <?php $slug = $lib['url_slug'] ?? $lib['library_id']; ?>
                        <option value="<?= htmlspecialchars($slug) ?>" 
                            <?= ($slug === $currentLibSlug) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($lib['library_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                
                <?php if ($currentLibSlug && $currentLibName): ?>
                    <span class="switcher-badge">
                        <i class="fa-solid fa-check me-1"></i>
                        <?= htmlspecialchars($currentLibName) ?>
                    </span>
                <?php endif; ?>
                
                <a href="index.php?p=multi-opac" class="switcher-link">
                    <i class="fa-solid fa-house me-1"></i> Portal Utama
                </a>
            </div>
        </div>
    </div>
    
    <?php
});

// ============================================================
// HOOK: FILTER SEARCH QUERY BUKU PERPUSTAKAAN
// ============================================================
try {
    \SLiMS\Plugins::getInstance()->register('opac_search_query_before', function($query) {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        
        // Filter hanya diterapkan jika ada 'lib' di GET atau session unit aktif
        $library_id = $_GET['lib'] ?? $_SESSION['multi_opac']['library_id'] ?? null;
        
        if ($library_id) {
            // Ubah slug ke ID jika perlu
            if (!is_numeric($library_id)) {
                $lib = getLibraryBySlug($library_id);
                $library_id = $lib['library_id'] ?? null;
            }
            
            if ($library_id) {
                if (strpos($query, 'WHERE') !== false) {
                    $query .= " AND b.library_id = " . intval($library_id);
                } else {
                    $query .= " WHERE b.library_id = " . intval($library_id);
                }
            }
        }
        
        return $query;
    });
} catch (Exception $e) {
    error_log("⚠️ [Multi OPAC] Hook opac_search_query_before error: " . $e->getMessage());
}

error_log("✅ [Multi OPAC] Controller Plugin Loaded (Tahap 1 Finished)");