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

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

function format_currency($amount) {
    return '₦' . number_format($amount, 2);
}
// 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

// Calculate the user's total sales for today
$username = $_SESSION['username'];
$currentDate = date('Y-m-d');
$stmt = $pdo->prepare("SELECT SUM(total) AS total_sales FROM sales WHERE username = :username AND DATE(sale_date) = :currentDate");
$stmt->execute(['username' => $username, 'currentDate' => $currentDate]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$totalSalesToday = $row['total_sales'] ?? 0;

// Calculate the total owings for the user
$owingStmt = $pdo->prepare("SELECT SUM(amount) AS total_owing FROM owings WHERE created_by = :username AND status = 'owing'");
$owingStmt->execute(['username' => $username]);
$owingRow = $owingStmt->fetch(PDO::FETCH_ASSOC);
$totalOwing = $owingRow['total_owing'] ?? 0;

// Add monthly sales calculation
$startOfMonth = date('Y-m-01');
$endOfMonth = date('Y-m-t');
$monthlyStmt = $pdo->prepare("SELECT SUM(total) AS monthly_sales FROM sales 
    WHERE username = :username 
    AND DATE(sale_date) BETWEEN :startDate AND :endDate");
$monthlyStmt->execute([
    'username' => $username, 
    'startDate' => $startOfMonth, 
    'endDate' => $endOfMonth
]);
$monthlyRow = $monthlyStmt->fetch(PDO::FETCH_ASSOC);
$monthlySales = $monthlyRow['monthly_sales'] ?? 0;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff Dashboard - <?= htmlspecialchars($pharmacy_name) ?></title>
    <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>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>

    <style>
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #34495e;
            --accent-color: #3498db;
            --success-color: #2ecc71;
            --warning-color: #f1c40f;
            --danger-color: #e74c3c;
            --light-color: #ecf0f1;
            --dark-color: #2c3e50;
            --border-color: #bdc3c7;
            --background-color: #f8f9fa;
        }

        body {
            margin: 0;
            padding: 0;
            background-color: var(--background-color);
            font-family: Arial, sans-serif;
            min-height: 100vh;
        }

        .wrapper {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            min-height: 100vh;
            background: var(--primary-color);
            position: fixed;
            left: 0;
            top: 0;
            z-index: 1000;
            transition: all 0.3s ease;
            display: flex;
            flex-direction: column;
        }

        .content {
            flex: 1;
            margin-left: 250px;  /* Match sidebar width */
            padding: 20px;
            min-height: 100vh;
            transition: margin-left 0.3s ease;
            position: relative;
            background: var(--background-color);
        }

        .sidebar-header {
            padding: 20px;
            background: var(--secondary-color);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .sidebar-header h2 {
            color: var(--accent-color);
            font-size: 1.25rem;
            margin: 0;
            font-weight: 600;
        }

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

        .menu-section a {
            padding: 12px 25px;
            color: var(--light-color);
            text-decoration: none;
            display: flex;
            align-items: center;
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }

        .menu-section a:hover, 
        .menu-section a.active {
            background: var(--secondary-color);
            border-left-color: var(--accent-color);
        }

        .menu-section a i {
            width: 20px;
            margin-right: 10px;
        }

        .sidebar-footer {
            position: absolute;
            bottom: 0;
            width: 100%;
            padding: 15px;
            background: var(--secondary-color);
        }

        .sidebar-footer a {
            color: var(--light-color);
            text-decoration: none;
            display: block;
            padding: 10px;
            transition: all 0.3s ease;
        }

        /* Dashboard Cards */
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 25px;
            position: relative;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .stat-card .icon {
            position: absolute;
            right: -10px;
            top: -10px;
            font-size: 5rem;
            opacity: 0.1;
            transform: rotate(10deg);
        }

        .stat-card .title {
            color: var(--dark-color);
            font-size: 0.9rem;
            margin-bottom: 10px;
        }

        .stat-card .value {
            font-size: 1.8rem;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .stat-card.sales {
            border-left: 4px solid var(--accent-color);
        }

        .stat-card.monthly {
            border-left: 4px solid var(--success-color);
        }

        .stat-card.owing {
            border-left: 4px solid var(--danger-color);
        }

        /* Quick Actions */
        .quick-action {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            text-decoration: none;
            color: var(--dark-color);
            transition: all 0.3s ease;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .quick-action:hover {
            transform: translateX(10px);
            background: var(--primary-color);
            color: white;
        }

        .quick-action i {
            font-size: 1.5rem;
            margin-right: 15px;
            color: var(--accent-color);
        }

        .quick-action:hover i,
        .quick-action:hover .text-muted {
            color: white !important;
        }

        /* Responsive fixes */
        @media (max-width: 768px) {
            .toggle-nav {
                display: block;
            }
            .sidebar {
                transform: translateX(-100%);
            }
            .sidebar.active {
                transform: translateX(0);
            }
            .content {
                margin-left: 0;
                width: 100%;
            }
            .content.shifted {
                margin-left: 250px;
            }
        }

        .top-bar {
            background: white;
            padding: 1rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            border-radius: 8px;
        }

        .toggle-nav {
            display: none;
            background: none;
            border: none;
            color: var(--primary-color);
            font-size: 1.5rem;
            cursor: pointer;
            padding: 0.5rem;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .user-info .user-name {
            color: var(--dark-color);
            font-weight: 500;
        }

        .user-info .role-badge {
            background: var(--accent-color);
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.8rem;
        }

        @media (max-width: 768px) {
            .toggle-nav {
                display: block;
            }
        }
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2><?= htmlspecialchars($pharmacy_name) ?></h2>
            </div>
            <div class="menu-section">
                <a href="staff_dashboard.php" class="toggle-button">
                    <span><i class="fas fa-home"></i> Dashboard</span>
                </a>
                <a href="sell_drug.php" class="toggle-button">
                    <span><i class="fas fa-cash-register"></i> Point of Sale</span>
                </a>
                <a href="owing_management.php" class="toggle-button">
                    <span><i class="fas fa-money-bill-wave"></i> Owing Management</span>
                </a>
                <a href="staff_sales.php" class="toggle-button">
                    <span><i class="fas fa-chart-line"></i> Sales History</span>
                </a>
            </div>
            <div class="sidebar-footer">
                <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </div>

        <div class="content">
            <div class="top-bar">
                <div class="d-flex align-items-center">
                    <button class="toggle-nav me-3" onclick="toggleSidebar()">
                        <i class="fas fa-bars"></i>
                    </button>
                    <h4 class="mb-0">Staff Dashboard</h4>
                </div>
                <div class="user-info">
                    <span class="role-badge">
                        <i class="fas fa-user-tag me-1"></i>
                        Staff
                    </span>
                    <span class="user-name">
                        <i class="fas fa-user-circle me-1"></i>
                        <?= htmlspecialchars($_SESSION['username']) ?>
                    </span>
                    <div class="dropdown">
                        <button class="btn btn-link text-dark p-0" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-ellipsis-v"></i>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li>
                                <a class="dropdown-item" href="logout.php">
                                    <i class="fas fa-sign-out-alt me-2"></i>
                                    Logout
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
            <div class="top-bar">
            <div class="welcome-banner">
                <h4 class="mb-2">Welcome, <?= htmlspecialchars($_SESSION['username']) ?>!</h4>
                <p class="mb-0">Today is <?= date('l, F j, Y') ?></p>
            </div>
            </div>

            <div class="stats-container">
                <div class="stat-card sales">
                    <div class="icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="title">Today's Sales</div>
                    <div class="value"><?= format_currency($totalSalesToday) ?></div>
                    <small class="text-muted">
                        <i class="fas fa-clock me-1"></i> Today's Performance
                    </small>
                </div>
                
                <div class="stat-card monthly">
                    <div class="icon">
                        <i class="fas fa-calendar-alt"></i>
                    </div>
                    <div class="title">Monthly Sales</div>
                    <div class="value"><?= format_currency($monthlySales) ?></div>
                    <small class="text-muted">
                        <i class="fas fa-calendar me-1"></i> This Month
                    </small>
                </div>
                
                <div class="stat-card owing">
                    <div class="icon">
                        <i class="fas fa-money-bill-wave"></i>
                    </div>
                    <div class="title">Outstanding Balance</div>
                    <div class="value"><?= format_currency($totalOwing) ?></div>
                    <small class="text-danger">
                        <i class="fas fa-exclamation-circle me-1"></i> Needs Attention
                    </small>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <h5 class="mb-3">Quick Actions</h5>
                    <a href="sell_drug.php" class="quick-action">
                        <i class="fas fa-cash-register"></i>
                        <div>
                            <strong>New Sale</strong>
                            <div class="small text-muted">Process a new transaction</div>
                        </div>
                    </a>
                    <a href="owing_management.php" class="quick-action">
                        <i class="fas fa-money-bill-wave"></i>
                        <div>
                            <strong>Manage Owing</strong>
                            <div class="small text-muted">Track and manage credits</div>
                        </div>
                    </a>
                    <a href="staff_sales.php" class="quick-action">
                        <i class="fas fa-chart-bar"></i>
                        <div>
                            <strong>Sales History</strong>
                            <div class="small text-muted">View your sales records</div>
                        </div>
                    </a>
                </div>
                <div class="col-md-6">
                    <h5 class="mb-3">Recent Sales</h5>
                    <div class="card">
                        <div class="list-group list-group-flush">
                            <?php 
                            $recentSalesStmt = $pdo->prepare("
                                SELECT sale_date, total, payment_method 
                                FROM sales 
                                WHERE username = :username 
                                ORDER BY sale_date DESC 
                                LIMIT 5
                            ");
                            $recentSalesStmt->execute(['username' => $username]);
                            $recentSales = $recentSalesStmt->fetchAll();

                            if (empty($recentSales)): ?>
                                <div class="text-center text-muted py-4">
                                    <i class="fas fa-receipt fa-2x mb-2"></i>
                                    <p>No recent sales found</p>
                                </div>
                            <?php else:
                                foreach ($recentSales as $sale): ?>
                                    <div class="list-group-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div>
                                                <small class="text-muted">
                                                    <i class="fas fa-clock me-1"></i>
                                                    <?= date('M j, Y g:i A', strtotime($sale['sale_date'])) ?>
                                                </small>
                                            </div>
                                            <div>
                                                <span class="fw-bold text-primary">
                                                    <?= format_currency($sale['total']) ?>
                                                </span>
                                                <small class="badge bg-light text-dark ms-2">
                                                    <?= htmlspecialchars($sale['payment_method']) ?>
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="..\libs\jquery\jquery-3.7.1.min.js"></script>
    <script src="..\libs\bootsrtap\js\bootstrap.bundle.min.js"></script>
    <script>
        function toggleSidebar() {
            const sidebar = document.querySelector('.sidebar');
            const content = document.querySelector('.content');
            const toggleBtn = document.querySelector('.toggle-nav i');
            
            sidebar.classList.toggle('active');
            content.classList.toggle('shifted');
            
            // Update toggle button icon
            if (sidebar.classList.contains('active')) {
                toggleBtn.classList.replace('fa-bars', 'fa-times');
            } else {
                toggleBtn.classList.replace('fa-times', 'fa-bars');
            }
        }

        // Initialize dropdown
        document.addEventListener('DOMContentLoaded', function() {
            var dropdownElementList = [].slice.call(document.querySelectorAll('.dropdown-toggle'))
            var dropdownList = dropdownElementList.map(function (dropdownToggleEl) {
                return new bootstrap.Dropdown(dropdownToggleEl)
            });
        });
    </script>
</body>
</html>