<?php
session_start();
if (!isset($_SESSION['username']) || $_SESSION['role'] != 'admin') {
    header("Location: login.php");
    exit();
}

// Include the database configuration file
include('../config/db.php');

// Fetch today's profit, total profit, today's sales, and total sales using prepared statements for better security
$query = "SELECT SUM(profit) AS today_profit, SUM(total) AS today_sales FROM sales WHERE DATE(sale_date) = CURDATE()";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$today_profit = $result['today_profit'] ?? 0;
$today_sales = $result['today_sales'] ?? 0;

// Fetch total profit
$query = "SELECT SUM(profit) AS total_profit FROM sales";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$total_profit = $result['total_profit'] ?? 0;

// Fetch total sales amount
$query = "SELECT SUM(total) AS total_sales_amount FROM sales";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$total_sales_amount = $result['total_sales_amount'] ?? 0;

// Fetch recent sales, limiting to 5 for display along with the remaining quantity
$query = "SELECT sales.*, drugs.quantity AS remaining_quantity 
          FROM sales 
          LEFT JOIN drugs ON sales.drug_name = drugs.drug_name 
          ORDER BY sale_date DESC LIMIT 5";
$stmt = $pdo->prepare($query);
$stmt->execute();
$recent_sales = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch recent sales, limiting to 5 for display
$query = "SELECT * FROM sales ORDER BY sale_date DESC LIMIT 5";
$stmt = $pdo->prepare($query);
$stmt->execute();
$recent_sales = $stmt->fetchAll(PDO::FETCH_ASSOC);


   // Query to fetch recent sales and the remaining quantity of the drug from the 'drugs' table
$query = "SELECT sales.*, drugs.quantity AS remaining_quantity
FROM sales
LEFT JOIN drugs ON sales.drug_name = drugs.drug_name
ORDER BY sale_date DESC LIMIT 7";
$stmt = $pdo->prepare($query);
$stmt->execute();
$recent_sales = $stmt->fetchAll(PDO::FETCH_ASSOC);


// Replace the existing notification query with:
$query = "SELECT notifications_enabled FROM settings LIMIT 1";
$stmt = $pdo->prepare($query);
$stmt->execute();
$settings = $stmt->fetch(PDO::FETCH_ASSOC);

$notifications = [];
$notification_count = 0;

if ($settings['notifications_enabled']) {
    // Your existing notification query
    $query = "SELECT drug_name, quantity, expiration_date 
              FROM drugs 
              WHERE quantity < 3 
              OR expiration_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 MONTH)";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $notification_count = count($notifications);
}

// Fetch pharmacy name from the settings table
$query = "SELECT pharmacy_name FROM settings LIMIT 1"; // Assuming only one entry
$stmt = $pdo->prepare($query);
$stmt->execute();
$setting = $stmt->fetch(PDO::FETCH_ASSOC);
$pharmacy_name = $setting['pharmacy_name'] ?? 'Default Pharmacy Name'; // Fallback to a default if not found


$query = "SELECT username, SUM(total) AS total_sales FROM sales GROUP BY username ORDER BY total_sales DESC LIMIT 3";
$stmt = $pdo->prepare($query);
$stmt->execute();
$top_users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// ... (rest of your PHP code)
// Function to format currency
function format_currency($amount) {
    return '₦' . number_format($amount, 2);
}

// Render the recent sales and remaining quantity
function render_recent_sales($sales) {
    foreach ($sales as $sale) {
        echo "<tr>
                <td>" . htmlspecialchars($sale['drug_name']) . "</td>
                <td>" . htmlspecialchars($sale['quantity']) . "</td>
                <td>" . htmlspecialchars($sale['remaining_quantity']) . "</td> <!-- Show remaining quantity here -->
                <td>" . format_currency($sale['total']) . "</td>
                <td>" . htmlspecialchars($sale['sale_date']) . "</td>
                
              </tr>";
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <!-- Bootstrap 5 CSS -->

    <link rel="stylesheet" href="..\libs\bootsrtap2\css\bootstrap.min.css">
    <link rel="stylesheet" href="..\libs\fontawesome\css\all.min.css">
    <script src="..\libs\bootsrtap2\js\bootstrap.bundle.min.js"></script>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <style>
        h2, h5 {
    font-size: 1.2rem; /* Smaller font sizes */
}
p {
    font-size: 0.9rem;
}
        body {
            background-color: #f5f6fa;
            font-family: Arial, sans-serif;
            overflow-x: hidden;
            font-size: 14px
        }
        .notification-container {
            margin-top: 20px;
        }
        .notification {
            background-color: #ffcccc;
            color: #e74c3c;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            font-size: 12px;
            font-weight: bold;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
        }
        .notification.expiring {
            background-color: #dc3545;
            color: #fff;
        }
        .notification.low-stock {
            background-color: #ffc107;
            color: #fff;
        }
        .notification i {
            margin-right: 10px;
            font-size: 20px;
        }
        .sidebar {
            width: 230px;
            position: fixed;
            height: 100vh;
            background: #2c3e50;
            color: #ecf0f1;
            transition: all 0.3s ease;
            overflow-y: auto;
            scrollbar-width: thin;
            scrollbar-color: #34495e transparent;
        }

        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .sidebar::-webkit-scrollbar-track {
            background: transparent;
        }

        .sidebar::-webkit-scrollbar-thumb {
            background-color: #34495e;
            border-radius: 3px;
        }

        .sidebar-header {
            padding: 20px;
            background: #243342;
            border-bottom: 1px solid #34495e;
        }

        .sidebar-header h2 {
            font-size: 1.2rem;
            margin: 0;
            color: #3498db;
            font-weight: 600;
        }

        .menu-section {
            padding: 10px 0;
        }

        .toggle-button {
            padding: 12px 15px;
            color: #ecf0f1;
            text-decoration: none;
            display: flex;
            align-items: center;
            border-left: 4px solid transparent;
            transition: all 0.3s ease;
        }

        .toggle-button:hover {
            background: #34495e;
            border-left-color: #3498db;
            color: #3498db;
        }

        .toggle-button span {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .toggle-button i.fa-chevron-down {
            transition: transform 0.3s ease;
        }

        .toggle-button[aria-expanded="true"] i.fa-chevron-down {
            transform: rotate(-180deg);
        }

        .collapse {
            background: #243342;
        }

        .collapse a {
            padding: 10px 15px 10px 50px;
            color: #bdc3c7;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s ease;
            font-size: 0.9rem;
        }

        .collapse a:hover {
            background: #2c3e50;
            color: #3498db;
        }

        .collapse a i {
            width: 20px;
            text-align: center;
        }

        .sidebar-footer {
            padding: 15px;
            background: #243342;
            border-top: 1px solid #34495e;
            position: sticky;
            bottom: 0;
        }

        .sidebar-footer a {
            display: flex;
            align-items: center;
            gap: 10px;
            color: #bdc3c7;
            padding: 10px;
            text-decoration: none;
            transition: all 0.3s ease;
        }

        .sidebar-footer a:hover {
            color: #3498db;
            background: #2c3e50;
            border-radius: 5px;
        }

        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                transform: translateX(-100%);
            }
            
            .sidebar.active {
                transform: translateX(0);
            }
        }
        .content {
            margin-left: 230px;
            padding: 20px;
            transition: margin-left 0.3s ease;
        }
        .top-bar {
            background-color: #ffffff;
            padding: 15px;
            display: flex;
            
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .ftop-bar {
    background-color: #ffffff;
    padding: 15px;
    
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    margin-bottom: 1px;

    position: sticky; /* Makes the element sticky */
    top: 0; /* Sticks at the top when scrolling */
    z-index: 1000; /* Ensures it stays above other elements */
}

        .dashboard-cards {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            gap: 20px;
            margin-top: 20px;
        }
        .dashboard-card {
            flex: 1 1 200px;
            padding: 15px;
            border-radius: 10px;
            color: #fff;
            text-align: center;
            transition: transform 0.3s ease;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        .dashboard-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }
        .today-sales-card { background-color: #2980b9; }
        .profit-today-card { background-color: #27ae60; }
        .total-sales-card { background-color: #3498db; }
        .total-profit-card { background-color: #2ecc71; }
        .dashboard-card h5 {
            font-size: 18px;
            margin-bottom: 20px;
        }
        .dashboard-card p {
            font-size: 30px; /* Increased font size for visibility */
            margin: 0;
            font-weight: bold;
        }
        .recent-sales {
            margin-top: 40px;
        }
        .table th, .table td {
            color: #2c3e50;
        }
        .footer {
            background-color: #2c3e50;
            color: #fff;
            padding: 20px;
            text-align: center;
            position: relative;
            bottom: 0;
            width: 100%;
        }
        .close_nav{
            display:none;
        }
        .show_nav{
            display:none;
        }
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            .sidebar.active {
                transform: translateX(0);
            }
            .content {
                margin-left: 0;
            }
            .close_nav{
                display:inline-block;
            }
            .show_nav{
            display:inline-block;
        }
        }
    </style>
</head>
<body>

<div class="ftop-bar">
<button class="btn btn-primary m-2 show_nav "  onclick="toggleSidebar(this)" style="background-color: #3498db; border: none;">
        <i class="fas fa-bars"></i>
        </button>
        
       <h2><?php echo htmlspecialchars($pharmacy_name); ?></h2>

        <div class="notification-toggle" style="position: relative;">
    <button id="toggleNotification" class="btn p-0 border-0" style="background-color: transparent;">
        <i class="fas fa-bell" style="color: orange; font-size: 1.5rem;"></i>
        <?php if ($notification_count > 0) { ?>
            <span class="badge position-absolute top-0 start-100 translate-middle bg-danger text-white">
                <?php echo $notification_count; ?>
            </span>
        <?php } ?>
    </button>
</div>

        
<div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false">
         <?php echo htmlspecialchars($_SESSION['username']); ?>
    </button>
    <ul class="dropdown-menu" aria-labelledby="userMenu">
        <li><a class="dropdown-item" href="settings.php">Settings</a></li>
        <li><a class="dropdown-item" href="log_history.php">Log History</a></li>
        <li><a class="dropdown-item" href="logout.php">Logout</a></li>
        <li> <button type="button" class="btn btn-danger" onclick="logoutAllUsers()">Log Out All Users</button></li>

    </ul>
</div>

    </div>

    <div class="sidebar">
    <div class="sidebar-header">
        <h2>Store Management</h2>
    </div>

    <div class="menu-section">
        <!-- Sales Section -->
        <a class="toggle-button" data-bs-toggle="collapse" href="#sellGroup" role="button">
            <span>
                <i class="fas fa-cash-register"></i>
                Sales
            </span>
            <i class="fas fa-chevron-down ms-auto"></i>
        </a>
        <div class="collapse" id="sellGroup">
            <a href="sell_drug.php"><i class="fas fa-cart-plus"></i>New Sale</a>
            <a href="sales.php"><i class="fas fa-list"></i>Sales History</a>
        </div>

        <!-- Inventory Section -->
        <a class="toggle-button d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#inventoryGroup" role="button">
            <span><i class="fas fa-box"></i> Inventory</span>
            <i class="fas fa-chevron-down"></i>
        </a>
        <div class="collapse" id="inventoryGroup">
            <a href="add_drug.php" class="ms-4"><i class="fas fa-plus"></i> Add Product</a>
            <a href="manage_drugs.php" class="ms-4"><i class="fas fa-boxes"></i> View Products</a>
            <a href="stock_report.php" class="ms-4"><i class="fas fa-clipboard-list"></i> Stock Summary</a>
        </div>

        <!-- People Management Section -->
        <a class="toggle-button d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#peopleGroup" role="button">
            <span><i class="fas fa-users"></i> People</span>
            <i class="fas fa-chevron-down"></i>
        </a>
        <div class="collapse" id="peopleGroup">
            <a href="manage_customers.php" class="ms-4"><i class="fas fa-user-friends"></i> Customers</a>
            <a href="manage_users.php" class="ms-4"><i class="fas fa-user-cog"></i> Staff</a>
            <a href="staff_report.php" class="ms-4"><i class="fas fa-chart-line"></i> Staff Performance</a>
        </div>

        <!-- Supplier Management -->
        <a class="toggle-button d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#supplierGroup" role="button">
            <span><i class="fas fa-truck"></i> Suppliers</span>
            <i class="fas fa-chevron-down"></i>
        </a>
        <div class="collapse" id="supplierGroup">
            <a href="add_supplier.php" class="ms-4"><i class="fas fa-plus"></i> Add Supplier</a>
            <a href="suppliers_list.php" class="ms-4"><i class="fas fa-list"></i> View Suppliers</a>
            <a href="add_supply.php" class="ms-4"><i class="fas fa-truck-loading"></i> Record Supply</a>
            <a href="view_supply.php" class="ms-4"><i class="fas fa-history"></i> Supply History</a>
        </div>

        <!-- Finance Section -->
        <a class="toggle-button d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#financeGroup" role="button">
            <span><i class="fas fa-money-bill-wave"></i> Finance</span>
            <i class="fas fa-chevron-down"></i>
        </a>
        <div class="collapse" id="financeGroup">
            <a href="manage_espenses.php" class="ms-4"><i class="fas fa-receipt"></i> Expenses</a>
            <a href="owing_management.php" class="ms-4"><i class="fas fa-hand-holding-usd"></i> Credit Sales</a>
            <a href="finance_report.php" class="ms-4"><i class="fas fa-chart-pie"></i> Financial Reports</a>
        </div>

        <!-- Reports Section -->
        <a class="toggle-button d-flex justify-content-between align-items-center" data-bs-toggle="collapse" href="#reportsGroup" role="button">
            <span><i class="fas fa-chart-bar"></i> Reports</span>
            <i class="fas fa-chevron-down"></i>
        </a>
        <div class="collapse" id="reportsGroup">
            <a href="reports.php" class="ms-4"><i class="fas fa-chart-line"></i> Sales Reports</a>
            <a href="customers_report.php" class="ms-4"><i class="fas fa-user-chart"></i> Customer Reports</a>
            <a href="all_transactions.php" class="ms-4"><i class="fas fa-history"></i> All Transactions</a>
        </div>

        <div class="sidebar-footer">
            <a href="settings.php"><i class="fas fa-cog"></i> Settings</a>
            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </div>
    </div>
</div>


<div class="content">
    <div class="top-bar">
        <h2>Store Dashboard</h2>
        <div>
            
        </div>
    </div>

     <!-- Toggle Notification Icon with Counter -->
     <div class="notification-toggle" style="position: relative;">
        <button id="toggleNotification" class="btn btn-warning" >
           <!-- <i class="fas fa-bell"></i> -->
            <strong>Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>!</strong>
        </button>
    </div>

    <div class="modal fade" id="notificationModal" tabindex="-1" aria-labelledby="notificationModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="notificationModalLabel">Notifications</h5>
                <button type="button" class="btn-close close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
                <div class="modal-body">
                    <?php if (!empty($notifications)) { 
                        foreach ($notifications as $notification) {
                            // Check if it's a low stock or expiring drug
                            $class = '';
                            $icon = '';
                            $message = '';

                            if ($notification['quantity'] < 10) {
                                $class = 'low-stock';
                                $icon = 'fas fa-exclamation-circle'; // Icon for low stock
                                $message = "Low stock for drug: " . htmlspecialchars($notification['drug_name']);
                            }
                            if (strtotime($notification['expiration_date']) <= strtotime('+3 months')) {
                                $class = 'expiring';
                                $icon = 'fas fa-calendar-exclamation'; // Icon for expiring drugs
                                $message = "Drug: " . htmlspecialchars($notification['drug_name']) . " is expiring soon on " . htmlspecialchars($notification['expiration_date']);
                            }

                            echo "<div class='notification $class'>
                                    <i class='$icon'></i>
                                    $message
                                  </div>";
                        }
                    } else {
                        echo "<p>No notifications at the moment.</p>";
                    } ?>
                </div>
            </div>
        </div>
    </div>
    <div class="dashboard-cards">
        <div class="dashboard-card today-sales-card">
            <h5>Today's Sales</h5>
            <p><?php echo format_currency($today_sales); ?></p>
        </div>
        <div class="dashboard-card profit-today-card">
            <h5>Today's Profit</h5>
            <p><?php echo format_currency($today_profit); ?></p>
        </div>
        <!-- <div class="dashboard-card total-sales-card">
            <h5>Total Sales</h5>
            <p><?php echo format_currency($total_sales_amount); ?></p>
        </div>
        <div class="dashboard-card total-profit-card">
            <h5>Total Profit</h5>
            <p><?php echo format_currency($total_profit); ?></p>
        </div> -->
    </div>

    <div class="top-users mt-5">
    <h3>Top 3 Staff with Highest Sales</h3>
    <section class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Username</th>
                    <th>Total Sales Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($top_users as $user): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($user['username']); ?></td>
                        <td><?php echo format_currency($user['total_sales']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </section>
</div>


    <div class="recent-sales">
        <h3>Recent Sales</h3>
        <section class='table-responsive'>
        <table  class="table table-bordered">
            <thead>
                <tr>
                 
                    <th>Product Name</th>
                    <th>Quantity</th>
                    <th>Stock Level</th>
                    <th>Total</th>
                    <th>Sale Date</th>
                </tr>
            </thead>
            <tbody>
                <?php render_recent_sales($recent_sales); ?>
            </tbody>
        </table>
        </section>
    </div>

    <div class="footer">
        &copy; <?php echo date("Y"); ?> <?php echo htmlspecialchars($pharmacy_name); ?>. All rights reserved.
    </div>
</div>

<script>

    

    a = 0;
    function toggleSidebar(x) {
       if(a  == 0){
        document.querySelector('.sidebar').classList.toggle('active');
        document.querySelector('.content').classList.toggle('active');
        x.innerHTML = '<i class="fa-solid fa-xmark"></i>'
        x.style.background='red'
        
        a = 1
    }else{
        document.querySelector('.sidebar').classList.toggle('active');
        document.querySelector('.content').classList.toggle('active');
        x.innerHTML = '<i class="fas fa-bars"></i>'
        x.style.background='blue'
        a = 0
       }
    }
    
    window.onload = function() {
            const notificationCount = <?php echo $notification_count; ?>;
            if (notificationCount > 0) {
                var modal = new bootstrap.Modal(document.getElementById('notificationModal'));
                modal.show();
            }
        };
    
     // Handle opening the notification modal when the toggle button is clicked
     document.getElementById('toggleNotification').addEventListener('click', function() {
        var modal = new bootstrap.Modal(document.getElementById('notificationModal'));
        modal.show();
    });

    // Handle when the modal is closed (either through the close button or outside the modal)
    var modalElement = document.getElementById('notificationModal');

    modalElement.addEventListener('hidden.bs.modal', function () {
        // Reset any state after closing the modal (this will execute when the modal is fully closed)

        // Example: Reset the notification badge count (you can adjust based on your needs)
        var notificationCount = <?php echo $notification_count; ?>;  // Get your notification count from PHP
        
        if (notificationCount === 0) {
            // Optionally hide the badge if no notifications are available
            document.querySelector('.notification-toggle .badge').style.display = 'none';
        } else {
            // Show the notification badge if there are notifications
            document.querySelector('.notification-toggle .badge').style.display = 'inline-block';
        }

        // You can also perform other actions to reset UI elements, like re-enabling buttons or other controls
    });

    // Ensure the modal works smoothly when the close button is clicked
    document.querySelector('.close').addEventListener('click', function() {
        // Close the modal and handle any necessary state reset
        var modal = new bootstrap.Modal(document.getElementById('notificationModal'));
        modal.hide();

        // Any additional actions to perform after closing (e.g., resetting UI elements or re-enabling components)
        var notificationCount = <?php echo $notification_count; ?>;
        if (notificationCount === 0) {
            document.querySelector('.notification-toggle .badge').style.display = 'none';
        }
    });

    <!-- JavaScript to Toggle Notifications -->

    document.getElementById("toggleNotification").addEventListener("click", function() {
        var notificationContainer = document.getElementById("notificationContainer");
        if (notificationContainer.style.display === "none" || notificationContainer.style.display === "") {
            notificationContainer.style.display = "block";
        } else {
            notificationContainer.style.display = "none";
        }
    });
    function logoutAllUsers() {
    if (confirm("Are you sure you want to log out all users?")) {
        window.location.href = "logout_all.php";
    }
}


</script>
</body>
</html>
