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

// Get date filter (default to today)
$filter_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$filter_room = isset($_GET['room']) ? $_GET['room'] : '';

// Build query
$schedule_sql = "SELECT 
    pp.*,
    pt.full_name as patient_name,
    p.patient_number,
    ept.procedure_name,
    ept.category,
    ept.duration_minutes,
    u.full_name as doctor_name,
    anes.full_name as anesthesiologist_name,
    pv.visit_number
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
LEFT JOIN users anes ON pp.anesthesiologist_id = anes.user_id
INNER JOIN patient_visits pv ON pp.visit_id = pv.visit_id
WHERE pp.procedure_date = ? 
AND pp.status IN ('SCHEDULED', 'IN_PROGRESS')
AND ept.category = 'SURGICAL'";

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

if ($filter_room) {
    $schedule_sql .= " AND pp.room_number = ?";
    $params[] = $filter_room;
    $types .= 's';
}

$schedule_sql .= " ORDER BY pp.procedure_time ASC";

$stmt = $conn->prepare($schedule_sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$schedule_result = $stmt->get_result();

// Get available rooms
$rooms_sql = "SELECT DISTINCT room_number FROM patient_procedures WHERE room_number IS NOT NULL ORDER BY room_number";
$rooms_result = $conn->query($rooms_sql);

// Get statistics for selected date
$stats_sql = "SELECT 
    COUNT(*) as total_surgeries,
    COUNT(CASE WHEN status = 'SCHEDULED' THEN 1 END) as scheduled,
    COUNT(CASE WHEN status = 'IN_PROGRESS' THEN 1 END) as in_progress,
    SUM(ept.duration_minutes) as total_duration
FROM patient_procedures pp
INNER JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
WHERE pp.procedure_date = ? 
AND pp.status IN ('SCHEDULED', 'IN_PROGRESS')
AND ept.category = 'SURGICAL'";

$stmt = $conn->prepare($stats_sql);
$stmt->bind_param('s', $filter_date);
$stmt->execute();
$stats = $stmt->get_result()->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Surgery Schedule')); ?>
    <?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;
        }
        
        .surgery-card {
            background: white;
            border-radius: 8px;
            padding: 1.25rem;
            margin-bottom: 1rem;
            border-left: 4px solid #2d7a2d;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .surgery-card.in-progress {
            border-left-color: #f59e0b;
            background: #fffbeb;
        }
        
        .timeline-marker {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #2d7a2d;
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 0.875rem;
        }
        
        .timeline-marker.in-progress {
            background: #f59e0b;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% {
                opacity: 1;
            }
            50% {
                opacity: 0.7;
            }
        }
        
        .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;
        }
    </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">Surgery Schedule</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"><a href="list_procedures.php">Procedures</a></li>
                                        <li class="breadcrumb-item active">Surgery Schedule</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['total_surgeries']); ?></div>
                                <div class="stat-label">Total Surgeries</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <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-3 col-md-6">
                            <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-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo $stats['total_duration'] ? round($stats['total_duration'] / 60, 1) : 0; ?>h</div>
                                <div class="stat-label">Total Duration</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <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">Date</label>
                                    <input type="date" name="date" class="form-control" 
                                           value="<?php echo $filter_date; ?>" 
                                           onchange="document.getElementById('filterForm').submit();">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Room/Theatre</label>
                                    <select name="room" class="form-select" onchange="document.getElementById('filterForm').submit();">
                                        <option value="">All Rooms</option>
                                        <?php while ($room = $rooms_result->fetch_assoc()): ?>
                                        <option value="<?php echo htmlspecialchars($room['room_number']); ?>" 
                                                <?php echo $filter_room === $room['room_number'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($room['room_number']); ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <button type="button" class="btn btn-secondary w-100" onclick="location.href='surgery_schedule.php'">
                                        <i class="ri-refresh-line me-1"></i> Reset
                                    </button>
                                </div>
                                <div class="col-md-3">
                                    <a href="schedule_procedure.php" class="action-btn btn-primary-custom w-100">
                                        <i class="ri-add-line"></i> Schedule Surgery
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Surgery Schedule -->
                    <div class="info-card">
                        <h5>
                            <i class="ri-surgical-mask-line me-2"></i>
                            Surgery Schedule for <?php echo date('l, F j, Y', strtotime($filter_date)); ?>
                        </h5>
                        
                        <?php if ($schedule_result->num_rows > 0): ?>
                            <?php while ($surgery = $schedule_result->fetch_assoc()): ?>
                            <div class="surgery-card <?php echo $surgery['status'] === 'IN_PROGRESS' ? 'in-progress' : ''; ?>">
                                <div class="row align-items-center">
                                    <div class="col-auto">
                                        <div class="timeline-marker <?php echo $surgery['status'] === 'IN_PROGRESS' ? 'in-progress' : ''; ?>">
                                            <div><?php echo date('H:i', strtotime($surgery['procedure_time'])); ?></div>
                                            <small style="font-size: 0.65rem;"><?php echo $surgery['duration_minutes']; ?>min</small>
                                        </div>
                                    </div>
                                    <div class="col-md-5">
                                        <h6 class="mb-2">
                                            <a href="view_procedure.php?id=<?php echo $surgery['procedure_id']; ?>" 
                                               class="text-dark text-decoration-none">
                                                <?php echo htmlspecialchars($surgery['procedure_name']); ?>
                                            </a>
                                        </h6>
                                        <div class="text-muted small">
                                            <i class="ri-user-line me-1"></i>
                                            <strong><?php echo htmlspecialchars($surgery['patient_name']); ?></strong>
                                            (<?php echo htmlspecialchars($surgery['patient_number']); ?>)
                                        </div>
                                        <div class="text-muted small mt-1">
                                            <i class="ri-stethoscope-line me-1"></i>
                                            Dr. <?php echo htmlspecialchars($surgery['doctor_name']); ?>
                                        </div>
                                        <?php if ($surgery['anesthesiologist_name']): ?>
                                        <div class="text-muted small mt-1">
                                            <i class="ri-syringe-line me-1"></i>
                                            Dr. <?php echo htmlspecialchars($surgery['anesthesiologist_name']); ?> (Anesthesiologist)
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="col-md-3">
                                        <?php if ($surgery['room_number']): ?>
                                        <div class="mb-2">
                                            <span class="badge bg-light text-dark">
                                                <i class="ri-hospital-line me-1"></i>
                                                <?php echo htmlspecialchars($surgery['room_number']); ?>
                                            </span>
                                        </div>
                                        <?php endif; ?>
                                        <div class="text-muted small">
                                            <i class="ri-hashtag me-1"></i>
                                            <?php echo htmlspecialchars($surgery['procedure_number']); ?>
                                        </div>
                                        <div class="text-muted small mt-1">
                                            <i class="ri-file-list-3-line me-1"></i>
                                            Visit: <?php echo htmlspecialchars($surgery['visit_number']); ?>
                                        </div>
                                    </div>
                                    <div class="col-md-2 text-center">
                                        <span class="badge badge-<?php echo strtolower($surgery['status']); ?> mb-2">
                                            <?php echo str_replace('_', ' ', $surgery['status']); ?>
                                        </span>
                                        <div class="fw-bold text-success">
                                            KES <?php echo number_format($surgery['cost'], 2); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto 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 $surgery['procedure_id']; ?>">
                                                        <i class="ri-eye-line me-2"></i>View Details
                                                    </a>
                                                </li>
                                                <?php if ($surgery['status'] === 'SCHEDULED'): ?>
                                                <li>
                                                    <a class="dropdown-item" href="edit_procedure.php?id=<?php echo $surgery['procedure_id']; ?>">
                                                        <i class="ri-edit-line me-2"></i>
                                                        >Edit
                                                    </a>
                                                </li>
                                                <li>
                                                    <a class="dropdown-item" href="#" onclick="startSurgery(<?php echo $surgery['procedure_id']; ?>)">
                                                        <i class="ri-play-line me-2"></i>Start Surgery
                                                    </a>
                                                </li>
                                                <?php endif; ?>
                                                <li>
                                                    <a class="dropdown-item" href="patient_profile.php?id=<?php echo $surgery['patient_id']; ?>">
                                                        <i class="ri-user-line me-2"></i>View Patient
                                                    </a>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                
                                <?php if ($surgery['pre_procedure_notes']): ?>
                                <div class="row mt-3">
                                    <div class="col-12">
                                        <div class="alert alert-info mb-0">
                                            <strong><i class="ri-information-line me-1"></i>Pre-Procedure Notes:</strong>
                                            <p class="mb-0 mt-1"><?php echo nl2br(htmlspecialchars($surgery['pre_procedure_notes'])); ?></p>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="text-center py-5">
                                <i class="ri-surgical-mask-line" style="font-size: 4rem; color: #cbd5e1;"></i>
                                <h5 class="mt-3 text-muted">No surgeries scheduled</h5>
                                <p class="text-muted">No surgical procedures scheduled for this date</p>
                                <a href="schedule_procedure.php" class="btn btn-primary mt-3">
                                    <i class="ri-add-line me-1"></i> Schedule Surgery
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>

                    <!-- Quick Navigation -->
                    <div class="row">
                        <div class="col-12">
                            <div class="info-card">
                                <h5><i class="ri-calendar-line me-2"></i>Quick Date Navigation</h5>
                                <div class="d-flex gap-2 flex-wrap">
                                    <?php
                                    // Generate buttons for next 7 days
                                    for ($i = 0; $i < 7; $i++) {
                                        $nav_date = date('Y-m-d', strtotime("+$i days"));
                                        $is_active = $nav_date === $filter_date;
                                        $day_name = $i === 0 ? 'Today' : ($i === 1 ? 'Tomorrow' : date('D', strtotime($nav_date)));
                                        $date_display = date('M j', strtotime($nav_date));
                                        
                                        // Count surgeries for this date
                                        $count_sql = "SELECT COUNT(*) as count FROM patient_procedures pp
                                                     INNER JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
                                                     WHERE pp.procedure_date = ? 
                                                     AND pp.status IN ('SCHEDULED', 'IN_PROGRESS')
                                                     AND ept.category = 'SURGICAL'";
                                        $count_stmt = $conn->prepare($count_sql);
                                        $count_stmt->bind_param('s', $nav_date);
                                        $count_stmt->execute();
                                        $count = $count_stmt->get_result()->fetch_assoc()['count'];
                                    ?>
                                    <a href="surgery_schedule.php?date=<?php echo $nav_date; ?>" 
                                       class="btn <?php echo $is_active ? 'btn-primary' : 'btn-outline-primary'; ?> position-relative">
                                        <div><?php echo $day_name; ?></div>
                                        <small class="d-block"><?php echo $date_display; ?></small>
                                        <?php if ($count > 0): ?>
                                        <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">
                                            <?php echo $count; ?>
                                        </span>
                                        <?php endif; ?>
                                    </a>
                                    <?php } ?>
                                </div>
                            </div>
                        </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>
    
    <script>
        function startSurgery(procedureId) {
            Swal.fire({
                title: 'Start Surgery?',
                text: 'This will mark the surgery as in progress',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#2d7a2d',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Start Surgery',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Send AJAX request to update status
                    fetch('ajax/update_procedure_status.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            procedure_id: procedureId,
                            status: 'IN_PROGRESS'
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Surgery Started',
                                text: 'The surgery has been marked as in progress',
                                timer: 1500,
                                showConfirmButton: false
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: data.message || 'Failed to update surgery status'
                            });
                        }
                    })
                    .catch(error => {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'An error occurred while updating the surgery status'
                        });
                    });
                }
            });
        }
        
        // Auto-refresh every 2 minutes to keep schedule current
        setTimeout(function() {
            location.reload();
        }, 120000);
    </script>
</body>
</html>
<?php $conn->close(); ?>