<?php
/**
 * Halaman Edit Tema & Konten OPAC Unit (SLiMS Native Look & Feel)
 * Path: plugins/multi_opac_path/pages/theme_editor.php
 */

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

// Load session admin
require SB . 'admin/default/session.inc.php';
require SB . 'admin/default/session_check.inc.php';
require_once __DIR__ . '/../src/helpers.php';

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

// ============================================================
// AMBIL PARAMETER
// ============================================================
$library_id = isset($_GET['library_id']) ? intval($_GET['library_id']) : 0;
$library_id = $library_id ?: ($_SESSION['library_id'] ?? 0);
$library_id = $library_id ?: 1;

$mod = isset($_GET['mod']) ? trim($_GET['mod']) : 'system';

// ============================================================
// CEK AKSES
// ============================================================
$isSuperAdmin = (($_SESSION['uid'] ?? 0) == 1);
$isOwnLibrary = ($_SESSION['library_id'] ?? 0) == $library_id;

if (!$isSuperAdmin && !$isOwnLibrary) {
    echo '<div class="errorBox">' . __('Akses Ditolak.') . '</div>';
    echo '<script>window.location.href = "' . SWB . 'admin/";</script>';
    exit;
}

// ============================================================
// AMBIL DATA TEMA EXISTING
// ============================================================
$existingTheme = getTheme($library_id);

// ============================================================
// DEFINISI MENU KONTEN NAVBAR KHUSUS UNIT
// ============================================================
$customContentMenus = [
    'libinfo'   => 'Informasi Perpustakaan',
    'help'      => 'Bantuan & Layanan',
];

// ============================================================
// HANDLER SIMPAN (POST)
// ============================================================
$msg = '';
$uploadError = false;

if (isset($_POST['save_theme'])) {
    $theme_data = [
        'primary_color'   => $_POST['primary_color'] ?? '#007bff',
        'secondary_color' => $_POST['secondary_color'] ?? '#6c757d',
        'header_text'     => $_POST['header_text'] ?? '',
        'footer_text'     => $_POST['footer_text'] ?? '',
        'logo'            => $existingTheme['logo'] ?? '',
    ];
    
    // ------------------------------------------------------------
    // 1. UPLOAD LOGO
    // ------------------------------------------------------------
    if (isset($_FILES['logo_file']) && $_FILES['logo_file']['error'] == 0) {
        $uploadDir = __DIR__ . '/../assets/logos/' . $library_id . '/';
        
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        if (is_writable($uploadDir)) {
            $ext = pathinfo($_FILES['logo_file']['name'], PATHINFO_EXTENSION);
            $allowedExt = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'];
            
            if (in_array(strtolower($ext), $allowedExt)) {
                $oldFiles = glob($uploadDir . 'logo.*');
                if ($oldFiles) {
                    foreach ($oldFiles as $oldFile) {
                        @unlink($oldFile);
                    }
                }
                
                $targetFile = $uploadDir . 'logo.' . $ext;
                
                if (move_uploaded_file($_FILES['logo_file']['tmp_name'], $targetFile)) {
                    $theme_data['logo'] = SWB . 'plugins/multi_opac_path/assets/logos/' . $library_id . '/logo.' . $ext;
                } else {
                    $uploadError = true;
                    $msg = '<div class="errorBox" style="margin-bottom: 15px;">❌ Gagal memindahkan file logo. Periksa izin folder.</div>';
                }
            } else {
                $uploadError = true;
                $msg = '<div class="errorBox" style="margin-bottom: 15px;">❌ Format file logo tidak didukung.</div>';
            }
        } else {
            $uploadError = true;
            $msg = '<div class="errorBox" style="margin-bottom: 15px;">❌ Folder tidak dapat ditulis: ' . htmlspecialchars($uploadDir) . '</div>';
        }
    }
    
    // ------------------------------------------------------------
    // 2. SIMPAN TEMA KE DATABASE
    // ------------------------------------------------------------
    if (!$uploadError) {
        try {
            saveTheme($library_id, $theme_data);
            
            // ------------------------------------------------------------
            // 3. SIMPAN KONTEN NAVBAR KE TABEL `content`
            // ------------------------------------------------------------
            foreach ($customContentMenus as $menuKey => $defaultTitle) {
                $contentTitle = trim($_POST['content_title_' . $menuKey] ?? '');
                $contentBody  = trim($_POST['content_body_' . $menuKey] ?? '');
                
                // Content Path Unik: e.g. "2-libinfo" atau "libinfo" jika Pusat (1)
                $contentPath = ($library_id == 1) ? $menuKey : $library_id . '-' . $menuKey;
                
                if (!empty($contentTitle) || !empty($contentBody)) {
                    // Cek apakah konten sudah ada
                    $checkStmt = $db->prepare("SELECT content_id FROM content WHERE content_path = ? AND library_id = ?");
                    $checkStmt->execute([$contentPath, $library_id]);
                    $existingContent = $checkStmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($existingContent) {
                        // UPDATE
                        $updateStmt = $db->prepare("UPDATE content SET content_title = ?, content_desc = ?, last_update = NOW() WHERE content_id = ?");
                        $updateStmt->execute([$contentTitle, $contentBody, $existingContent['content_id']]);
                    } else {
                        // INSERT
                        $insertStmt = $db->prepare("INSERT INTO content (content_title, content_path, content_desc, is_draft, library_id, input_date, last_update) VALUES (?, ?, ?, 0, ?, NOW(), NOW())");
                        $insertStmt->execute([$contentTitle, $contentPath, $contentBody, $library_id]);
                    }
                }
            }
            
            $msg = '<div class="infoBox" style="background-color: #d4edda; color: #155724; border-color: #c3e6cb; margin-bottom: 15px;">✅ Pengaturan Tema dan Konten Navbar berhasil disimpan!</div>';
            $existingTheme = getTheme($library_id);
            
        } catch (Exception $e) {
            $msg = '<div class="errorBox" style="margin-bottom: 15px;">❌ Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    }
}

// ============================================================
// AMBIL DATA LIBRARY
// ============================================================
$stmt = $db->prepare("SELECT * FROM mst_library WHERE library_id = ?");
$stmt->execute([$library_id]);
$library = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$library) {
    echo '<div class="errorBox">' . __('Perpustakaan tidak ditemukan.') . '</div>';
    echo '<script>window.location.href = "' . SWB . 'admin/";</script>';
    exit;
}

$themeFromDb = getTheme($library_id);
$theme = [
    'primary_color'   => $themeFromDb['primary_color'] ?? '#007bff',
    'secondary_color' => $themeFromDb['secondary_color'] ?? '#6c757d',
    'header_text'     => $themeFromDb['header_text'] ?? $library['library_name'],
    'footer_text'     => $themeFromDb['footer_text'] ?? '© ' . date('Y') . ' ' . $library['library_name'],
    'logo'            => $themeFromDb['logo'] ?? ''
];

// ============================================================
// AMBIL KONTEN NAVBAR EXISTING UNTUK UNIT INI
// ============================================================
$existingContents = [];
foreach ($customContentMenus as $menuKey => $defaultTitle) {
    $contentPath = ($library_id == 1) ? $menuKey : $library_id . '-' . $menuKey;
    
    $cStmt = $db->prepare("SELECT content_title, content_desc FROM content WHERE content_path = ? AND library_id = ? LIMIT 1");
    $cStmt->execute([$contentPath, $library_id]);
    $res = $cStmt->fetch(PDO::FETCH_ASSOC);
    
    $existingContents[$menuKey] = [
        'title' => $res['content_title'] ?? $defaultTitle,
        'body'  => $res['content_desc'] ?? ''
    ];
}

$allLibraries = $isSuperAdmin ? getAllLibraries() : [];
$queryString = $_SERVER['QUERY_STRING'] ?? '';
$queryStringClean = preg_replace('/&?library_id=\d+/', '', $queryString);
$baseAjaxUrl = 'plugin_container.php?' . $queryStringClean;
?>

<div class="menuBox">
    <div class="menuBoxInner systemIcon">
        <div class="per_title">
            <h2>🎨 <?= __('Edit Tema & Konten Navbar') ?>: <?= htmlspecialchars($library['library_name']) ?></h2>
        </div>
        
        <div class="sub_section">
            
            <?= $msg ?>
            
            <?php if ($isSuperAdmin && count($allLibraries) > 1): ?>
                <div class="form-group mb-3" style="max-width: 420px; display: flex; align-items: center; gap: 10px;">
                    <label style="font-weight: bold; white-space: nowrap; margin-bottom: 0;"><?= __('Pilih Perpustakaan') ?>:</label>
                    <select id="libSelector" onchange="changeLib(this.value)" class="form-control spec-select">
                        <?php foreach ($allLibraries as $lib): ?>
                            <option value="<?= $lib['library_id'] ?>" <?= ($lib['library_id'] == $library_id) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($lib['library_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <script>
                function changeLib(libId) {
                    const url = '<?= $baseAjaxUrl ?>' + '&library_id=' + libId;
                    const $jq = (typeof parent.jQuery !== 'undefined') ? parent.jQuery : jQuery;
                    $jq('#mainContent').simbioAJAX(url);
                }
                </script>
            <?php endif; ?>
            
            <div class="infoBox" style="margin-top: 10px; margin-bottom: 20px;">
                <em><?= __('Mengubah tema dan isi konten halaman khusus untuk unit') ?>: <strong><?= htmlspecialchars($library['library_name']) ?></strong></em>
            </div>

            <form method="post" action="<?= htmlspecialchars($_SERVER['REQUEST_URI']) ?>" id="themeForm" enctype="multipart/form-data">
                <?php if (function_exists('renderCSRFToken')): ?>
                    <?= renderCSRFToken() ?>
                <?php endif; ?>
                
                <input type="hidden" name="save_theme" value="1">
                <input type="hidden" name="library_id" value="<?= $library_id ?>">

                <table class="s-table table">
                    <!-- WARNA -->
                    <tr>
                        <td colspan="2" class="alterCell font-weight-bold" style="background:#f1f3f5; font-size: 1.05rem;">
                            🎨 <?= __('Pengaturan Warna OPAC') ?>
                        </td>
                    </tr>
                    <tr>
                        <td class="alterCell font-weight-bold" style="width:220px; vertical-align: middle;"><?= __('Warna Utama') ?></td>
                        <td class="alterCell2">
                            <div style="display:flex; align-items:center; gap:12px;">
                                <input type="color" id="primary_color" name="primary_color" class="form-control" 
                                       value="<?= htmlspecialchars($theme['primary_color']) ?>" style="height:38px; width:65px; cursor:pointer; padding:2px;" onchange="updatePreview()">
                                <small class="text-muted"><?= __('Gunakan warna ini untuk Header OPAC, tombol, dan link utama.') ?></small>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?= __('Warna Sekunder') ?></td>
                        <td class="alterCell2">
                            <div style="display:flex; align-items:center; gap:12px;">
                                <input type="color" id="secondary_color" name="secondary_color" class="form-control" 
                                       value="<?= htmlspecialchars($theme['secondary_color']) ?>" style="height:38px; width:65px; cursor:pointer; padding:2px;" onchange="updatePreview()">
                                <small class="text-muted"><?= __('Digunakan pada area Footer dan elemen pendukung.') ?></small>
                            </div>
                        </td>
                    </tr>

                    <!-- TEKS -->
                    <tr>
                        <td colspan="2" class="alterCell font-weight-bold" style="background:#f1f3f5; font-size: 1.05rem;">
                            📝 <?= __('Pengaturan Teks Header & Footer') ?>
                        </td>
                    </tr>
                    <tr>
                        <td class="alterCell font-weight-bold"><?= __('Teks Header / Judul') ?></td>
                        <td class="alterCell2">
                            <input type="text" id="header_text" name="header_text" class="form-control col-8" 
                                   value="<?= htmlspecialchars($theme['header_text']) ?>" onkeyup="updatePreview()">
                        </td>
                    </tr>
                    <tr>
                        <td class="alterCell font-weight-bold"><?= __('Teks Footer') ?></td>
                        <td class="alterCell2">
                            <input type="text" id="footer_text" name="footer_text" class="form-control col-8" 
                                   value="<?= htmlspecialchars($theme['footer_text']) ?>" onkeyup="updatePreview()">
                        </td>
                    </tr>

                    <!-- LOGO -->
                    <tr>
                        <td colspan="2" class="alterCell font-weight-bold" style="background:#f1f3f5; font-size: 1.05rem;">
                            🖼️ <?= __('Upload Logo Perpustakaan') ?>
                        </td>
                    </tr>
                    <tr>
                        <td class="alterCell font-weight-bold" style="vertical-align: middle;"><?= __('Upload Logo') ?></td>
                        <td class="alterCell2">
                            <input type="file" name="logo_file" class="form-control col-6" accept="image/png,image/jpeg,image/gif,image/svg+xml,image/webp">
                            <small class="form-text text-muted">
                                <?= __('Format: PNG, JPG, GIF, SVG, WEBP. Maksimal 2MB.') ?>
                                <?php if (!empty($theme['logo'])): ?>
                                    <br><span style="color: green;">✅ <?= __('Logo saat ini tersimpan') ?>:</span><br>
                                    <img src="<?= htmlspecialchars($theme['logo']) ?>" style="max-height:50px; border:1px solid #ddd; padding:3px; margin-top:5px; border-radius:4px;">
                                <?php else: ?>
                                    <br><span style="color: #6c757d;"><?= __('Belum ada logo yang diupload.') ?></span>
                                <?php endif; ?>
                            </small>
                        </td>
                    </tr>

                    <!-- KONTEN NAVBAR KHUSUS -->
                    <tr>
                        <td colspan="2" class="alterCell font-weight-bold" style="background:#f1f3f5; font-size: 1.05rem;">
                            📄 <?= __('Kelola Halaman Content Navbar (Khusus Unit Ini)') ?>
                        </td>
                    </tr>
                    <?php foreach ($customContentMenus as $mKey => $mLabel): ?>
                        <tr>
                            <td class="alterCell font-weight-bold" style="vertical-align: top; padding-top: 15px;">
                                📌 <?= htmlspecialchars($mLabel) ?><br>
                                <small class="text-muted">Slug Path: <code><?= ($library_id == 1) ? $mKey : $library_id . '-' . $mKey ?></code></small>
                            </td>
                            <td class="alterCell2" style="padding: 15px;">
                                <div class="form-group mb-2">
                                    <label class="font-weight-bold" style="font-size:0.9rem;"><?= __('Judul Halaman') ?></label>
                                    <input type="text" name="content_title_<?= $mKey ?>" class="form-control col-8" 
                                           value="<?= htmlspecialchars($existingContents[$mKey]['title']) ?>" placeholder="Judul Halaman">
                                </div>
                                <div class="form-group mb-0">
                                    <label class="font-weight-bold" style="font-size:0.9rem;"><?= __('Isi Konten Halaman (HTML/Teks)') ?></label>
                                    <textarea name="content_body_<?= $mKey ?>" class="form-control col-12" rows="5" 
                                              placeholder="Tuliskan informasi atau konten HTML di sini..."><?= htmlspecialchars($existingContents[$mKey]['body']) ?></textarea>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>

                    <!-- PREVIEW -->
                    <tr>
                        <td colspan="2" class="alterCell font-weight-bold" style="background:#f1f3f5; font-size: 1.05rem;">
                            👁️ <?= __('Pratinjau Langsung Tampilan') ?>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" class="alterCell2" style="padding: 15px;">
                            <div class="border rounded shadow-sm overflow-hidden" style="max-width: 100%;">
                                <div id="prev-header" class="p-3 text-white" style="background-color: <?= $theme['primary_color'] ?>;">
                                    <h4 id="prev-header-text" class="m-0 text-white font-weight-bold"><?= htmlspecialchars($theme['header_text']) ?></h4>
                                </div>
                                <div class="p-4 bg-white">
                                    <p class="text-secondary mb-3"><?= __('Contoh Tampilan Komponen OPAC:') ?></p>
                                    <button type="button" id="prev-button" class="s-btn btn text-white px-4" style="background-color: <?= $theme['primary_color'] ?>; border:none;"><?= __('Cari Buku') ?></button>
                                </div>
                                <div id="prev-footer" class="p-2 text-white text-center" style="background-color: <?= $theme['secondary_color'] ?>;">
                                    <small id="prev-footer-text"><?= htmlspecialchars($theme['footer_text']) ?></small>
                                </div>
                            </div>
                        </td>
                    </tr>

                    <!-- SUBMIT -->
                    <tr>
                        <td class="alterCell font-weight-bold"></td>
                        <td class="alterCell2">
                            <button type="submit" class="s-btn btn btn-primary" id="submitBtn">💾 <?= __('Simpan Tema & Konten Navbar') ?></button>
                        </td>
                    </tr>
                </table>

            </form>
        </div>
    </div>
</div>

<script>
function saveThemeSettings() {
    var form = document.getElementById('themeForm');
    var formData = new FormData(form);
    
    $.ajax({
        url: form.action,
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        success: function(html) {
            var $target = parent.$('#mainContent').length ? parent.$('#mainContent') : $('#mainContent');
            if ($target.length) {
                $target.html(html);
            } else {
                $('#mainContent').html(html);
            }
        },
        error: function(xhr, status, error) {
            alert('AJAX error, mencoba submit biasa...');
            form.submit();
        }
    });
}

$(document).ready(function() {
    $('#themeForm').off('submit').on('submit', function(e) {
        e.preventDefault();
        saveThemeSettings();
    });
});

function updatePreview() {
    var primaryColor   = $('#primary_color').val();
    var secondaryColor = $('#secondary_color').val();
    var headerText     = $('#header_text').val();
    var footerText     = $('#footer_text').val();

    $('#prev-header, #prev-button').css('background-color', primaryColor);
    $('#prev-footer').css('background-color', secondaryColor);
    $('#prev-header-text').text(headerText);
    $('#prev-footer-text').text(footerText);
}
</script>

<style>
.spec-select {
    height: calc(2.25rem + 2px) !important;
    padding: .375rem 1.75rem .375rem .75rem !important;
}
.alterCell {
    background-color: #f8f9fa;
}
</style>