<?php
/**
 * Equipment Log Page
 * Audiologist Role - Track Equipment Usage and Maintenance
 */

require_once 'layouts/session.php';
require_once 'layouts/dbconn.php';

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

$page_title = "Equipment Log";
$user_id = $_SESSION['user_id'];

// Get audiology equipment
$equipment_sql = "SELECT * FROM equipment_logs 
                  WHERE department = 'AUDIOLOGY' OR equipment_name LIKE '%Audio%' OR equipment_name LIKE '%Audi%'
                  ORDER BY equipment_name";
$equipment_result = $conn->query($equipment_sql);

// Get recent usage logs
$usage_sql = "SELECT el.*, u.full_name as used_by_name
              FROM equipment_usage_logs eul
              INNER JOIN equipment_logs el ON eul.equipment_id = el.equipment_id
              INNER JOIN users u ON eul.used_by = u.user_id
              WHERE (el.department = 'AUDIOLOGY' OR el.equipment_name LIKE '%Audio%')
              AND eul.used_by = ?
              ORDER BY eul.used_at DESC
              LIMIT 50";
$stmt = $conn->prepare($usage_sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$usage_result = $stmt->get_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/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .page-header { background: white; padding: 1.5rem; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 1.5rem; }
        .info-card { background: white; border-radius: 12px; padding: 1.5rem; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-bottom: 1.5rem; }
        .info-card h5 { font-size: 1.125rem; font-weight: 600; margin-bottom: 1.25rem; padding-bottom: 0.75rem; border-bottom: 2px solid #e2e8f0; }
        .equipment-card { background: #f8fafc; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; border-left: 4px solid #2d7a2d; }
    </style>
</head>
<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <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"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">Test Management</li>
                                        <li class="breadcrumb-item active"><?php echo $page_title; ?></li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="page-header">
                        <h4><i class="ri-tools-line me-2" style="color: #2d7a2d;"></i>Audiology Equipment Management</h4>
                        <p class="mb-0">Track equipment usage, maintenance, and availability</p>
                    </div>
                    
                    <!-- Equipment Inventory -->
                    <div class="row">
                        <div class="col-12">
                            <div class="info-card">
                                <h5><i class="ri-device-line me-2"></i>Available Equipment</h5>
                                
                                <div class="row">
                                    <?php if ($equipment_result->num_rows > 0): ?>
                                        <?php while ($equip = $equipment_result->fetch_assoc()): ?>
                                            <div class="col-xl-6 col-md-12 mb-3">
                                                <div class="equipment-card">
                                                    <div class="d-flex justify-content-between align-items-start">
                                                        <div>
                                                            <h6><?php echo htmlspecialchars($equip['equipment_name']); ?></h6>
                                                            <small class="text-muted">Code: <?php echo htmlspecialchars($equip['equipment_code']); ?></small>
                                                        </div>
                                                        <span class="badge bg-<?php echo $equip['status'] == 'OPERATIONAL' ? 'success' : ($equip['status'] == 'MAINTENANCE' ? 'warning' : 'danger'); ?>">
                                                            <?php echo htmlspecialchars($equip['status']); ?>
                                                        </span>
                                                    </div>
                                                    <?php if ($equip['description']): ?>
                                                        <p class="mt-2 mb-2"><small><?php echo htmlspecialchars($equip['description']); ?></small></p>
                                                    <?php endif; ?>
                                                    <div class="mt-2">
                                                        <?php if ($equip['next_maintenance_date']): ?>
                                                            <small class="text-muted">Next Maintenance: <?php echo date('M j, Y', strtotime($equip['next_maintenance_date'])); ?></small>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="mt-2">
                                                        <button class="btn btn-sm btn-primary" onclick="logUsage(<?php echo $equip['equipment_id']; ?>, '<?php echo htmlspecialchars($equip['equipment_name']); ?>')">
                                                            <i class="ri-checkbox-circle-line"></i> Log Usage
                                                        </button>
                                                        <?php if ($equip['status'] != 'OPERATIONAL'): ?>
                                                            <button class="btn btn-sm btn-warning" onclick="reportIssue(<?php echo $equip['equipment_id']; ?>)">
                                                                <i class="ri-error-warning-line"></i> Report Issue
                                                            </button>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="col-12">
                                            <p class="text-center text-muted">No equipment registered</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Usage History -->
                    <div class="row">
                        <div class="col-12">
                            <div class="info-card">
                                <h5><i class="ri-history-line me-2"></i>My Usage History</h5>
                                <div class="table-responsive">
                                    <table id="usageTable" class="table table-striped nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Date/Time</th>
                                                <th>Equipment</th>
                                                <th>Purpose</th>
                                                <th>Duration</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php if ($usage_result->num_rows > 0): ?>
                                                <?php while ($usage = $usage_result->fetch_assoc()): ?>
                                                    <tr>
                                                        <td><?php echo date('M j, Y g:i A', strtotime($usage['used_at'])); ?></td>
                                                        <td><strong><?php echo htmlspecialchars($usage['equipment_name']); ?></strong></td>
                                                        <td><small><?php echo htmlspecialchars($usage['purpose'] ?? 'General use'); ?></small></td>
                                                        <td><?php echo htmlspecialchars($usage['duration_minutes'] ?? '—') . ' min'; ?></td>
                                                        <td>
                                                            <span class="badge bg-<?php echo $usage['status'] == 'OPERATIONAL' ? 'success' : 'warning'; ?>">
                                                                <?php echo htmlspecialchars($usage['status']); ?>
                                                            </span>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            <?php else: ?>
                                                <tr><td colspan="5" class="text-center">No usage history</td></tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script>
        $(document).ready(function() { $('#usageTable').DataTable({ responsive: true, order: [[0, 'desc']], pageLength: 25 }); });
        
        function logUsage(equipmentId, equipmentName) {
            Swal.fire({
                title: 'Log Equipment Usage',
                html: '<p>Equipment: <strong>' + equipmentName + '</strong></p>' +
                      '<input type="text" id="purpose" class="swal2-input" placeholder="Purpose/Test Type">' +
                      '<input type="number" id="duration" class="swal2-input" placeholder="Duration (minutes)">',
                showCancelButton: true,
                confirmButtonColor: '#2d7a2d',
                confirmButtonText: 'Log Usage',
                preConfirm: () => {
                    return {
                        purpose: document.getElementById('purpose').value,
                        duration: document.getElementById('duration').value
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.post('ajax/log_equipment_usage.php', {
                        equipment_id: equipmentId,
                        purpose: result.value.purpose,
                        duration: result.value.duration
                    }, function(res) {
                        if (res.success) Swal.fire('Logged', 'Equipment usage logged successfully', 'success').then(() => location.reload());
                        else Swal.fire('Error', res.message, 'error');
                    }, 'json');
                }
            });
        }
        
        function reportIssue(equipmentId) {
            Swal.fire({
                title: 'Report Equipment Issue',
                input: 'textarea',
                inputPlaceholder: 'Describe the issue...',
                showCancelButton: true,
                confirmButtonColor: '#f59e0b',
                confirmButtonText: 'Report Issue'
            }).then((result) => {
                if (result.isConfirmed && result.value) {
                    $.post('ajax/report_equipment_issue.php', {
                        equipment_id: equipmentId,
                        issue: result.value
                    }, function(res) {
                        if (res.success) Swal.fire('Reported', 'Issue reported successfully', 'success').then(() => location.reload());
                        else Swal.fire('Error', res.message, 'error');
                    }, 'json');
                }
            });
        }
    </script>
    <script src="assets/js/app.js"></script>
</body>
</html>