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

$page_title = "Equipment Management";

// Fetch all equipment
$query = "SELECT * FROM lab_equipment ORDER BY department, equipment_name";
$result = mysqli_query($conn, $query);

// Get statistics
$stats_query = "SELECT 
                COUNT(*) as total_equipment,
                SUM(CASE WHEN status = 'OPERATIONAL' THEN 1 ELSE 0 END) as operational,
                SUM(CASE WHEN status = 'UNDER_MAINTENANCE' THEN 1 ELSE 0 END) as maintenance,
                SUM(CASE WHEN status = 'OUT_OF_SERVICE' THEN 1 ELSE 0 END) as out_of_service,
                COUNT(DISTINCT department) as total_departments
                FROM lab_equipment";
$stats_result = mysqli_query($conn, $stats_query);
$stats = mysqli_fetch_assoc($stats_result);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .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;
            border-left: 4px solid #667eea;
            transition: transform 0.2s;
            margin-bottom: 1.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
            text-transform: uppercase;
        }
        
        .equipment-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            border-left: 4px solid #10b981;
            transition: all 0.3s;
        }
        
        .equipment-card:hover {
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
        }
        
        .equipment-card.maintenance {
            border-left-color: #f59e0b;
        }
        
        .equipment-card.out-of-service {
            border-left-color: #ef4444;
            opacity: 0.7;
        }
        
        .status-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
            text-transform: uppercase;
        }
        
        .status-operational {
            background: #d1fae5;
            color: #065f46;
        }
        
        .status-maintenance {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-out-of-service {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .equipment-info {
            display: flex;
            gap: 1.5rem;
            margin: 1rem 0;
            flex-wrap: wrap;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .info-item i {
            color: #667eea;
        }
        
        .filter-section {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            margin-bottom: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
    </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">Equipment Management</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">Laboratory</li>
                                        <li class="breadcrumb-item active">Equipment</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-tools-line me-2"></i>Equipment Management</h4>
                                <p class="mb-0">Manage laboratory and testing equipment inventory</p>
                                </div>
                            <button class="btn btn-light btn-lg" onclick="showAddEquipmentModal()">
                                <i class="ri-add-line me-2"></i>Add New Equipment
                            </button>
                        </div>
                    </div>
                    <!-- Statistics -->
                <div class="row">
                    <div class="col-lg-3 col-md-6">
                        <div class="stat-card">
                            <div class="stat-value"><?php echo $stats['total_equipment']; ?></div>
                            <div class="stat-label">Total Equipment</div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="stat-card">
                            <div class="stat-value text-success"><?php echo $stats['operational']; ?></div>
                            <div class="stat-label">Operational</div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="stat-card">
                            <div class="stat-value text-warning"><?php echo $stats['maintenance']; ?></div>
                            <div class="stat-label">Under Maintenance</div>
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="stat-card">
                            <div class="stat-value text-danger"><?php echo $stats['out_of_service']; ?></div>
                            <div class="stat-label">Out of Service</div>
                        </div>
                    </div>
                </div>

                <!-- Filter Section -->
                <div class="filter-section">
                    <div class="row">
                        <div class="col-md-4 mb-3 mb-md-0">
                            <select class="form-select" id="statusFilter">
                                <option value="">All Status</option>
                                <option value="OPERATIONAL">Operational</option>
                                <option value="UNDER_MAINTENANCE">Under Maintenance</option>
                                <option value="OUT_OF_SERVICE">Out of Service</option>
                            </select>
                        </div>
                        <div class="col-md-4 mb-3 mb-md-0">
                            <select class="form-select" id="departmentFilter">
                                <option value="">All Departments</option>
                                <option value="AUDIOLOGY">Audiology</option>
                                <option value="LABORATORY">Laboratory</option>
                                <option value="RADIOLOGY">Radiology</option>
                                <option value="ENDOSCOPY">Endoscopy</option>
                                <option value="ALLERGY">Allergy</option>
                                <option value="SLEEP_STUDY">Sleep Study</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <button class="btn btn-secondary w-100" onclick="resetFilters()">
                                <i class="ri-refresh-line me-2"></i>Reset Filters
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Equipment List -->
                <div id="equipmentList">
                    <?php 
                    $current_dept = '';
                    while($equipment = mysqli_fetch_assoc($result)): 
                        if($current_dept != $equipment['department']) {
                            if($current_dept != '') echo '</div>';
                            $current_dept = $equipment['department'];
                            echo '<h5 class="mt-4 mb-3" style="color: #1e293b; font-weight: 600;">' . str_replace('_', ' ', $current_dept) . ' Equipment</h5>';
                            echo '<div class="department-group" data-department="' . $current_dept . '">';
                        }
                        
                        $status_class = '';
                        $status_badge_class = 'status-operational';
                        if($equipment['status'] == 'UNDER_MAINTENANCE') {
                            $status_class = 'maintenance';
                            $status_badge_class = 'status-maintenance';
                        } elseif($equipment['status'] == 'OUT_OF_SERVICE') {
                            $status_class = 'out-of-service';
                            $status_badge_class = 'status-out-of-service';
                        }
                    ?>
                    
                    <div class="equipment-card <?php echo $status_class; ?>" data-status="<?php echo $equipment['status']; ?>">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <div class="d-flex align-items-center gap-3 mb-2 flex-wrap">
                                    <h5 class="mb-0"><?php echo htmlspecialchars($equipment['equipment_name']); ?></h5>
                                    <span class="test-code"><?php echo htmlspecialchars($equipment['equipment_code']); ?></span>
                                    <span class="status-badge <?php echo $status_badge_class; ?>">
                                        <?php echo str_replace('_', ' ', $equipment['status']); ?>
                                    </span>
                                </div>
                                
                                <?php if($equipment['description']): ?>
                                <p class="text-muted mb-2" style="font-size: 0.875rem;">
                                    <?php echo htmlspecialchars($equipment['description']); ?>
                                </p>
                                <?php endif; ?>
                                
                                <div class="equipment-info">
                                    <?php if($equipment['manufacturer']): ?>
                                    <div class="info-item">
                                        <i class="ri-building-line"></i>
                                        <?php echo htmlspecialchars($equipment['manufacturer']); ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if($equipment['model_number']): ?>
                                    <div class="info-item">
                                        <i class="ri-barcode-line"></i>
                                        Model: <?php echo htmlspecialchars($equipment['model_number']); ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if($equipment['serial_number']): ?>
                                    <div class="info-item">
                                        <i class="ri-hashtag"></i>
                                        S/N: <?php echo htmlspecialchars($equipment['serial_number']); ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if($equipment['purchase_date']): ?>
                                    <div class="info-item">
                                        <i class="ri-calendar-line"></i>
                                        Purchased: <?php echo date('M d, Y', strtotime($equipment['purchase_date'])); ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if($equipment['last_maintenance_date']): ?>
                                    <div class="info-item">
                                        <i class="ri-tools-line"></i>
                                        Last Service: <?php echo date('M d, Y', strtotime($equipment['last_maintenance_date'])); ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <?php if($equipment['location']): ?>
                                <div class="mt-2">
                                    <small class="text-muted">
                                        <i class="ri-map-pin-line me-1"></i>
                                        Location: <?php echo htmlspecialchars($equipment['location']); ?>
                                    </small>
                                </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="d-flex flex-column gap-2" style="min-width: 120px;">
                                <button onclick="editEquipment(<?php echo $equipment['equipment_id']; ?>)" 
                                        class="btn btn-sm" style="background: #667eea; color: white;">
                                    <i class="ri-edit-line"></i> Edit
                                </button>
                                <button onclick="showMaintenanceLog(<?php echo $equipment['equipment_id']; ?>)" 
                                        class="btn btn-outline-secondary btn-sm">
                                    <i class="ri-history-line"></i> History
                                </button>
                                <?php if($equipment['status'] == 'OPERATIONAL'): ?>
                                <button onclick="markMaintenance(<?php echo $equipment['equipment_id']; ?>)" 
                                        class="btn btn-outline-warning btn-sm">
                                    <i class="ri-tools-line"></i> Maintenance
                                </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <?php endwhile; ?>
                    <?php if($current_dept != '') echo '</div>'; ?>
                </div>

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

<!-- Add Equipment Modal -->
<div class="modal fade" id="addEquipmentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Equipment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="addEquipmentForm">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-8 mb-3">
                            <label class="form-label">Equipment Name <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="equipment_name" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Code <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="equipment_code" required>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Department <span class="text-danger">*</span></label>
                            <select class="form-select" name="department" required>
                                <option value="">Select Department</option>
                                <option value="AUDIOLOGY">Audiology</option>
                                <option value="LABORATORY">Laboratory</option>
                                <option value="RADIOLOGY">Radiology</option>
                                <option value="ENDOSCOPY">Endoscopy</option>
                                <option value="ALLERGY">Allergy</option>
                                <option value="SLEEP_STUDY">Sleep Study</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Status <span class="text-danger">*</span></label>
                            <select class="form-select" name="status" required>
                                <option value="OPERATIONAL">Operational</option>
                                <option value="UNDER_MAINTENANCE">Under Maintenance</option>
                                <option value="OUT_OF_SERVICE">Out of Service</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="2"></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Manufacturer</label>
                            <input type="text" class="form-control" name="manufacturer">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Model Number</label>
                            <input type="text" class="form-control" name="model_number">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Serial Number</label>
                            <input type="text" class="form-control" name="serial_number">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Location</label>
                            <input type="text" class="form-control" name="location">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Purchase Date</label>
                            <input type="date" class="form-control" name="purchase_date">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Warranty Expiry</label>
                            <input type="date" class="form-control" name="warranty_expiry">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" style="background: #667eea; border: none;">
                        <i class="ri-save-line me-2"></i>Save Equipment
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include 'layouts/vendor-scripts.php'; ?>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="assets/js/app.js"></script>

<script>
    function showAddEquipmentModal() {
        var modal = new bootstrap.Modal(document.getElementById('addEquipmentModal'));
        modal.show();
    }
    
    $('#addEquipmentForm').on('submit', function(e) {
        e.preventDefault();
        
        $.ajax({
            url: 'actions/add_equipment.php',
            method: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(response) {
                if(response.success) {
                    Swal.fire('Success!', response.message, 'success')
                    .then(() => location.reload());
                } else {
                    Swal.fire('Error!', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error!', 'Failed to add equipment', 'error');
            }
        });
    });
    
    function editEquipment(equipmentId) {
        window.location.href = 'edit_equipment.php?id=' + equipmentId;
    }
    
    function showMaintenanceLog(equipmentId) {
        window.location.href = 'equipment_maintenance_log.php?id=' + equipmentId;
    }
    
    function markMaintenance(equipmentId) {
        Swal.fire({
            title: 'Mark for Maintenance?',
            text: 'This equipment will be marked as under maintenance',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#f59e0b',
            confirmButtonText: 'Yes, mark it'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'actions/update_equipment_status.php',
                    method: 'POST',
                    data: { equipment_id: equipmentId, status: 'UNDER_MAINTENANCE' },
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            Swal.fire('Updated!', response.message, 'success')
                            .then(() => location.reload());
                        }
                    }
                });
            }
        });
    }
    
    // Filter functionality
    $('#statusFilter, #departmentFilter').on('change', function() {
        filterEquipment();
    });
    
    function filterEquipment() {
        const status = $('#statusFilter').val();
        const department = $('#departmentFilter').val();
        
        $('.equipment-card').each(function() {
            const cardStatus = $(this).data('status');
            const cardDept = $(this).closest('.department-group').data('department');
            
            const matchesStatus = !status || cardStatus === status;
            const matchesDept = !department || cardDept === department;
            
            $(this).toggle(matchesStatus && matchesDept);
        });
    }
    
    function resetFilters() {
        $('#statusFilter').val('');
        $('#departmentFilter').val('');
        filterEquipment();
    }
</script>
</body>
</html>