<?php
/**
 * Navigation Bar Template
 * CMTC Shopping
 */
// Count cart items
$cart_count = 0;
if (isset($_SESSION['user_id'])) {
    $stmt_cart = $db->prepare("
        SELECT SUM(ci.quantity) FROM cart_items ci 
        JOIN carts c ON ci.cart_id = c.id 
        WHERE c.user_id = ?
    ");
    $stmt_cart->execute([$_SESSION['user_id']]);
    $cart_count = intval($stmt_cart->fetchColumn());
}

// Get notifications and live order tracking statuses specifically for logged-in user
$unread_notifs = [];
$my_orders_tracking = [];

if (isset($_SESSION['user_id'])) {
    $current_uid = intval($_SESSION['user_id']);

    // Fetch ONLY unread notifications for this logged-in user ID
    $stmt_notif = $db->prepare("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5");
    $stmt_notif->execute([$current_uid]);
    $unread_notifs = $stmt_notif->fetchAll();

    // Fetch ONLY active ongoing orders placed by this logged-in user ID
    $stmt_my_orders = $db->prepare("
        SELECT o.id, o.order_no, o.status, o.net_amount, o.created_at, o.updated_at
        FROM orders o
        WHERE o.user_id = ? AND o.status NOT IN ('received', 'cancelled')
        ORDER BY o.updated_at DESC
        LIMIT 5
    ");
    $stmt_my_orders->execute([$current_uid]);
    $my_orders_tracking = $stmt_my_orders->fetchAll();
}
?>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark px-4 py-3 shadow-sm border-bottom border-secondary">
    <div class="container-fluid">
        <a class="navbar-brand d-flex align-items-center gap-2" href="<?php echo base_url('index.php'); ?>" style="text-decoration: none;">
            <?php if (!empty($sys_settings['logo'])): ?>
                <img src="<?php echo base_url('uploads/' . sanitize($sys_settings['logo'])); ?>" alt="Logo" height="38">
            <?php else: ?>
                <span class="d-inline-flex align-items-center justify-content-center text-white rounded-3 shadow-sm" style="width: 38px; height: 38px; background: linear-gradient(135deg, #0d6efd 0%, #00d2ff 100%); font-size: 1.25rem; box-shadow: 0 4px 12px rgba(13, 110, 253, 0.4) !important;">
                    <i class="bi bi-cart3"></i>
                </span>
            <?php endif; ?>
            <span class="fw-bold fs-4" style="font-family: 'Outfit', 'Sarabun', sans-serif; background: linear-gradient(135deg, #ffffff 40%, #85b3ff 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; letter-spacing: 0.5px;">
                <?php echo sanitize($sys_settings['system_name'] ?? 'CMTC Smart Outfit Shopping & Booking'); ?>
            </span>
        </a>
        
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarContent">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarContent">
            <!-- Global Search Form -->
            <form class="d-flex ms-auto me-3 my-2 my-lg-0" action="<?php echo base_url('views/search.php'); ?>" method="GET">
                <div class="input-group">
                    <input class="form-control bg-secondary text-white border-0" type="search" name="q" placeholder="ค้นหาสินค้า..." aria-label="Search" required>
                    <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i></button>
                </div>
            </form>

            <ul class="navbar-nav align-items-center gap-2">
                <!-- Shopping Cart -->
                <?php if (isset($_SESSION['user_id'])): ?>
                    <li class="nav-item">
                        <a class="nav-link position-relative px-2" href="<?php echo base_url('views/cart.php'); ?>" title="ตะกร้าสินค้า">
                            <i class="bi bi-cart3 fs-5"></i>
                            <?php if ($cart_count > 0): ?>
                                <span class="position-absolute top-1 start-100 translate-middle badge rounded-pill bg-danger" style="font-size: 0.65rem;">
                                    <?php echo $cart_count; ?>
                                </span>
                            <?php endif; ?>
                        </a>
                    </li>
                <?php endif; ?>

                <!-- Theme Toggle -->
                <li class="nav-item">
                    <a class="nav-link" href="#" id="btnThemeToggle">
                        <i class="bi bi-moon-fill fs-5"></i>
                    </a>
                </li>

                <!-- Notifications Dropdown -->
                <?php if (isset($_SESSION['user_id'])): ?>
                    <?php 
                    $total_notif_badge = count($unread_notifs) + count($my_orders_tracking);
                    ?>
                    <li class="nav-item dropdown">
                        <a class="nav-link position-relative dropdown-toggle no-arrow" href="#" id="notifDropdown" data-bs-toggle="dropdown">
                            <i class="bi bi-bell fs-5"></i>
                            <?php if ($total_notif_badge > 0): ?>
                                <span class="position-absolute top-1 start-100 translate-middle p-1 bg-danger border border-light rounded-circle"></span>
                            <?php endif; ?>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end shadow border-0 py-0" style="width: 350px; max-height: 480px; overflow-y: auto;" aria-labelledby="notifDropdown">
                            <li class="dropdown-header fw-bold bg-light py-2 border-bottom d-flex justify-content-between align-items-center">
                                <span class="text-dark"><i class="bi bi-bell-fill text-primary me-1"></i> ติดตามสถานะคำสั่งซื้อ</span>
                                <span class="badge bg-primary rounded-pill"><?php echo count($my_orders_tracking); ?> รายการ</span>
                            </li>

                            <!-- 1. Live Order Tracking List -->
                            <?php if (count($my_orders_tracking) > 0): ?>
                                <?php foreach ($my_orders_tracking as $ord): 
                                    $st = $ord['status'];
                                    $st_badge = 'bg-secondary';
                                    $st_icon = 'bi-clock-history';
                                    $st_text = 'รอดำเนินการ / รอชำระเงิน';
                                    
                                    if ($st === 'paid') {
                                        $st_badge = 'bg-info text-dark';
                                        $st_icon = 'bi-credit-card-check';
                                        $st_text = 'แจ้งชำระแล้ว (รอตรวจสอบ)';
                                    } elseif ($st === 'approved') {
                                        $st_badge = 'bg-success';
                                        $st_icon = 'bi-check-circle-fill';
                                        $st_text = 'อนุมัติการชำระเงินแล้ว';
                                    } elseif ($st === 'preparing') {
                                        $st_badge = 'bg-warning text-dark';
                                        $st_icon = 'bi-box-seam';
                                        $st_text = 'กำลังเตรียมจัดส่ง / แพ็กของ';
                                    } elseif ($st === 'ready') {
                                        $st_badge = 'bg-primary';
                                        $st_icon = 'bi-bag-check-fill';
                                        $st_text = 'สินค้าพร้อมรับแล้ว!';
                                    } elseif ($st === 'received') {
                                        $st_badge = 'bg-dark';
                                        $st_icon = 'bi-house-check-fill';
                                        $st_text = 'รับสินค้าเรียบร้อยแล้ว';
                                    } elseif ($st === 'cancelled') {
                                        $st_badge = 'bg-danger';
                                        $st_icon = 'bi-x-circle-fill';
                                        $st_text = 'คำสั่งซื้อถูกยกเลิก';
                                    }
                                ?>
                                    <li>
                                        <a class="dropdown-item py-2 border-bottom border-light d-block text-decoration-none" href="<?php echo base_url('views/order_detail.php?id=' . $ord['id']); ?>" style="white-space: normal;">
                                            <div class="d-flex justify-content-between align-items-center mb-1">
                                                <span class="fw-bold text-dark" style="font-size: 0.85rem;"><i class="bi bi-receipt me-1"></i><?php echo sanitize($ord['order_no']); ?></span>
                                                <span class="badge <?php echo $st_badge; ?>" style="font-size: 0.7rem;"><i class="bi <?php echo $st_icon; ?> me-1"></i><?php echo $st_text; ?></span>
                                            </div>
                                            <div class="d-flex justify-content-between align-items-center text-muted" style="font-size: 0.75rem;">
                                                <span>ยอดชำระ: <strong class="text-primary"><?php echo format_price($ord['net_amount']); ?></strong></span>
                                                <span><?php echo format_thai_date($ord['updated_at'], true); ?></span>
                                            </div>
                                        </a>
                                    </li>
                                <?php endforeach; ?>
                            <?php endif; ?>

                            <!-- 2. System Notifications List -->
                            <?php if (count($unread_notifs) > 0): ?>
                                <li class="dropdown-header fw-bold bg-light py-2 border-bottom border-top text-dark">
                                    <i class="bi bi-chat-left-dots-fill text-info me-1"></i> การแจ้งเตือนระบบ
                                </li>
                                <?php foreach ($unread_notifs as $notif): 
                                    $link_url = '#';
                                    if (preg_match('/(CMTC-\d+-\d+)/', $notif['message'], $matches)) {
                                        $order_no = $matches[1];
                                        $stmt_ord = $db->prepare("SELECT id FROM orders WHERE order_no = ? LIMIT 1");
                                        $stmt_ord->execute([$order_no]);
                                        $ord_id = $stmt_ord->fetchColumn();
                                        if ($ord_id) {
                                            $link_url = base_url("views/order_detail.php?id=" . $ord_id);
                                        }
                                    }
                                ?>
                                    <li>
                                        <a class="dropdown-item py-2 border-bottom border-light" href="<?php echo $link_url; ?>" style="white-space: normal;">
                                            <div class="fw-bold text-primary" style="font-size: 0.82rem;"><?php echo sanitize($notif['title']); ?></div>
                                            <div class="text-muted mt-1 mb-1" style="font-size: 0.78rem; line-height: 1.4;"><?php echo sanitize($notif['message']); ?></div>
                                            <div class="text-end text-muted" style="font-size: 0.68rem;"><?php echo format_thai_date($notif['created_at']); ?></div>
                                        </a>
                                    </li>
                                <?php endforeach; ?>
                            <?php endif; ?>

                            <?php if (count($my_orders_tracking) == 0 && count($unread_notifs) == 0): ?>
                                <li class="text-center py-4 text-muted small">
                                    <i class="bi bi-inbox fs-3 d-block mb-1 opacity-50"></i>
                                    ไม่มีข้อมูลคำสั่งซื้อหรือการแจ้งเตือน
                                </li>
                            <?php endif; ?>
                        </ul>
                    </li>

                    <!-- User Profile Dropdown -->
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle d-flex align-items-center gap-2" href="#" id="profileDropdown" data-bs-toggle="dropdown">
                            <?php if (!empty($_SESSION['avatar'])): ?>
                                <img src="<?php echo base_url('uploads/' . sanitize($_SESSION['avatar'])); ?>" class="rounded-circle" width="30" height="30" style="object-fit: cover;">
                            <?php else: ?>
                                <i class="bi bi-person-circle fs-5"></i>
                            <?php endif; ?>
                            <span class="small d-none d-md-inline"><?php echo sanitize($_SESSION['fullname']); ?></span>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end shadow border-0" aria-labelledby="profileDropdown">
                            <li><a class="dropdown-item" href="<?php echo base_url('views/profile.php'); ?>"><i class="bi bi-person me-2"></i>ข้อมูลส่วนตัว</a></li>
                            <?php if ($_SESSION['role_id'] == 1 || $_SESSION['role_id'] == 2 || $_SESSION['role_id'] == 3): ?>
                                <li><a class="dropdown-item" href="<?php echo base_url('views/dashboard.php'); ?>"><i class="bi bi-speedometer2 me-2"></i>แดชบอร์ดจัดการ</a></li>
                            <?php endif; ?>
                            <?php if ($_SESSION['role_id'] == 3): ?>
                                <li><a class="dropdown-item" href="<?php echo base_url('views/orders.php'); ?>"><i class="bi bi-journal-text me-2"></i>ประวัติการจอง</a></li>
                            <?php endif; ?>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="<?php echo base_url('logout.php'); ?>"><i class="bi bi-box-arrow-right me-2"></i>ออกจากระบบ</a></li>
                        </ul>
                    </li>
                <?php else: ?>
                    <li class="nav-item">
                        <a class="btn btn-outline-light me-2" href="<?php echo base_url('login.php'); ?>">เข้าสู่ระบบ</a>
                    </li>
                    <li class="nav-item">
                        <a class="btn btn-primary" href="<?php echo base_url('register.php'); ?>">สมัครสมาชิก</a>
                    </li>
                <?php endif; ?>
            </ul>
        </div>
    </div>
</nav>
