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

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

// Check page access based on database permissions
requirePageAccess('list_procedures.php', $conn);

// Get filter parameters
$filter_status = isset($_GET['status']) ? $_GET['status'] : '';
$filter_category = isset($_GET['category']) ? $_GET['category'] : '';
$search_query = isset($_GET['search']) ? $_GET['search'] : '';

// Build query with filters
$procedures_sql = "SELECT 
    pp.*,
    pt.full_name as patient_name,
    p.patient_number,
    ept.procedure_name,
    ept.category,
    ept.subcategory,
    ept.standard_cost,
    u.full_name as performed_by_name,
    pv.visit_number,
    pv.registration_date
FROM patient_procedures pp
INNER JOIN patients p ON pp.patient_id = p.patient_id
INNER JOIN users pt ON p.user_id = pt.user_id
INNER JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
INNER JOIN users u ON pp.performed_by = u.user_id
INNER JOIN patient_visits pv ON pp.visit_id = pv.visit_id
WHERE 1=1";

$params = [];
$types = '';

if ($filter_status) {
    $procedures_sql .= " AND pp.status = ?";
    $params[] = $filter_status;
    $types .= 's';
}

if ($filter_category) {
    $procedures_sql .= " AND ept.category = ?";
    $params[] = $filter_category;
    $types .= 's';
}

if ($search_query) {
    $procedures_sql .= " AND (pt.full_name LIKE ? OR p.patient_number LIKE ? OR ept.procedure_name LIKE ? OR pp.procedure_number LIKE ?)";
    $search_param = "%{$search_query}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'ssss';
}

$procedures_sql .= " ORDER BY pp.procedure_date DESC, pp.procedure_time DESC";

$stmt = $conn->prepare($procedures_sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$procedures_result = $stmt->get_result();

// Get statistics
$stats_sql = "SELECT 
    COUNT(*) as total_procedures,
    COUNT(CASE WHEN pp.status = 'SCHEDULED' THEN 1 END) as scheduled,
    COUNT(CASE WHEN pp.status = 'COMPLETED' THEN 1 END) as completed,
    COUNT(CASE WHEN pp.status = 'IN_PROGRESS' THEN 1 END) as in_progress,
    COUNT(CASE WHEN DATE(pp.procedure_date) = CURDATE() THEN 1 END) as today_procedures,
    SUM(pp.cost) as total_revenue
FROM patient_procedures pp";
$stats = $conn->query($stats_sql)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'ENT Procedures')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .profile-header {
            background: linear-gradient(135deg, #2d7a2d 0%, #26a69a 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .info-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 500;
            font-size: 0.75rem;
            text-transform: uppercase;
        }
        
        .badge-scheduled {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .badge-in-progress {
            background: #fef3c7;
            color: #92400e;
        }
        
        .badge-completed {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-cancelled {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .badge-diagnostic {
            background: #e0e7ff;
            color: #3730a3;
        }
        
        .badge-therapeutic {
            background: #ddd6fe;
            color: #5b21b6;
        }
        
        .badge-surgical {
            background: #fce7f3;
            color: #9f1239;
        }
        
        .badge-audiological {
            background: #ccfbf1;
            color: #134e4a;
        }
        
        .badge-endoscopic {
            background: #fed7aa;
            color: #7c2d12;
        }
        
        .procedure-card {
            background: white;
            border-radius: 8px;
            padding: 1.25rem;
            margin-bottom: 1rem;
            border: 1px solid #e2e8f0;
            transition: all 0.2s;
        }
        
        .procedure-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            border-color: #2d7a2d;
        }
        
        .filter-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e2e8f0;
        }
        
        .action-btn {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            text-decoration: none;
        }
        
        .btn-primary-custom {
            background: #2d7a2d;
            color: white;
        }
        
        .btn-primary-custom:hover {
            background: #245d24;
            color: white;
        }
        
        .search-box {
            position: relative;
        }
        
        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #64748b;
        }
        
        .search-box input {
            padding-left: 2.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">ENT Procedures</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">Procedures</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-2 col-md-4">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['total_procedures']); ?></div>
                                <div class="stat-label">Total Procedures</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4">
                            <div class="stat-card">
                                <div class="stat-value text-primary"><?php echo number_format($stats['scheduled']); ?></div>
                                <div class="stat-label">Scheduled</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4">
                            <div class="stat-card">
                                <div class="stat-value text-warning"><?php echo number_format($stats['in_progress']); ?></div>
                                <div class="stat-label">In Progress</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4">
                            <div class="stat-card">
                                <div class="stat-value text-success"><?php echo number_format($stats['completed']); ?></div>
                                <div class="stat-label">Completed</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4">
                            <div class="stat-card">
                                <div class="stat-value text-info"><?php echo number_format($stats['today_procedures']); ?></div>
                                <div class="stat-label">Today</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4">
                            <div class="stat-card">
                                <div class="stat-value">KES <?php echo number_format($stats['total_revenue']); ?></div>
                                <div class="stat-label">Total Revenue</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters and Actions -->
                    <div class="filter-section">
                        <form method="GET" action="" id="filterForm">
                            <div class="row align-items-end">
                                <div class="col-md-4">
                                    <label class="form-label">Search</label>
                                    <div class="search-box">
                                        <i class="ri-search-line"></i>
                                        <input type="text" name="search" class="form-control" 
                                               placeholder="Search by patient, procedure name, or number..." 
                                               value="<?php echo htmlspecialchars($search_query); ?>">
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Status</label>
                                    <select name="status" class="form-select" onchange="document.getElementById('filterForm').submit();">
                                        <option value="">All Status</option>
                                        <option value="SCHEDULED" <?php echo $filter_status === 'SCHEDULED' ? 'selected' : ''; ?>>Scheduled</option>
                                        <option value="IN_PROGRESS" <?php echo $filter_status === 'IN_PROGRESS' ? 'selected' : ''; ?>>In Progress</option>
                                        <option value="COMPLETED" <?php echo $filter_status === 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                        <option value="CANCELLED" <?php echo $filter_status === 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Category</label>
                                    <select name="category" class="form-select" onchange="document.getElementById('filterForm').submit();">
                                        <option value="">All Categories</option>
                                        <option value="DIAGNOSTIC" <?php echo $filter_category === 'DIAGNOSTIC' ? 'selected' : ''; ?>>Diagnostic</option>
                                        <option value="THERAPEUTIC" <?php echo $filter_category === 'THERAPEUTIC' ? 'selected' : ''; ?>>Therapeutic</option>
                                        <option value="SURGICAL" <?php echo $filter_category === 'SURGICAL' ? 'selected' : ''; ?>>Surgical</option>
                                        <option value="AUDIOLOGICAL" <?php echo $filter_category === 'AUDIOLOGICAL' ? 'selected' : ''; ?>>Audiological</option>
                                        <option value="ENDOSCOPIC" <?php echo $filter_category === 'ENDOSCOPIC' ? 'selected' : ''; ?>>Endoscopic</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="btn btn-secondary w-100">
                                        <i class="ri-filter-3-line me-1"></i> Filter
                                    </button>
                                </div>
                                <div class="col-md-2">
                                    <a href="schedule_procedure.php" class="action-btn btn-primary-custom w-100">
                                        <i class="ri-add-line"></i> Schedule Procedure
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Procedures List -->
                    <div class="info-card">
                        <h5><i class="ri-activity-line me-2"></i>All Procedures (<?php echo $procedures_result->num_rows; ?>)</h5>
                        
                        <?php if ($procedures_result->num_rows > 0): ?>
                            <?php while ($procedure = $procedures_result->fetch_assoc()): ?>
                            <div class="procedure-card">
                                <div class="row align-items-center">
                                    <div class="col-md-6">
                                        <h6 class="mb-2">
                                            <a href="view_procedure.php?id=<?php echo $procedure['procedure_id']; ?>" 
                                               class="text-dark text-decoration-none">
                                                <?php echo htmlspecialchars($procedure['procedure_name']); ?>
                                            </a>
                                        </h6>
                                        <div class="text-muted small">
                                            <i class="ri-user-line me-1"></i>
                                            <strong><?php echo htmlspecialchars($procedure['patient_name']); ?></strong>
                                            (<?php echo htmlspecialchars($procedure['patient_number']); ?>)
                                        </div>
                                        <div class="text-muted small mt-1">
                                            <i class="ri-stethoscope-line me-1"></i>
                                            Dr. <?php echo htmlspecialchars($procedure['performed_by_name']); ?>
                                        </div>
                                        <div class="text-muted small mt-1">
                                            <i class="ri-file-list-3-line me-1"></i>
                                            Visit: <?php echo htmlspecialchars($procedure['visit_number']); ?>
                                        </div>
                                    </div>
                                    <div class="col-md-3">
                                        <div class="mb-2">
                                            <span class="badge badge-<?php echo strtolower($procedure['category']); ?>">
                                                <?php echo $procedure['category']; ?>
                                            </span>
                                            <?php if ($procedure['subcategory']): ?>
                                            <span class="badge bg-light text-dark ms-1">
                                                <?php echo htmlspecialchars($procedure['subcategory']); ?>
                                            </span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="text-muted small">
                                            <i class="ri-calendar-line me-1"></i>
                                            <?php echo date('d M Y', strtotime($procedure['procedure_date'])); ?>
                                            <?php if ($procedure['procedure_time']): ?>
                                                at <?php echo date('H:i', strtotime($procedure['procedure_time'])); ?>
                                            <?php endif; ?>
                                        </div>
                                        <div class="text-muted small mt-1">
                                            <i class="ri-hashtag me-1"></i>
                                            <?php echo htmlspecialchars($procedure['procedure_number']); ?>
                                        </div>
                                    </div>
                                    <div class="col-md-2 text-center">
                                        <span class="badge badge-<?php echo strtolower($procedure['status']); ?> mb-2">
                                            <?php echo str_replace('_', ' ', $procedure['status']); ?>
                                        </span>
                                        <div class="fw-bold text-success">
                                            KES <?php echo number_format($procedure['cost'], 2); ?>
                                        </div>
                                    </div>
                                    <div class="col-md-1 text-end">
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-light" type="button" data-bs-toggle="dropdown">
                                                <i class="ri-more-2-fill"></i>
                                            </button>
                                            <ul class="dropdown-menu">
                                                <li>
                                                    <a class="dropdown-item" href="view_procedure.php?id=<?php echo $procedure['procedure_id']; ?>">
                                                        <i class="ri-eye-line me-2"></i>View Details
                                                    </a>
                                                </li>
                                                <?php if ($procedure['status'] === 'SCHEDULED'): ?>
                                                <li>
                                                    <a class="dropdown-item" href="edit_procedure.php?id=<?php echo $procedure['procedure_id']; ?>">
                                                        <i class="ri-edit-line me-2"></i>Edit
                                                    </a>
                                                </li>
                                                <?php endif; ?>
                                                <li>
                                                    <a class="dropdown-item" href="patient_profile.php?id=<?php echo $procedure['patient_id']; ?>">
                                                        <i class="ri-user-line me-2"></i>View Patient
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="ri-file-list-3-line" style="font-size: 4rem; color: #cbd5e1;"></i>
                                <h5 class="mt-3 text-muted">No procedures found</h5>
                                <p class="text-muted">Try adjusting your filters or search criteria</p>
                                <a href="schedule_procedure.php" class="btn btn-primary mt-3">
                                    <i class="ri-add-line me-1"></i> Schedule New Procedure
                                </a>
                            </div>
                        <?php endif; ?>
                    </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>
<?php $conn->close(); ?>