<?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('view_procedure.php', $conn);

// Get procedure ID
$procedure_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$procedure_id) {
    header('Location: list_procedures.php');
    exit();
}

// Fetch procedure details with all related information
$procedure_sql = "SELECT 
    pp.*,
    u_patient.full_name as patient_name,
    p.patient_number,
    p.registration_type,
    u_patient.phone_primary as patient_phone,
    u_patient.email as patient_email,
    u_patient.date_of_birth,
    u_patient.gender,
    TIMESTAMPDIFF(YEAR, u_patient.date_of_birth, CURDATE()) as patient_age,
    ept.procedure_name,
    ept.procedure_code,
    ept.category,
    ept.subcategory,
    ept.duration_minutes,
    ept.requires_anesthesia,
    ept.anesthesia_type,
    u_doctor.full_name as doctor_name,
    d.specialization as doctor_specialization,
    u_anes.full_name as anesthesiologist_name,
    pv.visit_number,
    pv.registration_date,
    pv.visit_type,
    c.consultation_id,
    c.chief_complaint
FROM patient_procedures pp
INNER JOIN patients p ON pp.patient_id = p.patient_id
INNER JOIN users u_patient ON p.user_id = u_patient.user_id
INNER JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
INNER JOIN users u_doctor ON pp.performed_by = u_doctor.user_id
LEFT JOIN doctors d ON u_doctor.user_id = d.user_id
LEFT JOIN users u_anes ON pp.anesthesiologist_id = u_anes.user_id
INNER JOIN patient_visits pv ON pp.visit_id = pv.visit_id
LEFT JOIN consultations c ON pp.consultation_id = c.consultation_id
WHERE pp.procedure_id = ?";

$stmt = $conn->prepare($procedure_sql);
$stmt->bind_param('i', $procedure_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    header('Location: list_procedures.php');
    exit();
}

$procedure = $result->fetch_assoc();

// Get procedure status history if available
$history_sql = "SELECT * FROM procedure_status_history 
                WHERE procedure_id = ? 
                ORDER BY changed_at DESC";
$stmt = $conn->prepare($history_sql);
$stmt->bind_param('i', $procedure_id);
$stmt->execute();
$history_result = $stmt->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Procedure')); ?>
    <?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;
        }
        
        .profile-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2rem;
            font-weight: 700;
            color: #2d7a2d;
            border: 4px solid rgba(255,255,255,0.3);
        }
        
        .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;
        }
        
        .info-row {
            display: flex;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            width: 200px;
            font-weight: 600;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .info-value {
            flex: 1;
            color: #1e293b;
        }
        
        .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;
        }
        
        .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: 1.5rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .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;
        }
        
        .timeline-item {
            position: relative;
            padding-left: 2rem;
            padding-bottom: 1.5rem;
            border-left: 2px solid #e2e8f0;
        }
        
        .timeline-item:last-child {
            border-left: 2px solid transparent;
            padding-bottom: 0;
        }
        
        .timeline-marker {
            position: absolute;
            left: -0.5rem;
            top: 0;
            width: 1rem;
            height: 1rem;
            border-radius: 50%;
            background: #2d7a2d;
            border: 3px solid white;
            box-shadow: 0 0 0 2px #e2e8f0;
        }
        
        .timeline-marker.completed {
            background: #059669;
        }
        
        .timeline-marker.cancelled {
            background: #dc2626;
        }
        
        .notes-section {
            background: #f8fafc;
            border-left: 4px solid #2d7a2d;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1rem;
        }
        
        .medical-alert {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 1rem;
            border-radius: 6px;
            margin-bottom: 1rem;
        }
    </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">Procedure Details</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">View</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Procedure Header -->
                    <div class="profile-header">
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <div class="profile-avatar">
                                    <i class="ri-surgical-mask-line"></i>
                                </div>
                            </div>
                            <div class="col">
                                <h3 class="mb-2"><?php echo htmlspecialchars($procedure['procedure_name']); ?></h3>
                                <div class="d-flex gap-3 flex-wrap">
                                    <div>
                                        <i class="ri-hashtag me-1"></i>
                                        <?php echo htmlspecialchars($procedure['procedure_number']); ?>
                                    </div>
                                    <div>
                                        <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>
                                        <i class="ri-user-line me-1"></i>
                                        <?php echo htmlspecialchars($procedure['patient_name']); ?>
                                    </div>
                                    <div>
                                        <span class="badge badge-<?php echo strtolower($procedure['status']); ?>">
                                            <?php echo str_replace('_', ' ', $procedure['status']); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-auto">
                                <div class="d-flex gap-2 flex-wrap">
                                    <?php if ($procedure['status'] === 'SCHEDULED' && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR'])): ?>
                                    <a href="edit_procedure.php?id=<?php echo $procedure_id; ?>" class="btn btn-light">
                                        <i class="ri-edit-line me-1"></i> Edit
                                    </a>
                                    <button type="button" class="btn btn-warning" onclick="startProcedure()">
                                        <i class="ri-play-line me-1"></i> Start
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($procedure['status'] === 'IN_PROGRESS' && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR'])): ?>
                                    <button type="button" class="btn btn-success" onclick="completeProcedure()">
                                        <i class="ri-check-line me-1"></i> Complete
                                    </button>
                                    <?php endif; ?>
                                    
                                    <a href="patient_profile.php?id=<?php echo $procedure['patient_id']; ?>" class="btn btn-info">
                                        <i class="ri-user-line me-1"></i> Patient
                                    </a>
                                    
                                    <button type="button" class="btn btn-light" onclick="window.print()">
                                        <i class="ri-printer-line me-1"></i> Print
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column -->
                        <div class="col-lg-8">
                            <!-- Procedure Information -->
                            <div class="info-card">
                                <h5><i class="ri-information-line me-2"></i>Procedure Information</h5>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Procedure Code</div>
                                            <div class="info-value"><strong><?php echo htmlspecialchars($procedure['procedure_code']); ?></strong></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Category</div>
                                            <div class="info-value">
                                                <span class="badge badge-<?php echo strtolower($procedure['category']); ?>">
                                                    <?php echo $procedure['category']; ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Subcategory</div>
                                            <div class="info-value"><?php echo htmlspecialchars($procedure['subcategory'] ?: '-'); ?></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Duration</div>
                                            <div class="info-value"><?php echo $procedure['duration_minutes']; ?> minutes</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Cost</div>
                                            <div class="info-value">
                                                <strong class="text-success">KES <?php echo number_format($procedure['cost'], 2); ?></strong>
                                            </div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Status</div>
                                            <div class="info-value">
                                                <span class="badge badge-<?php echo strtolower($procedure['status']); ?>">
                                                    <?php echo str_replace('_', ' ', $procedure['status']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Anesthesia</div>
                                            <div class="info-value">
                                                <?php if ($procedure['requires_anesthesia']): ?>
                                                    <span class="badge bg-warning text-dark">
                                                        Yes - <?php echo $procedure['anesthesia_type']; ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="badge bg-light text-dark">No</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        <?php if ($procedure['room_number']): ?>
                                        <div class="info-row">
                                            <div class="info-label">Room/Theatre</div>
                                            <div class="info-value"><strong><?php echo htmlspecialchars($procedure['room_number']); ?></strong></div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Patient Information -->
                            <div class="info-card">
                                <h5><i class="ri-user-line me-2"></i>Patient Information</h5>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Patient Name</div>
                                            <div class="info-value">
                                                <a href="patient_profile.php?id=<?php echo $procedure['patient_id']; ?>">
                                                    <strong><?php echo htmlspecialchars($procedure['patient_name']); ?></strong>
                                                </a>
                                            </div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Patient Number</div>
                                            <div class="info-value"><?php echo htmlspecialchars($procedure['patient_number']); ?></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Age/Gender</div>
                                            <div class="info-value"><?php echo $procedure['patient_age']; ?> years / <?php echo ucfirst(strtolower($procedure['gender'])); ?></div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Registration Type</div>
                                            <div class="info-value">
                                                <span class="badge bg-light text-dark">
                                                    <?php echo str_replace('_', ' ', $procedure['registration_type']); ?>
                                                </span>
                                            </div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Phone</div>
                                            <div class="info-value"><?php echo htmlspecialchars($procedure['patient_phone'] ?: '-'); ?></div>
                                        </div>
                                        <div class="info-row">
                                            <div class="info-label">Visit Number</div>
                                            <div class="info-value">
                                                <?php echo htmlspecialchars($procedure['visit_number']); ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Medical Team -->
                            <div class="info-card">
                                <h5><i class="ri-team-line me-2"></i>Medical Team</h5>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Performing Doctor</div>
                                            <div class="info-value">
                                                <strong>Dr. <?php echo htmlspecialchars($procedure['doctor_name']); ?></strong>
                                                <?php if ($procedure['doctor_specialization']): ?>
                                                    <br><small class="text-muted"><?php echo htmlspecialchars($procedure['doctor_specialization']); ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <?php if ($procedure['anesthesiologist_name']): ?>
                                    <div class="col-md-6">
                                        <div class="info-row">
                                            <div class="info-label">Anesthesiologist</div>
                                            <div class="info-value">
                                                <strong>Dr. <?php echo htmlspecialchars($procedure['anesthesiologist_name']); ?></strong>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <?php if ($procedure['assisted_by']): 
                                    $assistants = json_decode($procedure['assisted_by'], true);
                                    if ($assistants && is_array($assistants)):
                                ?>
                                <div class="info-row">
                                    <div class="info-label">Assisted By</div>
                                    <div class="info-value">
                                        <?php 
                                        foreach ($assistants as $assistant_id) {
                                            $assistant_sql = "SELECT full_name FROM users WHERE user_id = ?";
                                            $stmt = $conn->prepare($assistant_sql);
                                            $stmt->bind_param('i', $assistant_id);
                                            $stmt->execute();
                                            $assistant_result = $stmt->get_result();
                                            if ($assistant_result->num_rows > 0) {
                                                $assistant = $assistant_result->fetch_assoc();
                                                echo htmlspecialchars($assistant['full_name']) . '<br>';
                                            }
                                        }
                                        ?>
                                    </div>
                                </div>
                                <?php 
                                    endif;
                                endif; 
                                ?>
                            </div>

                            <!-- Clinical Notes -->
                            <div class="info-card">
                                <h5><i class="ri-file-text-line me-2"></i>Clinical Notes</h5>
                                
                                <?php if ($procedure['pre_procedure_notes']): ?>
                                <div class="notes-section">
                                    <h6 class="mb-2"><i class="ri-clipboard-line me-1"></i> Pre-Procedure Notes</h6>
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($procedure['pre_procedure_notes'])); ?></p>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($procedure['procedure_notes']): ?>
                                <div class="notes-section">
                                    <h6 class="mb-2"><i class="ri-stethoscope-line me-1"></i> Procedure Notes</h6>
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($procedure['procedure_notes'])); ?></p>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($procedure['post_procedure_notes']): ?>
                                <div class="notes-section">
                                    <h6 class="mb-2"><i class="ri-file-list-line me-1"></i> Post-Procedure Notes</h6>
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($procedure['post_procedure_notes'])); ?></p>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($procedure['complications']): ?>
                                <div class="medical-alert">
                                    <h6 class="mb-2"><i class="ri-alert-line me-1"></i> Complications</h6>
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($procedure['complications'])); ?></p>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($procedure['outcome']): ?>
                                <div class="notes-section">
                                    <h6 class="mb-2"><i class="ri-checkbox-circle-line me-1"></i> Outcome</h6>
                                    <p class="mb-0"><?php echo nl2br(htmlspecialchars($procedure['outcome'])); ?></p>
                                </div>
                                <?php endif; ?>
                                
                                <?php if (!$procedure['pre_procedure_notes'] && !$procedure['procedure_notes'] && !$procedure['post_procedure_notes'] && !$procedure['complications'] && !$procedure['outcome']): ?>
                                <div class="text-center py-3 text-muted">
                                    <i class="ri-file-list-line" style="font-size: 2rem;"></i>
                                    <p class="mb-0">No clinical notes available</p>
                                </div>
                                <?php endif; ?>
                            </div>

                            <?php if ($procedure['specimens_collected'] || $procedure['images_captured']): ?>
                            <!-- Additional Information -->
                            <div class="info-card">
                                <h5><i class="ri-test-tube-line me-2"></i>Additional Information</h5>
                                
                                <?php if ($procedure['specimens_collected']): 
                                    $specimens = json_decode($procedure['specimens_collected'], true);
                                    if ($specimens && is_array($specimens)):
                                ?>
                                <div class="mb-3">
                                    <h6>Specimens Collected</h6>
                                    <ul>
                                        <?php foreach ($specimens as $specimen): ?>
                                        <li><?php echo htmlspecialchars($specimen); ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                                <?php 
                                    endif;
                                endif; 
                                ?>
                                
                                <?php if ($procedure['pathology_required']): ?>
                                <div class="alert alert-info">
                                    <i class="ri-microscope-line me-2"></i>
                                    <strong>Pathology Required:</strong> Yes
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($procedure['images_captured']): 
                                    $images = json_decode($procedure['images_captured'], true);
                                    if ($images && is_array($images)):
                                ?>
                                <div>
                                    <h6>Images Captured</h6>
                                    <p><?php echo count($images); ?> image(s) captured during procedure</p>
                                </div>
                                <?php 
                                    endif;
                                endif; 
                                ?>
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- Right Column -->
                        <div class="col-lg-4">
                            <!-- Quick Stats -->
                            <div class="row">
                                <div class="col-12 mb-3">
                                    <div class="stat-card">
                                        <div class="stat-value text-success">KES <?php echo number_format($procedure['cost'], 2); ?></div>
                                        <div class="stat-label">Procedure Cost</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Timeline/Status History -->
                            <?php if ($history_result->num_rows > 0): ?>
                            <div class="info-card">
                                <h5><i class="ri-time-line me-2"></i>Status History</h5>
                                
                                <div class="timeline">
                                    <?php while ($history = $history_result->fetch_assoc()): ?>
                                    <div class="timeline-item">
                                        <div class="timeline-marker <?php echo strtolower($history['new_status']); ?>"></div>
                                        <div>
                                            <strong><?php echo str_replace('_', ' ', $history['new_status']); ?></strong>
                                            <div class="text-muted small">
                                                <?php echo date('d M Y, H:i', strtotime($history['changed_at'])); ?>
                                            </div>
                                            <?php if ($history['notes']): ?>
                                            <div class="text-muted small mt-1">
                                                <?php echo htmlspecialchars($history['notes']); ?>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Quick Actions -->
                            <div class="info-card">
                                <h5><i class="ri-settings-3-line me-2"></i>Quick Actions</h5>
                                
                                <div class="d-grid gap-2">
                                    <?php if ($procedure['status'] === 'SCHEDULED' && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR'])): ?>
                                    <button type="button" class="btn btn-warning" onclick="startProcedure()">
                                        <i class="ri-play-line me-1"></i> Start Procedure
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($procedure['status'] === 'IN_PROGRESS' && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR'])): ?>
                                    <button type="button" class="btn btn-success" onclick="completeProcedure()">
                                        <i class="ri-check-line me-1"></i> Mark Complete
                                    </button>
                                    <button type="button" class="btn btn-info" onclick="addNotes()">
                                        <i class="ri-file-text-line me-1"></i> Add Notes
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if (in_array($procedure['status'], ['SCHEDULED', 'IN_PROGRESS']) && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])): ?>
                                    <button type="button" class="btn btn-danger" onclick="cancelProcedure()">
                                        <i class="ri-close-line me-1">
                                            </i> Cancel Procedure
                                    </button>
                                    <?php endif; ?>
                                    
                                    <a href="list_procedures.php" class="btn btn-light">
                                        <i class="ri-arrow-left-line me-1"></i> Back to List
                                    </a>
                                </div>
                            </div>

                            <!-- Related Information -->
                            <div class="info-card">
                                <h5><i class="ri-links-line me-2"></i>Related Information</h5>
                                
                                <div class="d-grid gap-2">
                                    <a href="patient_profile.php?id=<?php echo $procedure['patient_id']; ?>" class="btn btn-outline-primary">
                                        <i class="ri-user-line me-1"></i> Patient Profile
                                    </a>
                                    
                                    <?php if ($procedure['consultation_id']): ?>
                                    <a href="view_consultation.php?id=<?php echo $procedure['consultation_id']; ?>" class="btn btn-outline-primary">
                                        <i class="ri-stethoscope-line me-1"></i> Consultation
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </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 startProcedure() {
            Swal.fire({
                title: 'Start Procedure?',
                text: 'This will mark the procedure as in progress',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#2d7a2d',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Start',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    updateProcedureStatus('IN_PROGRESS', 'Procedure started');
                }
            });
        }
        
        function completeProcedure() {
            Swal.fire({
                title: 'Complete Procedure?',
                html: `
                    <div class="text-start">
                        <label class="form-label">Outcome Notes (Optional)</label>
                        <textarea id="outcome_notes" class="form-control" rows="4" placeholder="Enter procedure outcome..."></textarea>
                    </div>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#2d7a2d',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Complete Procedure',
                cancelButtonText: 'Cancel',
                preConfirm: () => {
                    return {
                        notes: document.getElementById('outcome_notes').value
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    updateProcedureStatus('COMPLETED', result.value.notes || 'Procedure completed successfully');
                }
            });
        }
        
        function cancelProcedure() {
            Swal.fire({
                title: 'Cancel Procedure?',
                html: `
                    <div class="text-start">
                        <label class="form-label">Reason for Cancellation <span class="text-danger">*</span></label>
                        <textarea id="cancel_reason" class="form-control" rows="4" placeholder="Enter reason for cancellation..." required></textarea>
                    </div>
                `,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Cancel Procedure',
                cancelButtonText: 'Go Back',
                preConfirm: () => {
                    const reason = document.getElementById('cancel_reason').value;
                    if (!reason) {
                        Swal.showValidationMessage('Please provide a reason for cancellation');
                    }
                    return { reason: reason }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    updateProcedureStatus('CANCELLED', result.value.reason);
                }
            });
        }
        
        function addNotes() {
            Swal.fire({
                title: 'Add Procedure Notes',
                html: `
                    <div class="text-start">
                        <label class="form-label">Note Type</label>
                        <select id="note_type" class="form-select mb-3">
                            <option value="procedure_notes">Procedure Notes</option>
                            <option value="post_procedure_notes">Post-Procedure Notes</option>
                            <option value="complications">Complications</option>
                            <option value="outcome">Outcome</option>
                        </select>
                        <label class="form-label">Notes</label>
                        <textarea id="note_content" class="form-control" rows="5" placeholder="Enter notes..."></textarea>
                    </div>
                `,
                width: '600px',
                showCancelButton: true,
                confirmButtonColor: '#2d7a2d',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Save Notes',
                cancelButtonText: 'Cancel',
                preConfirm: () => {
                    const noteType = document.getElementById('note_type').value;
                    const noteContent = document.getElementById('note_content').value;
                    if (!noteContent) {
                        Swal.showValidationMessage('Please enter notes');
                    }
                    return { type: noteType, content: noteContent }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    saveNotes(result.value.type, result.value.content);
                }
            });
        }
        
        function updateProcedureStatus(status, notes) {
            // Show loading
            Swal.fire({
                title: 'Updating...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Send AJAX request
            fetch('ajax/update_procedure_status.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    procedure_id: <?php echo $procedure_id; ?>,
                    status: status,
                    notes: notes
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Procedure status updated successfully',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: data.message || 'Failed to update procedure status'
                    });
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while updating the procedure'
                });
            });
        }
        
        function saveNotes(noteType, noteContent) {
            // Show loading
            Swal.fire({
                title: 'Saving...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Send AJAX request
            fetch('ajax/save_procedure_notes.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    procedure_id: <?php echo $procedure_id; ?>,
                    note_type: noteType,
                    note_content: noteContent
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Notes saved successfully',
                        timer: 1500,
                        showConfirmButton: false
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: data.message || 'Failed to save notes'
                    });
                }
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: 'An error occurred while saving notes'
                });
            });
        }
    </script>
</body>
</html>
<?php $conn->close(); ?>