<?php 
include 'config.php'; 

// --- অফিসার লগইন লজিক ---
if (session_status() === PHP_SESSION_NONE) { session_start(); }

// লগআউট হ্যান্ডেলার
if(isset($_GET['officer_logout'])) {
    unset($_SESSION['officer_logged_in']);
    header("Location: index.php"); exit;
}

// লগইন হ্যান্ডেলার
$off_error = "";
if(isset($_POST['officer_login'])) {
    $email = mysqli_real_escape_string($conn, $_POST['off_email']);
    $pass = $_POST['off_pass'];
    $res = $conn->query("SELECT * FROM officer_users WHERE email='$email'");
    if($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        if(password_verify($pass, $row['password'])) {
            $_SESSION['officer_logged_in'] = true;
            $_SESSION['officer_id'] = $row['id']; // আইডি সেভ করা হলো
            header("Location: index.php"); exit;
        } else { $off_error = "Wrong Password!"; }
    } else { $off_error = "Email not found!"; }
}

$is_officer = isset($_SESSION['officer_logged_in']);

include 'header.php'; 

// কার্ড হাইট সেটআপ
$h = "200px";
if($theme['card_size']=='small') $h="140px";
if($theme['card_size']=='large') $h="280px";

// ফন্ট সাইজ সেটিংস
$cat_mob = isset($theme['fs_cat_mob']) ? $theme['fs_cat_mob'] : 20;
$cat_tab = isset($theme['fs_cat_tab']) ? $theme['fs_cat_tab'] : 24;
$cat_pc  = isset($theme['fs_cat_pc'])  ? $theme['fs_cat_pc']  : 30;

$card_mob = isset($theme['fs_card_mob']) ? $theme['fs_card_mob'] : 16;
$card_tab = isset($theme['fs_card_tab']) ? $theme['fs_card_tab'] : 18;
$card_pc  = isset($theme['fs_card_pc'])  ? $theme['fs_card_pc']  : 20;
?>

<style>
    body { display: flex; flex-direction: column; min-height: 100vh; }
    .main-content { flex: 1; width: 100%; padding-bottom: 50px; }

    /* গ্রিড লেআউট */
    .grid-wrap {
        display: grid; gap: 20px; padding: 30px 15px; max-width: 1200px; margin: 0 auto;
        grid-template-columns: repeat(<?= $theme['col_mobile'] ?>, 1fr);
    }
    @media (min-width: 768px) {
        .grid-wrap { grid-template-columns: repeat(<?= $theme['col_desktop'] ?>, 1fr); }
    }

    /* কার্ড ডিজাইন */
    .t-card {
        background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1);
        border-radius: 12px; overflow: hidden; transition: 0.3s; position: relative;
        backdrop-filter: blur(5px); height: 100%; display: flex; flex-direction: column;
    }
    .t-card:hover { 
        transform: translateY(-7px); border-color: <?= $theme['effect_color'] ?>; 
        box-shadow: 0 10px 30px -10px <?= $theme['effect_color'] ?>; 
    }
    /* Enhanced Tag-Style Styles */
    .badge-offer { 
        position: absolute; top: 10px; right: 10px; 
        background: #ff3333; color: #fff; 
        width: 45px; height: 45px; 
        display: flex; align-items: center; justify-content: center;
        border-radius: 50%; font-size: 11px; font-weight: 800; z-index: 5; 
        box-shadow: 0 4px 10px rgba(255,51,51,0.4); animation: pulse 1.5s infinite;
        border: 2px dashed rgba(255,255,255,0.5);
    }
    .badge-status { 
        position: absolute; top: 10px; left: 10px; padding: 4px 10px; border-radius: 50px; 
        font-size: 10px; font-weight: bold; text-transform: uppercase; z-index: 5; color: #000;
        box-shadow: 0 0 10px rgba(0,0,0,0.5);
    }
    .status-update { background: #00f2ff; }
    .status-upcoming { background: #ffcc00; }
    
    /* কার্ড ব্লকার ডিজাইন - ক্লিয়ার ভিউ */
    .card-blocker {
        position: absolute; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.6); backdrop-filter: blur(3px); /* ব্লার কমানো হয়েছে */
        display: flex; flex-direction: column; justify-content: center; align-items: center;
        z-index: 10; color: #fff; text-align: center;
    }
    .gear-spinner {
        font-size: 50px; 
        color: #fff; /* সেটিংস আইকন সাদা */
        text-shadow: 0 0 20px <?= $theme['effect_color'] ?>;
        animation: gear-rotate 3s linear infinite;
        margin-bottom: 12px;
    }
    .card-blocker b {
        background: <?= $theme['effect_color'] ?>; /* থিম কালার ব্যাকগ্রাউন্ড */
        color: #fff !important; /* সাদা টেক্সট */
        padding: 5px 15px;
        border-radius: 5px;
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 1px;
        box-shadow: 0 0 15px <?= $theme['effect_color'] ?>;
    }
    @keyframes gear-rotate {
        from { transform: rotate(0deg); }
        to { transform: rotate(360deg); }
    }

    /* টাইটেল আরও স্পষ্ট করা */
    .t-title { 
        text-shadow: 1px 1px 2px rgba(0,0,0,0.8);
        letter-spacing: 0.5px;
        line-height: 1.2;
    }

    .timer-box { 
        position: absolute; bottom: 0; left: 0; width: 100%; background: #000; 
        color: #fff; text-align: center; font-size: 12px; padding: 6px 0; font-family: 'Courier New', monospace;
        border-top: 2px solid var(--accent); z-index: 15; font-weight: bold;
    }

    /* Status Blocking Overlay */
    #statusOverlay {
        display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.9); z-index: 9999999; justify-content: center; align-items: center;
        backdrop-filter: blur(10px); text-align: center; color: #fff; padding: 20px;
    }
    .overlay-content { max-width: 400px; width: 90%; }
    .overlay-icon { font-size: 60px; margin-bottom: 20px; }
    .overlay-title { font-size: 24px; font-weight: bold; margin-bottom: 10px; color: var(--accent); }
    .overlay-msg { font-size: 16px; opacity: 0.8; margin-bottom: 25px; }
    
    /* Animations */
    @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } }
    .fa-spin-slow { animation: fa-spin 3s infinite linear; }
    .t-img { width: 100%; height: <?= $h ?>; object-fit: cover; display: block; aspect-ratio: 1 / 1; border-bottom: 3px solid <?= $theme['effect_color'] ?>; }
    .t-body { padding: 15px; text-align: <?= $theme['text_align'] ?>; flex-grow: 1; }
    
    .t-title { 
        color: <?= $theme['title_color'] ?>; font-weight: bold; 
        display: <?= $theme['show_title']?'block':'none' ?>; margin-bottom: 5px;
    }
    .t-desc { 
        color: <?= $theme['desc_color'] ?>; font-size: 13px; 
        display: <?= $theme['show_desc']?'block':'none' ?>; opacity: 0.8; line-height: 1.4;
    }

    /* ক্যাটাগরি টাইটেল এলাইনমেন্ট ফিক্স */
    .cat-title {
        max-width: 1200px; margin: 40px auto 0 auto; padding: 0 15px;
        color: <?= $theme['effect_color'] ?>; text-transform: uppercase;
        font-weight: 800; letter-spacing: 2px; display: flex; align-items: center; gap: 15px;
    }

    /* পজিশন অনুযায়ী লাইন সেটআপ */
    .cat-title.align-center { justify-content: center; }
    .cat-title.align-left { justify-content: flex-start; }
    .cat-title.align-right { justify-content: flex-end; }

    /* লাইনের লজিক */
    .cat-title.align-center::before, .cat-title.align-center::after { content: ""; flex: 1; height: 1px; background: rgba(255,255,255,0.1); }
    .cat-title.align-left::after { content: ""; flex: 1; height: 1px; background: rgba(255,255,255,0.1); }
    .cat-title.align-right::before { content: ""; flex: 1; height: 1px; background: rgba(255,255,255,0.1); }

    /* রেসপন্সিভ ফন্ট */
    .cat-title { font-size: <?= $cat_mob ?>px; }
    .t-title   { font-size: <?= $card_mob ?>px; }
    @media (min-width: 768px) {
        .cat-title { font-size: <?= $cat_tab ?>px; }
        .t-title   { font-size: <?= $card_tab ?>px; }
    }
    @media (min-width: 1024px) {
        .cat-title { font-size: <?= $cat_pc ?>px; }
        .t-title   { font-size: <?= $card_pc ?>px; }
    }

    /* অফিসার লগইন মডাল স্টাইল */
    #officerModal {
        display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.95); z-index: 1000000; justify-content: center; align-items: center;
    }
    .off-modal-content {
        background: #1f2833; padding: 30px; border-radius: 12px; border: 2px solid <?= $theme['effect_color'] ?>;
        width: 90%; max-width: 350px; position: relative; box-shadow: 0 0 30px rgba(0,242,255,0.2);
    }
    
</style>

<div class="main-content">
    <?php if($theme['inline_notice_status']): ?>
    <div class="main-notice-box">
        <i class="fas fa-bullhorn me-2"></i> <?= htmlspecialchars($theme['inline_notice_text']) ?>
    </div>
    <?php endif; ?>

    

    <?php
    $page_slug = isset($_GET['page']) ? mysqli_real_escape_string($conn, $_GET['page']) : null;

    if ($page_slug) {
        $sql = "SELECT id, name AS category, cat_align, access_level FROM categories WHERE cat_slug = '$page_slug' LIMIT 1";
    } else {
        if ($is_officer) {
            // অফিসারের জন্য শুধু পারমিশন দেওয়া ক্যাটাগরিগুলো (আইডি অনুযায়ী)
            $off_id = (int)$_SESSION['officer_id'];
            $sql = "SELECT id, name AS category, cat_align, access_level FROM categories 
                    WHERE cat_status = 1 
                    AND id IN (SELECT category_id FROM officer_permissions WHERE officer_id = $off_id)
                    ORDER BY cat_order ASC";
        } else {
            // পাবলিক ইউজারদের জন্য শুধু access_level = 0
            $sql = "SELECT id, name AS category, cat_align, access_level FROM categories 
                    WHERE cat_status = 1 AND access_level = 0 
                    ORDER BY cat_order ASC";
        }
    }

    $cat_res = $conn->query($sql);
    
    if($cat_res->num_rows > 0) {
        while($cat_row = $cat_res->fetch_assoc()) {
            // যদি অফিসার ক্যাটাগরি হয় এবং অফিসার লগইন না থাকে
            if($cat_row['access_level'] == 1 && !$is_officer) {
                echo '<div style="text-align:center; padding:80px 20px; color:#aaa;">
                    <i class="fas fa-lock fa-4x mb-4" style="color:'.$theme['effect_color'].'"></i>
                    <h2 style="color:#fff;">Officer Only Content</h2>
                    <p>You need an Officer account to view this section.</p>';
                    // যদি সেটিংসে বাটন শো করা থাকে তবেই লগইন বাটন দেখাবে
                    if(isset($theme['show_officer_btn']) && $theme['show_officer_btn'] == 1) {
                        echo '<button class="btn btn-info mt-3" onclick="openOfficerModal()" style="font-weight:bold;">OFFICER LOGIN</button>';
                    }
                echo '</div>';
                continue;
            }

            $current_cat = $cat_row['category'];
            // ডাটাবেস থেকে এলাইনমেন্ট ভ্যালু নেওয়া হচ্ছে
            $align_val = !empty($cat_row['cat_align']) ? $cat_row['cat_align'] : 'center';
            ?>
            <div class="cat-title align-<?= $align_val ?>"><?= htmlspecialchars($current_cat) ?></div>
            <div class="grid-wrap">
                <?php
                $res = $conn->query("SELECT * FROM site_links WHERE category='".mysqli_real_escape_string($conn, $current_cat)."' ORDER BY sort_order ASC");
                while($row = $res->fetch_assoc()) {
                    $status = isset($row['item_status']) ? $row['item_status'] : 'normal';
                    $has_timer = !empty($row['timer_deadline']) && !str_starts_with($row['timer_deadline'], '0000');
                    $safe_title = addslashes(htmlspecialchars($row['title']));
                    
                    // ক্লিক ব্লক লজিক (আপডেট বা আপকামিং হলে ক্লিক ডিজেবল থাকবে এবং কোনো পপআপ আসবে না)
                    if($status !== 'normal') {
                        $click_action = "event.preventDefault(); return false;";
                        $target_url = "javascript:void(0)";
                    } else {
                        $click_action = "window.location.href='".$row['url']."'";
                        $target_url = $row['url'];
                    }
                ?>
                    <a href="javascript:void(0)" onclick="<?= $click_action ?>" style="text-decoration:none;" class="searchable-item">
                        <div class="t-card">
                            <?php if(isset($row['show_discount']) && $row['show_discount'] == 1 && !empty($row['offer_percentage'])): ?>
                                <div class="badge-offer">🏷️<br><?= htmlspecialchars($row['offer_percentage']) ?></div>
                            <?php endif; ?>

                            <?php if($status == 'update'): ?>
                                <div class="badge-status status-update"><i class="fas fa-sync-alt"></i> Update</div>
                            <?php elseif($status == 'upcoming'): ?>
                                <div class="badge-status status-upcoming"><i class="fas fa-clock"></i> Upcoming</div>
                            <?php endif; ?>

                            <img src="uploads/<?= $row['image'] ?>" class="t-img img-fluid" style="max-width: 100%; height: auto;" loading="lazy" onerror="this.src='https://via.placeholder.com/512?text=No+Image';">
                            
                            <?php if($status !== 'normal'): ?>
                                <div class="card-blocker">
                                    <i class="fas fa-cog gear-spinner"></i>
                                    <b>
                                        <?php 
                                            if($status == 'update') echo '🔄 UPDATING...';
                                            elseif($status == 'upcoming') echo '⏳ UPCOMING...';
                                            else echo strtoupper($status).'...';
                                        ?>
                                    </b>
                                </div>
                            <?php endif; ?>

                            <?php if($has_timer): ?>
                                <div class="timer-box countdown-timer" data-time="<?= date('Y-m-d H:i:s', strtotime($row['timer_deadline'])) ?>" style="border-top-color: <?= $theme['effect_color'] ?>;">
                                    00:00:00
                                </div>
                            <?php endif; ?>

                            <?php if($theme['show_title'] || $theme['show_desc']): ?>
                            <div class="t-body">
                                <div class="t-title"><?= $row['title'] ?></div>
                                <div class="t-desc"><?= $row['description'] ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </a>
                <?php } ?>
            </div>
            <?php
        }
    } else {
        echo '<div style="text-align:center; width:100%; padding: 50px; color: #aaa;"><h3>Nothing to show here.</h3></div>';
    }
    ?>

    <!-- অফিসার বাটন সেকশন -->
    <?php if($is_officer || (isset($theme['show_officer_btn']) && $theme['show_officer_btn'] == 1)): ?>
    <div style="text-align:center; margin-top:50px; padding: 20px;">
        <?php if($is_officer): ?>
            <span style="color:lime; font-size:12px; display:block; margin-bottom:10px;"><i class="fas fa-user-check"></i> Logged in as Officer</span>
            <a href="?officer_logout=1" style="color:#ff3333; text-decoration:none; font-size:12px; font-weight:bold; border:1px solid #ff3333; padding:5px 15px; border-radius:50px;"><i class="fas fa-sign-out-alt"></i> LOGOUT</a>
        <?php else: ?>
            <span onclick="openOfficerModal()" style="color:#444; cursor:pointer; font-size:12px; border:1px solid #333; padding:8px 20px; border-radius:50px;"><i class="fas fa-user-shield"></i> Officer Area</span>
        <?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<!-- OFFICER LOGIN MODAL -->
<div id="officerModal">
    <div class="off-modal-content">
        <span onclick="closeOfficerModal()" style="position:absolute; top:10px; right:15px; color:#fff; cursor:pointer; font-size:28px;">&times;</span>
        <div style="text-align:center; margin-bottom:20px;">
            <i class="fas fa-user-shield fa-3x" style="color:<?= $theme['effect_color'] ?>;"></i>
            <h4 style="color:<?= $theme['effect_color'] ?>; margin-top:10px;">OFFICER LOGIN</h4>
            <?php if($off_error): ?><p style="color:red; font-size:12px;"><?= $off_error ?></p><?php endif; ?>
        </div>
        <form method="POST">
            <input type="email" name="off_email" placeholder="Officer Email" style="width:100%; padding:12px; margin-bottom:10px; background:#000; border:1px solid #444; color:#fff; border-radius:5px;" required>
            <input type="password" name="off_pass" placeholder="Password" style="width:100%; padding:12px; margin-bottom:15px; background:#000; border:1px solid #444; color:#fff; border-radius:5px;" required>
            <button type="submit" name="officer_login" style="width:100%; padding:12px; background:<?= $theme['effect_color'] ?>; border:none; color:#000; font-weight:bold; border-radius:5px; cursor:pointer;">LOGIN</button>
        </form>
    </div>
</div>

<script>
    // অফিসার মডাল ওপেন/ক্লোজ ফাংশন
    function openOfficerModal() {
        document.getElementById('officerModal').style.display = 'flex';
    }
    function closeOfficerModal() {
        document.getElementById('officerModal').style.display = 'none';
    }

    // এরর থাকলে মডাল অটোমেটিক ওপেন হবে
    <?php if($off_error): ?> window.onload = openOfficerModal; <?php endif; ?>

    // বাইরে ক্লিক করলে ক্লোজ
    window.onclick = function(event) {
        let modal = document.getElementById('officerModal');
        if (event.target == modal) { closeOfficerModal(); }
    }

    // পপআপ ফাংশন
    function closePopup() { 
        if(document.getElementById('sitePopup')) {
            document.getElementById('sitePopup').style.display = 'none'; 
        }
    }

    function updateCountdowns() {
        $(".countdown-timer").each(function() {
            var dateStr = $(this).attr("data-time");
            if(!dateStr) return;
            dateStr = dateStr.replace(/-/g, "/"); 
            var deadline = new Date(dateStr).getTime();
            var now = new Date().getTime();
            var t = deadline - now;

            if (t > 0) {
                var d = Math.floor(t / (1000 * 60 * 60 * 24));
                var h = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                var m = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
                var s = Math.floor((t % (1000 * 60)) / 1000);

                var display = (d > 0 ? d + "d " : "") + 
                              (h < 10 ? "0" + h : h) + ":" + 
                              (m < 10 ? "0" + m : m) + ":" + 
                              (s < 10 ? "0" + s : s);
                
                $(this).html('<i class="fas fa-clock" style="color:inherit;"></i> ' + display);
            } else {
                $(this).html('<i class="fas fa-check-circle"></i> RELEASED');
            }
        });
    }
    setInterval(updateCountdowns, 1000);
    updateCountdowns();

    // Status Overlay Logic
    function showStatusBlock(title, type) {
        const overlay = document.getElementById('statusOverlay');
        const iconBox = document.getElementById('overlayIcon');
        const titleBox = document.getElementById('overlayTitle');
        const msgBox = document.getElementById('overlayMsg');

        titleBox.innerText = title;
        
        if(type === 'upcoming') {
            iconBox.innerHTML = '<i class="fas fa-cog fa-spin-slow" style="color:#ffcc00;"></i>';
            msgBox.innerText = "This item is currently UPCOMING. We are working hard to bring it to you soon!";
        } else if(type === 'update') {
            iconBox.innerHTML = '<i class="fas fa-sync-alt fa-spin" style="color:#00f2ff;"></i>';
            msgBox.innerText = "This item is under MAINTENANCE/UPDATE. Please check back after a few minutes.";
        }

        overlay.style.display = 'flex';
        document.body.style.overflow = 'hidden'; // Prevent scroll
    }

    function closeStatusBlock() {
        document.getElementById('statusOverlay').style.display = 'none';
        document.body.style.overflow = 'auto';
    }
    $(document).ready(function() {
        $("#itemSearch").on("keyup", function() {
            var value = $(this).val().toLowerCase();
            
            // আইটেম ফিল্টার করা
            $(".searchable-item").each(function() {
                var toggle = $(this).find(".t-title").text().toLowerCase().indexOf(value) > -1;
                $(this).toggle(toggle);
            });

            // খালি ক্যাটাগরি হাইড করা
            $(".grid-wrap").each(function() {
                var hasVisibleItems = $(this).find(".searchable-item:visible").length > 0;
                $(this).toggle(hasVisibleItems);
                $(this).prev(".cat-title").toggle(hasVisibleItems);
            });
        });
    });
</script>

<?php if($theme['popup_status']): ?>
<div class="popup-overlay" id="sitePopup" style="display:flex;">
    <div class="popup-content p-style-<?= $theme['popup_style'] ?>">
        <span class="p-close" onclick="closePopup()">&times;</span>
        <?php if(!empty($theme['popup_image'])): ?>
            <a href="<?= !empty($theme['popup_link']) ? $theme['popup_link'] : 'javascript:void(0)' ?>"><img src="uploads/<?= $theme['popup_image'] ?>" class="p-image"></a>
        <?php endif; ?>
        <div class="p-title"><?= htmlspecialchars($theme['popup_title']) ?></div>
        <div class="p-text"><?= nl2br(htmlspecialchars($theme['popup_text'])) ?></div>
        <div style="text-align:center;">
            <?php if($theme['popup_btn_status']): ?>
                <a href="<?= !empty($theme['popup_link']) ? $theme['popup_link'] : '#' ?>" class="p-btn" id="popupBtn">
                    <?= htmlspecialchars($theme['popup_btn_name']) ?> <span id="p-timer-count"><?= $theme['popup_timer'] > 0 ? '('.$theme['popup_timer'].')' : '' ?></span>
                </a>
            <?php endif; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- STATUS OVERLAY BLOCK -->
<div id="statusOverlay">
    <div class="overlay-content">
        <div id="overlayIcon" class="overlay-icon"></div>
        <div id="overlayTitle" class="overlay-title"></div>
        <div id="overlayMsg" class="overlay-msg"></div>
        <button onclick="closeStatusBlock()" style="background:var(--accent); color:#000; border:none; padding:10px 30px; border-radius:50px; font-weight:bold; cursor:pointer; margin-top:10px;">OKAY</button>
    </div>
</div>

<?php include 'footer.php'; ?>

        <?php require_once 'security/security.php'; echo get_complete_security(); ?>