<?php
/**
 * Member Content Template - Adopsi dari SLiMS member.inc.php
 * Path: plugins/multi_opac_path/template/member_content.tpl
 * Version: 1.4.0 - Dengan menu Bebas Pustaka manual
 */

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

// Load fungsi member
require_once __DIR__ . '/../pages/member_functions.php';

// Tentukan section yang aktif
$section = isset($_GET['sec']) ? trim($_GET['sec']) : 'loan';

// Ambil library slug
$lib_slug = $_GET['lib'] ?? $_SESSION['multi_opac']['library_slug'] ?? 'pusat';

// Tampilkan member image
$member_image = $_SESSION['m_image'] && file_exists(IMGBS . 'persons/' . $_SESSION['m_image']) ? $_SESSION['m_image'] : 'person.png';
$member_image_url = './images/persons/' . $member_image;

// ============================================================
// NAVIGASI MEMBER (TANPA SIDEBAR)
// ============================================================
$tabs_menus = [
    'loan' => ['text' => __('Current Loan'), 'link' => '?p=member&lib=' . $lib_slug . '&sec=loan'],
    'bookmark' => ['text' => __('Title Bookmark'), 'link' => '?p=member&lib=' . $lib_slug . '&sec=bookmark'],
    'title_basket' => ['text' => __('Title Basket'), 'link' => '?p=member&lib=' . $lib_slug . '&sec=title_basket'],
    'history' => ['text' => __('Loan History'), 'link' => '?p=member&lib=' . $lib_slug . '&sec=history'],
    'my_account' => ['text' => __('My Account'), 'link' => '?p=member&lib=' . $lib_slug . '&sec=my_account']
];

// 🔥 TAMBAHKAN: Menu Bebas Pustaka secara manual
if (isset($_SESSION['mid'])) {
    // Cek apakah file plugin Bebas Pustaka ada
    $plugin_path = dirname(__DIR__, 2) . '/bebas_pustaka/bebas_pustaka.plugin.php';
    if (file_exists($plugin_path)) {
        $tabs_menus['bebaspustaka'] = [
    'text' => 'Bebas Pustaka',
    'link' => '?p=member&lib=' . $lib_slug . '&sec=bebaspustaka', // ✅ Gunakan sec
    'icon' => 'fa-file-text'
];
    }
}

// ============================================================
// HOOK: TAMBAHKAN MENU DARI PLUGIN LAIN
// ============================================================
$extraMenus = [];
try {
    \SLiMS\Plugins::getInstance()->execute('member_menu', ['menu' => &$extraMenus]);
} catch (Exception $e) {
    // Hook tidak tersedia, abaikan
}

if (!empty($extraMenus) && is_array($extraMenus)) {
    foreach ($extraMenus as $menu) {
        if (isset($menu['title']) && isset($menu['url'])) {
            $url = $menu['url'];
            if (strpos($url, '&lib=') === false && !empty($lib_slug) && $lib_slug !== 'pusat') {
                $url .= '&lib=' . urlencode($lib_slug);
            }
            $tabs_menus[$menu['title']] = [
                'text' => $menu['title'],
                'link' => $url,
                'icon' => $menu['icon'] ?? 'fa-file'
            ];
        }
    }
}
?>

<div class="member-area-wrapper">
    <!-- HEADER MEMBER -->
    <div class="member-header">
        <div class="d-flex align-items-center gap-3">
            <img src="<?= $member_image_url ?>" alt="member photo" class="rounded-circle" style="width: 60px; height: 60px; object-fit: cover; border: 2px solid #007bff;">
            <div>
                <h4 class="mb-0">Hi, <?= htmlspecialchars($_SESSION['m_name']) ?></h4>
                <span class="text-muted">
                    <?php if ($_SESSION['m_membership_pending']): ?>
                        <i class="fas fa-lock text-red"></i> Member status pending
                    <?php elseif ($_SESSION['m_is_expired']): ?>
                        <i class="far fa-calendar-times text-red"></i> Member expired
                    <?php else: ?>
                        <i class="far fa-user text-green"></i> <?= htmlspecialchars($_SESSION['m_member_type']) ?>
                    <?php endif; ?>
                </span>
            </div>
        </div>
        <div>
            <a href="?p=member&lib=<?= $lib_slug ?>&logout=1" class="btn btn-sm btn-outline-danger">
                <i class="fa-solid fa-right-from-bracket me-1"></i> Logout
            </a>
        </div>
    </div>

    <!-- NAVIGASI TAB -->
    <ul class="nav nav-tabs nav-fill mt-3">
        <?php foreach ($tabs_menus as $key => $tab): 
            $active = ($section === $key) ? 'active' : '';
            $icon = $tab['icon'] ?? '';
        ?>
            <li class="nav-item">
                <a class="nav-link <?= $active ?>" href="<?= $tab['link'] ?>">
                    <?php if ($icon): ?><i class="fa-solid <?= $icon ?> me-1"></i><?php endif; ?>
                    <?= $tab['text'] ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>

    <!-- KONTEN -->
    <div class="member-content mt-4">
<?php
switch ($section) {
    case 'loan':
        echo '<h5 class="fw-bold mb-3">' . __('My Current Loan') . '</h5>';
        echo showLoanList();
        break;
    case 'bookmark':
        echo '<h5 class="fw-bold mb-3">' . __('My Title Bookmark') . '</h5>';
        echo showBookmarkList();
        break;
    case 'title_basket':
        echo '<h5 class="fw-bold mb-3">' . __('My Title Basket') . '</h5>';
        echo showBasket();
        break;
    case 'history':
        echo '<h5 class="fw-bold mb-3">' . __('My Loan History') . '</h5>';
        echo showLoanHist();
        break;
    case 'my_account':
        echo '<h5 class="fw-bold mb-3">' . __('Member Detail') . '</h5>';
        echo showMemberDetail();
        echo '<div class="mt-4">';
        echo '<h5 class="fw-bold mb-3">' . __('Change Password') . '</h5>';
        echo changePassword();
        echo '</div>';
        break;
    case 'bebaspustaka':
        // 🔥 KONTEN BEBAS PUSTAKA DI DALAM LAYOUT MEMBER
        echo '<h5 class="fw-bold mb-3">Bebas Pustaka</h5>';
        
        $bebas_helper = dirname(__DIR__, 2) . '/bebas_pustaka/src/helper.php';
        if (file_exists($bebas_helper)) {
            require_once $bebas_helper;
            
            $bebas_file = dirname(__DIR__, 2) . '/bebas_pustaka/pages/member.php';
            if (file_exists($bebas_file)) {
                // Set variabel yang dibutuhkan
                $_GET['lib'] = $lib_slug;
                require_once $bebas_file;
            } else {
                echo '<div class="alert alert-danger">File Bebas Pustaka tidak ditemukan.</div>';
            }
        } else {
            echo '<div class="alert alert-danger">Plugin Bebas Pustaka tidak ditemukan.</div>';
        }
        break;
    default:
        if (isset($tabs_menus[$section])) {
            echo '<h5 class="fw-bold mb-3">' . $tabs_menus[$section]['text'] . '</h5>';
            echo '<div class="alert alert-info">Konten dari plugin: ' . htmlspecialchars($section) . '</div>';
        } else {
            echo '<div class="alert alert-warning">Halaman tidak ditemukan.</div>';
        }
}
?>
    </div>
</div>

<script>
$(document).ready(function() {
    $('.deleteBookmark').click(function(e) {
        e.preventDefault();
        let id = $(this).data('id');
        $.post('index.php?p=member&lib=<?= $lib_slug ?>', {bookmark_id: id, delete_bookmark: true}, function(res) {
            if (!res.status) {
                toastr.error(res.message);
            } else {
                toastr.success(res.message, '', {
                    timeOut: 2000,
                    onHidden: function() {
                        window.location.replace('index.php?p=member&lib=<?= $lib_slug ?>&sec=bookmark');
                    }
                });
            }
        }).fail(function() {
            toastr.error('Unexpected error. Please tell it to the librarian');
        });
    });
});
</script>

<style>
.member-area-wrapper .member-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background: #f8f9fa;
    border-radius: 12px;
    border: 1px solid #e9ecef;
}
.member-area-wrapper .nav-tabs .nav-link {
    color: #495057;
    border: none;
    padding: 10px 16px;
    border-radius: 8px;
}
.member-area-wrapper .nav-tabs .nav-link.active {
    background: #007bff;
    color: white;
}
.member-area-wrapper .member-content {
    padding: 16px 0;
}
@media (max-width: 768px) {
    .member-area-wrapper .member-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
    }
}
</style>