<?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'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Handle alert acknowledgment
if (isset($_POST['acknowledge_alert'])) {
    $alert_id = (int)$_POST['alert_id'];
    $ack_sql = "UPDATE pharmacy_stock_alerts 
                SET is_acknowledged = 1, 
                    acknowledged_by = ?, 
                    acknowledged_at = NOW()
                WHERE alert_id = ?";
    $stmt = $conn->prepare($ack_sql);
    $stmt->bind_param('ii', $_SESSION['user_id'], $alert_id);
    $stmt->execute();
    
    header('Location: pharmacy_stock_alerts.php?msg=acknowledged');
    exit();
}

// Get filter
$filter_type = isset($_GET['type']) ? $_GET['type'] : '';
$filter_severity = isset($_GET['severity']) ? $_GET['severity'] : '';
$show_acknowledged = isset($_GET['show_acknowledged']) ? 1 : 0;

// Build query
$where_clauses = [];
if (!$show_acknowledged) {
    $where_clauses[] = "psa.is_acknowledged = 0";
}
if ($filter_type) {
    $where_clauses[] = "psa.alert_type = '" . $conn->real_escape_string($filter_type) . "'";
}
if ($filter_severity) {
    $where_clauses[] = "psa.severity = '" . $conn->real_escape_string($filter_severity) . "'";
}

$where_sql = count($where_clauses) > 0 ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

// Get alerts
$alerts_sql = "SELECT 
                psa.alert_id, psa.alert_type, psa.severity, psa.message,
                psa.current_stock, psa.reorder_level, psa.expiry_date,
                psa.days_to_expiry, psa.is_acknowledged, psa.created_at,
                psa.acknowledged_at, ack_user.full_name as acknowledged_by_name,
                pi.inventory_id, pi.item_code, pi.item_name, pi.category,
                pi.batch_number, pi.current_stock as actual_stock
               FROM pharmacy_stock_alerts psa
               INNER JOIN pharmacy_inventory pi ON psa.inventory_id = pi.inventory_id
               LEFT JOIN users ack_user ON psa.acknowledged_by = ack_user.user_id
               $where_sql
               ORDER BY psa.severity DESC, psa.created_at DESC";
$alerts = $conn->query($alerts_sql);

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_alerts,
                SUM(CASE WHEN severity = 'CRITICAL' THEN 1 ELSE 0 END) as critical_count,
                SUM(CASE WHEN severity = 'HIGH' THEN 1 ELSE 0 END) as high_count,
                SUM(CASE WHEN alert_type = 'OUT_OF_STOCK' THEN 1 ELSE 0 END) as out_of_stock,
                SUM(CASE WHEN alert_type = 'EXPIRED' THEN 1 ELSE 0 END) as expired_count
              FROM pharmacy_stock_alerts
              WHERE is_acknowledged = 0";
$stats = $conn->query($stats_sql)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Stock Alerts')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .alert-card {
            border-left: 4px solid;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            background: white;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .alert-card.critical { border-left-color: #dc2626; background: #fef2f2; }
        .alert-card.high { border-left-color: #f59e0b; background: #fffbeb; }
        .alert-card.medium { border-left-color: #3b82f6; background: #eff6ff; }
        .alert-card.low { border-left-color: #6b7280; background: #f9fafb; }
        .alert-card.acknowledged { opacity: 0.6; }
        
        .severity-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .severity-critical { background: #fee2e2; color: #dc2626; }
        .severity-high { background: #fef3c7; color: #d97706; }
        .severity-medium { background: #dbeafe; color: #2563eb; }
        .severity-low { background: #e5e7eb; color: #4b5563; }
    </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">Stock Alerts</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="pharmacy_dashboard.php">Pharmacy</a></li>
                                        <li class="breadcrumb-item active">Stock Alerts</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Total Active Alerts</p>
                                            <h4 class="mb-0"><?php echo $stats['total_alerts']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-danger rounded fs-3">
                                                <i class="ri-alarm-warning-line text-danger"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Critical Alerts</p>
                                            <h4 class="mb-0"><?php echo $stats['critical_count']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-danger rounded fs-3">
                                                <i class="ri-error-warning-line text-danger"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Out of Stock</p>
                                            <h4 class="mb-0"><?php echo $stats['out_of_stock']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-warning rounded fs-3">
                                                <i class="ri-close-circle-line text-warning"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <p class="text-muted mb-2">Expired Items</p>
                                            <h4 class="mb-0"><?php echo $stats['expired_count']; ?></h4>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-soft-danger rounded fs-3">
                                                <i class="ri-calendar-close-line text-danger"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" action="" class="row g-3 align-items-end">
                                        <div class="col-md-3">
                                            <label class="form-label">Alert Type</label>
                                            <select class="form-control" name="type">
                                                <option value="">All Types</option>
                                                <option value="LOW_STOCK" <?php echo $filter_type == 'LOW_STOCK' ? 'selected' : ''; ?>>Low Stock</option>
                                                <option value="OUT_OF_STOCK" <?php echo $filter_type == 'OUT_OF_STOCK' ? 'selected' : ''; ?>>Out of Stock</option>
                                                <option value="NEAR_EXPIRY" <?php echo $filter_type == 'NEAR_EXPIRY' ? 'selected' : ''; ?>>Near Expiry</option>
                                                <option value="EXPIRED" <?php echo $filter_type == 'EXPIRED' ? 'selected' : ''; ?>>Expired</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Severity</label>
                                            <select class="form-control" name="severity">
                                                <option value="">All Severities</option>
                                                <option value="CRITICAL" <?php echo $filter_severity == 'CRITICAL' ? 'selected' : ''; ?>>Critical</option>
                                                <option value="HIGH" <?php echo $filter_severity == 'HIGH' ? 'selected' : ''; ?>>High</option>
                                                <option value="MEDIUM" <?php echo $filter_severity == 'MEDIUM' ? 'selected' : ''; ?>>Medium</option>
                                                <option value="LOW" <?php echo $filter_severity == 'LOW' ? 'selected' : ''; ?>>Low</option>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="show_acknowledged" 
                                                       id="show_acknowledged" <?php echo $show_acknowledged ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="show_acknowledged">
                                                    Show Acknowledged Alerts
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <button type="submit" class="btn btn-primary w-100">
                                                <i class="ri-filter-line me-1"></i>Apply Filters
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alerts List -->
                    <div class="row">
                        <div class="col-12">
                            <?php if ($alerts->num_rows > 0): ?>
                                <?php while ($alert = $alerts->fetch_assoc()): ?>
                                    <div class="alert-card <?php echo strtolower($alert['severity']) . ($alert['is_acknowledged'] ? ' acknowledged' : ''); ?>">
                                        <div class="row align-items-center">
                                            <div class="col-md-1 text-center">
                                                <i class="ri-medicine-bottle-line fs-2 <?php echo $alert['severity'] == 'CRITICAL' ? 'text-danger' : 'text-warning'; ?>"></i>
                                            </div>
                                            <div class="col-md-3">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($alert['item_name']); ?></h6>
                                                <p class="text-muted mb-0"><small><?php echo htmlspecialchars($alert['item_code']); ?></small></p>
                                            </div>
                                            <div class="col-md-4">
                                                <p class="mb-1"><?php echo htmlspecialchars($alert['message']); ?></p>
                                                <div class="d-flex gap-2 flex-wrap">
                                                    <?php if ($alert['alert_type'] == 'LOW_STOCK' || $alert['alert_type'] == 'OUT_OF_STOCK'): ?>
                                                        <span class="badge badge-soft-info">Stock: <?php echo $alert['actual_stock']; ?></span>
                                                        <span class="badge badge-soft-warning">Reorder: <?php echo $alert['reorder_level']; ?></span>
                                                    <?php endif; ?>
                                                    <?php if ($alert['expiry_date']): ?>
                                                        <span class="badge <?php echo $alert['alert_type'] == 'EXPIRED' ? 'badge-danger' : 'badge-soft-warning'; ?>">
                                                            Expiry: <?php echo date('d M Y', strtotime($alert['expiry_date'])); ?>
                                                        </span>
                                                    <?php endif; ?>
                                                    <span class="severity-badge severity-<?php echo strtolower($alert['severity']); ?>">
                                                        <?php echo $alert['severity']; ?>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-md-2">
                                                <small class="text-muted">
                                                    <?php echo date('d M Y, h:i A', strtotime($alert['created_at'])); ?>
                                                </small>
                                                <?php if ($alert['is_acknowledged']): ?>
                                                    <br><span class="badge badge-soft-success">Acknowledged</span>
                                                    <br><small class="text-muted">By: <?php echo htmlspecialchars($alert['acknowledged_by_name']); ?></small>
                                                <?php endif; ?>
                                            </div>
                                            <div class="col-md-2 text-end">
                                                <?php if (!$alert['is_acknowledged']): ?>
                                                    <form method="POST" style="display: inline;">
                                                        <input type="hidden" name="alert_id" value="<?php echo $alert['alert_id']; ?>">
                                                        <button type="submit" name="acknowledge_alert" class="btn btn-sm btn-soft-success mb-1 w-100">
                                                            <i class="ri-check-line me-1"></i>Acknowledge
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                                <a href="pharmacy_inventory.php?id=<?php echo $alert['inventory_id']; ?>" 
                                                   class="btn btn-sm btn-soft-primary w-100">
                                                    <i class="ri-eye-line me-1"></i>View Item
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="card">
                                    <div class="card-body text-center py-5">
                                        <i class="ri-checkbox-circle-line text-success" style="font-size: 4rem;"></i>
                                        <h5 class="mt-3">No Active Alerts</h5>
                                        <p class="text-muted">All items are properly stocked and within expiry limits.</p>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>

                </div>
            </div>

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

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