<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'CHIEF_PHARMACIST', 'PHARMACIST', 'PHARMACY_TECH'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get pharmacy statistics
$stats_sql = "SELECT 
                COUNT(DISTINCT pi.inventory_id) as total_items,
                SUM(pi.current_stock * pi.unit_cost) as total_inventory_value,
                COUNT(CASE WHEN pi.current_stock <= pi.reorder_level THEN 1 END) as low_stock_items,
                COUNT(CASE WHEN pi.current_stock = 0 THEN 1 END) as out_of_stock_items
              FROM pharmacy_inventory pi
              WHERE pi.is_active = 1";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();

// Today's dispensing statistics
$today_disp_sql = "SELECT 
                    COUNT(*) as total_dispensing,
                    SUM(total_amount) as total_sales,
                    COUNT(DISTINCT patient_id) as unique_patients
                   FROM pharmacy_dispensing
                   WHERE DATE(dispensing_date) = CURDATE()";
$today_disp = $conn->query($today_disp_sql)->fetch_assoc();

// Pending requisitions
$pending_req_sql = "SELECT COUNT(*) as pending_count 
                    FROM pharmacy_requisitions 
                    WHERE status = 'PENDING'";
$pending_req = $conn->query($pending_req_sql)->fetch_assoc();

// Stock alerts
$alerts_sql = "SELECT 
                psa.alert_id, psa.alert_type, psa.severity, psa.message,
                psa.created_at, pi.item_name, pi.current_stock, pi.reorder_level
               FROM pharmacy_stock_alerts psa
               INNER JOIN pharmacy_inventory pi ON psa.inventory_id = pi.inventory_id
               WHERE psa.is_acknowledged = 0
               ORDER BY psa.severity DESC, psa.created_at DESC
               LIMIT 10";
$alerts = $conn->query($alerts_sql);

// Recent dispensing
$recent_disp_sql = "SELECT 
                     pd.dispensing_id, pd.dispensing_number, pd.patient_name,
                     pd.patient_type, pd.total_amount, pd.payment_status,
                     pd.dispensing_date, u.full_name as pharmacist_name
                    FROM pharmacy_dispensing pd
                    INNER JOIN users u ON pd.dispensed_by = u.user_id
                    ORDER BY pd.dispensing_date DESC
                    LIMIT 10";
$recent_dispensing = $conn->query($recent_disp_sql);

// Low stock items
$low_stock_sql = "SELECT 
                   inventory_id, item_name, current_stock, reorder_level,
                   minimum_stock, unit_cost, selling_price
                  FROM pharmacy_inventory
                  WHERE current_stock <= reorder_level AND is_active = 1
                  ORDER BY current_stock ASC
                  LIMIT 10";
$low_stock = $conn->query($low_stock_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pharmacy Dashboard')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border-left: 4px solid;
            transition: transform 0.2s;
        }
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .stat-card.primary { border-left-color: #3b82f6; }
        .stat-card.success { border-left-color: #10b981; }
        .stat-card.warning { border-left-color: #f59e0b; }
        .stat-card.danger { border-left-color: #ef4444; }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }
        .stat-icon.primary { background: #dbeafe; color: #3b82f6; }
        .stat-icon.success { background: #d1fae5; color: #10b981; }
        .stat-icon.warning { background: #fef3c7; color: #f59e0b; }
        .stat-icon.danger { background: #fee2e2; color: #ef4444; }
        
        .alert-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .alert-badge.critical { background: #fee2e2; color: #dc2626; }
        .alert-badge.high { background: #fef3c7; color: #d97706; }
        .alert-badge.medium { background: #dbeafe; color: #2563eb; }
        .alert-badge.low { background: #e5e7eb; color: #4b5563; }
        
        .quick-action-card {
            background: white;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            border: 2px solid #e5e7eb;
            transition: all 0.2s;
            cursor: pointer;
            text-decoration: none;
            color: inherit;
            display: block;
        }
        .quick-action-card:hover {
            border-color: #3b82f6;
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .quick-action-icon {
            font-size: 2rem;
            color: #3b82f6;
            margin-bottom: 0.5rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Pharmacy Dashboard</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Pharmacy</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card primary">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <p class="text-muted mb-2">Total Items</p>
                                        <h3 class="mb-0"><?php echo number_format($stats['total_items']); ?></h3>
                                    </div>
                                    <div class="stat-icon primary">
                                        <i class="ri-medicine-bottle-line"></i>
                                    </div>
                                </div>
                                <p class="text-muted mb-0 mt-2">
                                    <small>Active inventory items</small>
                                </p>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card success">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <p class="text-muted mb-2">Inventory Value</p>
                                        <h3 class="mb-0">KES <?php echo number_format($stats['total_inventory_value'], 0); ?></h3>
                                    </div>
                                    <div class="stat-icon success">
                                        <i class="ri-money-dollar-circle-line"></i>
                                    </div>
                                </div>
                                <p class="text-muted mb-0 mt-2">
                                    <small>Total stock value</small>
                                </p>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card warning">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <p class="text-muted mb-2">Low Stock Items</p>
                                        <h3 class="mb-0"><?php echo $stats['low_stock_items']; ?></h3>
                                    </div>
                                    <div class="stat-icon warning">
                                        <i class="ri-alert-line"></i>
                                    </div>
                                </div>
                                <p class="text-muted mb-0 mt-2">
                                    <small>Requires reordering</small>
                                </p>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card danger">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <p class="text-muted mb-2">Out of Stock</p>
                                        <h3 class="mb-0"><?php echo $stats['out_of_stock_items']; ?></h3>
                                    </div>
                                    <div class="stat-icon danger">
                                        <i class="ri-close-circle-line"></i>
                                    </div>
                                </div>
                                <p class="text-muted mb-0 mt-2">
                                    <small>Urgent action needed</small>
                                </p>
                            </div>
                        </div>
                    </div>

                    <!-- Today's Activity -->
                    <div class="row mt-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card primary">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <p class="text-muted mb-2">Today's Dispensing</p>
                                        <h3 class="mb-0"><?php echo $today_disp['total_dispensing']; ?></h3>
                                    </div>
                                    <div class="stat-icon primary">
                                        <i class="ri-file-list-3-line"></i>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card success">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <p class="text-muted mb-2">Today's Sales</p>
                                        <h3 class="mb-0">KES <?php echo number_format($today_disp['total_sales'], 0); ?></h3>
                                    </div>
                                    <div class="stat-icon success">
                                        <i class="ri-hand-coin-line"></i>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card primary">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <p class="text-muted mb-2">Unique Patients</p>
                                        <h3 class="mb-0"><?php echo $today_disp['unique_patients']; ?></h3>
                                    </div>
                                    <div class="stat-icon primary">
                                        <i class="ri-user-3-line"></i>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card warning">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <p class="text-muted mb-2">Pending Requisitions</p>
                                        <h3 class="mb-0"><?php echo $pending_req['pending_count']; ?></h3>
                                    </div>
                                    <div class="stat-icon warning">
                                        <i class="ri-file-search-line"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <h5 class="mb-3">Quick Actions</h5>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <a href="pharmacy_dispense.php" class="quick-action-card">
                                <div class="quick-action-icon">
                                    <i class="ri-capsule-line"></i>
                                </div>
                                <div>Dispense</div>
                            </a>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <a href="pharmacy_prescriptions.php" class="quick-action-card">
                                <div class="quick-action-icon">
                                    <i class="ri-file-list-line"></i>
                                </div>
                                <div>Prescriptions</div>
                            </a>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <a href="pharmacy_inventory.php" class="quick-action-card">
                                <div class="quick-action-icon">
                                    <i class="ri-archive-line"></i>
                                </div>
                                <div>Inventory</div>
                            </a>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <a href="pharmacy_requisitions.php" class="quick-action-card">
                                <div class="quick-action-icon">
                                    <i class="ri-file-add-line"></i>
                                </div>
                                <div>Requisitions</div>
                            </a>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <a href="pharmacy_reports.php" class="quick-action-card">
                                <div class="quick-action-icon">
                                    <i class="ri-bar-chart-line"></i>
                                </div>
                                <div>Reports</div>
                            </a>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6 mb-3">
                            <a href="pharmacy_stock_alerts.php" class="quick-action-card">
                                <div class="quick-action-icon">
                                    <i class="ri-notification-3-line"></i>
                                </div>
                                <div>Alerts</div>
                            </a>
                        </div>
                    </div>

                    <div class="row mt-4">
                        <!-- Stock Alerts -->
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">Stock Alerts</h5>
                                    <a href="pharmacy_stock_alerts.php" class="btn btn-sm btn-soft-primary">View All</a>
                                </div>
                                <div class="card-body">
                                    <?php if ($alerts->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Item</th>
                                                        <th>Type</th>
                                                        <th>Severity</th>
                                                        <th>Stock</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while ($alert = $alerts->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($alert['item_name']); ?></td>
                                                            <td><span class="badge badge-soft-warning"><?php echo str_replace('_', ' ', $alert['alert_type']); ?></span></td>
                                                            <td>
                                                                <span class="alert-badge <?php echo strtolower($alert['severity']); ?>">
                                                                    <?php echo $alert['severity']; ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo $alert['current_stock']; ?> / <?php echo $alert['reorder_level']; ?></td>
                                                            <td>
                                                                <a href="pharmacy_inventory.php?action=reorder&id=<?php echo $alert['inventory_id']; ?>" 
                                                                   class="btn btn-sm btn-soft-success">
                                                                    <i class="ri-shopping-cart-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-4">
                                            <i class="ri-checkbox-circle-line text-success" style="font-size: 3rem;"></i>
                                            <p class="text-muted mt-2">No active alerts</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Low Stock Items -->
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">Low Stock Items</h5>
                                    <a href="pharmacy_inventory.php?filter=low_stock" class="btn btn-sm btn-soft-primary">View All</a>
                                </div>
                                <div class="card-body">
                                    <?php if ($low_stock->num_rows > 0): ?>
                                        <div class="table-responsive">
                                            <table class="table table-sm">
                                                <thead>
                                                    <tr>
                                                        <th>Item Name</th>
                                                        <th>Current</th>
                                                        <th>Reorder</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while ($item = $low_stock->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($item['item_name']); ?></td>
                                                            <td>
                                                                <span class="badge <?php echo $item['current_stock'] == 0 ? 'badge-danger' : 'badge-warning'; ?>">
                                                                    <?php echo $item['current_stock']; ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo $item['reorder_level']; ?></td>
                                                            <td>
                                                                <a href="pharmacy_requisition_create.php?item=<?php echo $item['inventory_id']; ?>" 
                                                                   class="btn btn-sm btn-soft-primary">
                                                                    Order
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    <?php else: ?>
                                        <div class="text-center py-4">
                                            <i class="ri-checkbox-circle-line text-success" style="font-size: 3rem;"></i>
                                            <p class="text-muted mt-2">All items well stocked</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Recent Dispensing -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">Recent Dispensing</h5>
                                    <a href="pharmacy_dispensing_history.php" class="btn btn-sm btn-soft-primary">View All</a>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover">
                                            <thead>
                                                <tr>
                                                    <th>Dispensing #</th>
                                                    <th>Patient</th>
                                                    <th>Type</th>
                                                    <th>Amount</th>
                                                    <th>Payment</th>
                                                    <th>Pharmacist</th>
                                                    <th>Date</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($recent_dispensing->num_rows > 0): ?>
                                                    <?php while ($disp = $recent_dispensing->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><strong><?php echo htmlspecialchars($disp['dispensing_number']); ?></strong></td>
                                                            <td><?php echo htmlspecialchars($disp['patient_name']); ?></td>
                                                            <td>
                                                                <span class="badge badge-soft-info">
                                                                    <?php echo str_replace('_', ' ', $disp['patient_type']); ?>
                                                                </span>
                                                            </td>
                                                            <td>KES <?php echo number_format($disp['total_amount'], 2); ?></td>
                                                            <td>
                                                                <?php
                                                                $badge_class = 'badge-success';
                                                                if ($disp['payment_status'] == 'PENDING') $badge_class = 'badge-warning';
                                                                elseif ($disp['payment_status'] == 'PARTIAL') $badge_class = 'badge-info';
                                                                ?>
                                                                <span class="badge <?php echo $badge_class; ?>">
                                                                    <?php echo $disp['payment_status']; ?>
                                                                </span>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($disp['pharmacist_name']); ?></td>
                                                            <td><?php echo date('d M Y, h:i A', strtotime($disp['dispensing_date'])); ?></td>
                                                            <td>
                                                                <a href="pharmacy_dispensing_view.php?id=<?php echo $disp['dispensing_id']; ?>" 
                                                                   class="btn btn-sm btn-soft-primary">
                                                                    <i class="ri-eye-line"></i>
                                                                </a>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center py-4">
                                                            <p class="text-muted">No recent dispensing records</p>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
</body>
</html>