
<?php

require_once 'config/db_config.php';

// Validate session
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role'])) {
    header("Location: login.php");
    exit();
}

// Helper function to display time ago
function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime();
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = [
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    ];

    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) {
        $string = array_slice($string, 0, 1);
    }
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

// Fetch notification count
$notification_count = 0;
try {
    $user_id = $_SESSION['user_id'];
    $role = $_SESSION['role'];
    $query = "SELECT COUNT(*) as count FROM notifications WHERE user_id = :user_id AND status = 'pending'";
    $params = [':user_id' => $user_id];

    if ($role === 'branch' && isset($_SESSION['branch_id'])) {
        $query .= " AND branch_id = :branch_id";
        $params[':branch_id'] = $_SESSION['branch_id'];
    }

    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $notification_count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
} catch (PDOException $e) {
    error_log("Error fetching notification count: " . $e->getMessage());
}
?>

<style>
/* Light mode styles */
.navbar-header {
    padding: 12px 16px;
    background-color: #fff;
    border-bottom: 1px solid #e0e0e0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.sidebar-toggle, .sidebar-mobile-toggle {
    width: 40px;
    height: 40px;
    background-color: #f5f5f5;
    border: none;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.sidebar-toggle:hover, .sidebar-mobile-toggle:hover {
    background-color: #e0e0e0;
}

.sidebar-toggle .icon, .sidebar-mobile-toggle .icon {
    font-size: 1.5rem;
    color: #333;
}

.navbar-search {
    position: relative;
    max-width: 300px;
    width: 100%;
}

.navbar-search input {
    width: 100%;
    padding: 8px 16px 8px 40px;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    font-size: 0.875rem;
    background-color: #fff;
    color: #333;
    transition: border-color 0.3s ease;
}

.navbar-search input:focus {
    outline: none;
    border-color: #007bff;
}

.navbar-search .icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 1rem;
    color: #6c757d;
}

.branch-info {
    font-size: 0.875rem;
    display: flex;
    align-items: center;
    background-color: #e7f1ff;
    padding: 8px 12px;
    border-radius: 6px;
    color: #005566;
}

.has-indicator {
    position: relative;
}

.indicator {
    position: absolute;
    top: 0;
    right: 0;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    border: 2px solid #fff;
}

.dropdown-menu-lg {
    min-width: 320px;
    max-width: 400px;
    border-radius: 8px;
    background-color: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dropdown-menu-sm {
    min-width: 200px;
    border-radius: 8px;
    background-color: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.max-h-400-px {
    max-height: 400px;
    overflow-y: auto;
}

.scroll-sm {
    scrollbar-width: thin;
    scrollbar-color: #ccc #f5f5f5;
}

.scroll-sm::-webkit-scrollbar {
    width: 6px;
}

.scroll-sm::-webkit-scrollbar-track {
    background: #f5f5f5;
}

.scroll-sm::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 3px;
}

.to-top-list li a {
    padding: 10px 16px;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #333;
    transition: background-color 0.3s ease, color 0.3s ease;
}

.to-top-list li a:hover {
    background-color: #f5f5f5;
    color: #007bff;
}

.brand-title-sm {
    display: none;
    font-size: 1.25rem;
    font-weight: 600;
    color: #333;
}

.brand-title-lg {
    font-size: 1.5rem;
    font-weight: 600;
    color: #333;
}

/* Dark mode styles */
[data-theme="dark"] .navbar-header {
    background-color: #273142;
    border-bottom: 1px solid #333;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

[data-theme="dark"] .sidebar-toggle,
[data-theme="dark"] .sidebar-mobile-toggle {
    background-color: #273142;
}

[data-theme="dark"] .sidebar-toggle:hover,
[data-theme="dark"] .sidebar-mobile-toggle:hover {
    background-color: #273142;
}

[data-theme="dark"] .sidebar-toggle .icon,
[data-theme="dark"] .sidebar-mobile-toggle .icon {
    color: #ccc;
}

[data-theme="dark"] .navbar-search input {
    background-color: #2a2a2a;
    border-color: #444;
    color: #ccc;
}

[data-theme="dark"] .navbar-search input:focus {
    border-color: #007bff;
}

[data-theme="dark"] .navbar-search .icon {
    color: #999;
}

[data-theme="dark"] .branch-info {
    background-color: #2a3f5f;
    color: #e7f1ff;
}

[data-theme="dark"] .dropdown-menu-lg,
[data-theme="dark"] .dropdown-menu-sm {
    background-color: #2a2a2a;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

[data-theme="dark"] .to-top-list li a {
    color: #ccc;
}

[data-theme="dark"] .to-top-list li a:hover {
    background-color: #333;
    color: #007bff;
}

[data-theme="dark"] .brand-title-sm,
[data-theme="dark"] .brand-title-lg {
    color: #ccc;
}

[data-theme="dark"] .dropdown-menu-lg .bg-primary-50,
[data-theme="dark"] .dropdown-menu-sm .bg-primary-50 {
    background-color: #2a3f5f;
}

[data-theme="dark"] .text-primary-light {
    color: #e7f1ff !important;
}

[data-theme="dark"] .text-secondary-light {
    color: #999 !important;
}

[data-theme="dark"] .text-black {
    color: #ccc !important;
}

[data-theme="dark"] .bg-base {
    background-color: #2a2a2a !important;
}

[data-theme="dark"] .bg-neutral-50 {
    background-color: #333 !important;
}

[data-theme="dark"] .bg-warning-main {
    background-color: #ffca2c !important;
}

[data-theme="dark"] .bg-danger-main {
    background-color: #dc3545 !important;
}

[data-theme="dark"] .bg-neutral-400 {
    background-color: #555 !important;
}

[data-theme="dark"] .bg-primary-100 {
    background-color: #2a3f5f !important;
}

/* Responsive Styles */
@media (max-width: 992px) {
    .navbar-header {
        padding: 10px 12px;
    }

    .navbar-search {
        max-width: 250px;
    }

    .branch-info {
        font-size: 0.8rem;
        padding: 6px 10px;
    }

    .sidebar-toggle, .sidebar-mobile-toggle {
        width: 36px;
        height: 36px;
    }

    .has-indicator, .dropdown > button > img {
        width: 36px !important;
        height: 36px !important;
    }

    .dropdown-menu-lg {
        min-width: 280px;
        max-width: 340px;
    }

    .dropdown-menu-sm {
        min-width: 180px;
    }
}

@media (max-width: 768px) {
    .navbar-search {
        max-width: 200px;
    }

    .navbar-search input {
        font-size: 0.8rem;
        padding: 6px 12px 6px 32px;
    }

    .navbar-search .icon {
        font-size: 0.9rem;
        left: 10px;
    }

    .branch-info {
        display: none;
    }

    .sidebar-toggle {
        display: none;
    }

    .sidebar-mobile-toggle {
        display: flex !important;
    }
}

@media (max-width: 576px) {
    .navbar-header .row {
        flex-wrap: nowrap;
    }

    .navbar-search {
        display: none;
    }

    .has-indicator, .dropdown > button > img {
        width: 32px !important;
        height: 32px !important;
    }

    .dropdown-menu-lg {
        min-width: 240px;
        max-width: 280px;
    }

    .dropdown-menu-sm {
        min-width: 160px;
    }

    .dropdown-menu-lg .text-lg,
    .dropdown-menu-sm .text-lg {
        font-size: 0.9rem;
    }

    .dropdown-menu-lg .text-md,
    .dropdown-menu-sm .text-md {
        font-size: 0.8rem;
    }

    .dropdown-menu-lg .text-sm,
    .dropdown-menu-sm .text-sm {
        font-size: 0.75rem;
    }

    .to-top-list li a {
        padding: 8px 12px;
        font-size: 0.8rem;
    }

    .brand-title-lg {
        display: none;
    }

    .brand-title-sm {
        display: block;
    }
}
</style>
<?php


// --- Detect third-party branch login ---
$is_third_party_branch = false;

if (
    isset($_SESSION['user_id'], $_SESSION['role'], $_SESSION['branch_id']) &&
    $_SESSION['role'] === 'branch' &&  // adjust role name if different
    is_numeric($_SESSION['branch_id'])
) {
    try {
        $stmt = $pdo->prepare("SELECT third_party FROM branches WHERE branch_id = ? LIMIT 1");
        $stmt->execute([$_SESSION['branch_id']]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row && $row['third_party'] == 1) {
            $is_third_party_branch = true;
        }
    } catch (Exception $e) {
        // ignore – fallback to default
    }
}
?>
<div class="navbar-header">
    <div class="row align-items-center justify-content-between">
        <div class="col-auto">
            <div class="d-flex align-items-center gap-3">
                <button type="button" class="sidebar-toggle" aria-label="Toggle Sidebar">
                    <iconify-icon icon="heroicons:bars-3-solid" class="icon text-2xl non-active" aria-hidden="true"></iconify-icon>
                    <iconify-icon icon="iconoir:arrow-right" class="icon text-2xl active" aria-hidden="true"></iconify-icon>
                </button>
                <button type="button" class="sidebar-mobile-toggle d-none" aria-label="Toggle Mobile Sidebar">
                    <iconify-icon icon="heroicons:bars-3-solid" class="icon" aria-hidden="true"></iconify-icon>
                </button>
                <?php if ($is_third_party_branch): ?>
    <?php
    // Fetch branch name
    $branch_name = 'Third-Party Branch';
    try {
        $stmt = $pdo->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
        $stmt->execute([$_SESSION['branch_id']]);
        $b = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($b) $branch_name = $b['branch_name'];
    } catch (Exception $e) {}
    ?>
    <span class="brand-title-lg"><?= htmlspecialchars($branch_name) ?></span>
    <span class="brand-title-sm"><?= htmlspecialchars($branch_name) ?></span>
<?php else: ?>
    <!--<span class="brand-title-lg">GS Bakery </span>-->
    <!--<span class="brand-title-sm">GSB</span>-->
<?php endif; ?>
            </div>
        </div>
        <div class="col-auto">
            <div class="d-flex align-items-center gap-3">
                <!-- Theme Toggle -->
                <button type="button" data-theme-toggle class="w-40-px h-40-px bg-neutral-200 rounded-circle d-flex justify-content-center align-items-center" aria-label="Toggle Theme">
                    <iconify-icon icon="solar:moon-linear" class="icon text-xl" aria-hidden="true"></iconify-icon>
                </button>

                <!-- Branch Info Display -->
                <?php if (isset($_SESSION['branch_id'])): ?>
                    <div class="branch-info">
                        <span class="text-primary-light fw-semibold">
                            <?php
                            $branch_id = $_SESSION['branch_id'];
                            $stmt = $pdo->prepare("SELECT branch_name, city FROM branches WHERE branch_id = ?");
                            $stmt->execute([$branch_id]);
                            $branch = $stmt->fetch(PDO::FETCH_ASSOC);

                            if ($branch) {
                                echo htmlspecialchars($branch['branch_name'] . " - " . $branch['city']);
                            } else {
                                echo "Branch Not Found";
                            }
                            ?>
                        </span>
                    </div>
                <?php endif; ?>

                <!-- Notifications Dropdown -->
                <div class="dropdown">
                    <button class="has-indicator w-40-px h-40-px bg-neutral-200 rounded-circle d-flex justify-content-center align-items-center" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="Notifications">
                        <iconify-icon icon="mage:email" class="text-primary-light text-xl" aria-hidden="true"></iconify-icon>
                        <?php if ($notification_count > 0): ?>
                            <span class="indicator bg-warning-main"></span>
                        <?php endif; ?>
                    </button>
                    <div class="dropdown-menu to-top dropdown-menu-lg p-0">
                        <div class="m-16 py-12 px-16 radius-8 bg-primary-50 mb-16 d-flex align-items-center justify-content-between gap-2">
                            <h6 class="text-lg text-primary-light fw-semibold mb-0">Notifications</h6>
                            <span class="text-primary-600 fw-semibold text-lg w-40-px h-40-px rounded-circle bg-base d-flex justify-content-center align-items-center">
                                <?php echo $notification_count; ?>
                            </span>
                        </div>
                        <div class="max-h-400-px overflow-y-auto scroll-sm pe-4">
                            <?php
                            try {
                                $query = "
                                    SELECT n.*, b.branch_name 
                                    FROM notifications n 
                                    LEFT JOIN branches b ON n.branch_id = b.branch_id 
                                    WHERE n.user_id = :user_id
                                ";
                                $params = [':user_id' => 2];

                                if ($role === 'branch' && isset($_SESSION['branch_id'])) {
                                    $query .= " AND n.branch_id = :branch_id";
                                    $params[':branch_id'] = $_SESSION['branch_id'];
                                }

                                $query .= " ORDER BY n.created_at DESC LIMIT 5";
                                $stmt = $pdo->prepare($query);
                                $stmt->execute($params);
                                $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

                                if (count($notifications) > 0) {
                                    foreach ($notifications as $notification) {
                                        $status_class = $notification['status'] == 'read' ? 'bg-neutral-50' : '';
                                        $time_ago = time_elapsed_string($notification['created_at']);
                                        ?>
                                        <a href="javascript:void(0)" class="notification-item px-24 py-12 d-flex align-items-start gap-3 mb-2 justify-content-between <?php echo $status_class; ?>" data-notification-id="<?php echo $notification['notification_id']; ?>" aria-label="View Notification">
                                            <div class="text-black hover-bg-transparent hover-text-primary d-flex align-items-center gap-3">
                                                <span class="w-40-px h-40-px rounded-circle flex-shrink-0 position-relative bg-primary-100 d-flex align-items-center justify-content-center">
                                                    <iconify-icon icon="mdi:bell-notification" class="text-primary-light" aria-hidden="true"></iconify-icon>
                                                </span>
                                                <div>
                                                    <h6 class="text-md fw-semibold mb-4"><?php echo htmlspecialchars($notification['title']); ?></h6>
                                                    <p class="mb-0 text-sm text-secondary-light text-w-100-px">
                                                        <?php echo htmlspecialchars(substr($notification['message'], 0, 50)) . '...'; ?>
                                                        <?php if ($notification['branch_name']): ?>
                                                            <br><small class="text-primary-600">Branch: <?php echo htmlspecialchars($notification['branch_name']); ?></small>
                                                        <?php endif; ?>
                                                    </p>
                                                </div>
                                            </div>
                                            <div class="d-flex flex-column align-items-end">
                                                <span class="text-sm text-secondary-light flex-shrink-0"><?php echo $time_ago; ?></span>
                                                <span class="mt-4 text-xs text-base w-16-px h-16-px d-flex justify-content-center align-items-center 
                                                    <?php echo $notification['status'] == 'pending' ? 'bg-warning-main' : 'bg-neutral-400'; ?> rounded-circle">
                                                    <?php echo $notification['status'] == 'pending' ? '!' : '✓'; ?>
                                                </span>
                                            </div>
                                        </a>
                                        <?php
                                    }
                                } else {
                                    echo '<div class="px-24 py-12 text-center text-secondary-light">No new notifications</div>';
                                }
                            } catch (PDOException $e) {
                                echo '<div class="px-24 py-12 text-center text-danger">Error loading notifications</div>';
                                error_log("Error fetching notifications: " . $e->getMessage());
                            }
                            ?>
                        </div>
                        <div class="text-center py-12 px-16">
                            <a href="notifications.php" class="text-primary-600 fw-semibold text-md">See All Notifications</a>
                        </div>
                    </div>
                </div>

                <!-- User Profile Dropdown -->
                <div class="dropdown">
                    <button class="d-flex justify-content-center align-items-center rounded-circle" type="button" data-bs-toggle="dropdown" aria-expanded="false" aria-label="User Profile">
                        <?php
                        $user_avatar = 'assets/user1.png'; // Default avatar
                        ?>
                        <img src="<?php echo $user_avatar; ?>" alt="User Avatar" class="w-40-px h-40-px object-fit-cover rounded-circle">
                    </button>
                    <div class="dropdown-menu to-top dropdown-menu-sm">
                        <div class="py-12 px-16 radius-8 bg-primary-50 mb-16 d-flex align-items-center justify-content-between gap-2">
                            <div>
                                <h6 class="text-lg text-primary-light fw-semibold mb-2">
                                    <?php echo htmlspecialchars($_SESSION['full_name'] ?? 'User'); ?>
                                </h6>
                                <span class="text-secondary-light fw-medium text-sm">
                                    <?php 
                                    if (isset($_SESSION['role'])) {
                                        echo ucfirst($_SESSION['role']);
                                        if (isset($_SESSION['branch_id'])) {
                                            $stmt = $pdo->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
                                            $stmt->execute([$_SESSION['branch_id']]);
                                            $branch = $stmt->fetch(PDO::FETCH_ASSOC);
                                            if ($branch) {
                                                echo " - " . htmlspecialchars($branch['branch_name']);
                                            }
                                        }
                                    }
                                    ?>
                                </span>
                            </div>
                            <button type="button" class="hover-text-danger" aria-label="Close Dropdown">
                                <iconify-icon icon="radix-icons:cross-1" class="icon text-xl" aria-hidden="true"></iconify-icon>
                            </button>
                        </div>
                        <ul class="to-top-list list-unstyled mb-0">
                            <li>
                                <a class="dropdown-item text-black px-0 py-8 hover-bg-transparent hover-text-primary d-flex align-items-center gap-3" href="view-profile.php">
                                    <iconify-icon icon="solar:user-linear" class="icon text-xl" aria-hidden="true"></iconify-icon> My Profile
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item text-black px-0 py-8 hover-bg-transparent hover-text-primary d-flex align-items-center gap-3" href="notifications.php">
                                    <iconify-icon icon="tabler:message-check" class="icon text-xl" aria-hidden="true"></iconify-icon> Notifications
                                    <?php if ($notification_count > 0): ?>
                                        <span class="badge bg-warning-main ms-auto"><?php echo $notification_count; ?></span>
                                    <?php endif; ?>
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item text-black px-0 py-8 hover-bg-transparent hover-text-primary d-flex align-items-center gap-3" href="settings.php">
                                    <iconify-icon icon="icon-park-outline:setting-two" class="icon text-xl" aria-hidden="true"></iconify-icon> Settings
                                </a>
                            </li>
                            <li>
                                <a class="dropdown-item text-black px-0 py-8 hover-bg-transparent hover-text-danger d-flex align-items-center gap-3" href="logout.php">
                                    <iconify-icon icon="lucide:power" class="icon text-xl" aria-hidden="true"></iconify-icon> Log Out
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// JavaScript for theme toggle
document.addEventListener('DOMContentLoaded', function () {
    const themeToggle = document.querySelector('[data-theme-toggle]');
    const html = document.documentElement;

    // Check for saved theme preference
    const savedTheme = localStorage.getItem('theme') || 'light';
    html.setAttribute('data-theme', savedTheme);
    updateThemeIcon(savedTheme);

    themeToggle.addEventListener('click', function () {
        const currentTheme = html.getAttribute('data-theme');
        const newTheme = currentTheme === 'light' ? 'dark' : 'light';
        html.setAttribute('data-theme', newTheme);
        localStorage.setItem('theme', newTheme);
        updateThemeIcon(newTheme);
    });

    function updateThemeIcon(theme) {
        const icon = themeToggle.querySelector('iconify-icon');
        icon.setAttribute('icon', theme === 'light' ? 'solar:moon-linear' : 'solar:sun-linear');
    }

    // Mark notification as read
    document.querySelectorAll('.notification-item').forEach(item => {
        item.addEventListener('click', function () {
            const notificationId = this.getAttribute('data-notification-id');
            fetch('mark_notification_read.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `notification_id=${notificationId}`
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.classList.add('bg-neutral-50');
                    this.querySelector('.bg-warning-main').classList.remove('bg-warning-main');
                    this.querySelector('.bg-warning-main, .bg-neutral-400').classList.add('bg-neutral-400');
                    this.querySelector('.text-xs').textContent = '✓';
                    const countElement = document.querySelector('.dropdown-menu-lg .bg-base');
                    let count = parseInt(countElement.textContent);
                    if (count > 0) {
                        count--;
                        countElement.textContent = count;
                        if (count === 0) {
                            document.querySelector('.indicator').style.display = 'none';
                            document.querySelector('.dropdown-menu-lg .badge')?.remove();
                        }
                    }
                }
            })
            .catch(error => console.error('Error marking notification as read:', error));
        });
    });
});
</script>
