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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $visit_id = $_POST['visit_id'];
    $patient_id = $_POST['patient_id'];
    $pricing_id = $_POST['pricing_id'];
    $performed_by = $_POST['performed_by'];
    $procedure_date = $_POST['procedure_date'];
    $procedure_time = $_POST['procedure_time'];
    $room_number = $_POST['room_number'] ?? null;
    $pre_procedure_notes = $_POST['pre_procedure_notes'] ?? null;
    $anesthesiologist_id = !empty($_POST['anesthesiologist_id']) ? $_POST['anesthesiologist_id'] : null;
    
    // Get service pricing details
    $pricing_sql = "SELECT * FROM service_pricing WHERE pricing_id = ? AND service_type = 'PROCEDURE'";
    $stmt = $conn->prepare($pricing_sql);
    $stmt->bind_param('i', $pricing_id);
    $stmt->execute();
    $pricing = $stmt->get_result()->fetch_assoc();
    
    if (!$pricing) {
        $error_message = "Invalid procedure selected";
    } else {
        // Get patient registration type to determine price
        $patient_sql = "SELECT registration_type FROM patients WHERE patient_id = ?";
        $stmt = $conn->prepare($patient_sql);
        $stmt->bind_param('i', $patient_id);
        $stmt->execute();
        $patient_info = $stmt->get_result()->fetch_assoc();
        
        // Determine price based on registration type
        $procedure_cost = $pricing['base_price'];
        if ($patient_info['registration_type'] === 'INSURANCE' && $pricing['insurance_price']) {
            $procedure_cost = $pricing['insurance_price'];
        } elseif ($patient_info['registration_type'] === 'CORPORATE' && $pricing['corporate_price']) {
            $procedure_cost = $pricing['corporate_price'];
        }
        
        // Generate procedure number
        $count_sql = "SELECT COUNT(*) as count FROM patient_procedures WHERE DATE(created_at) = CURDATE()";
        $count_result = $conn->query($count_sql);
        $count = $count_result->fetch_assoc()['count'];
        $procedure_number = 'PROC' . date('Ymd') . str_pad($count + 1, 4, '0', STR_PAD_LEFT);
        
        // Get or create procedure_type_id
        $procedure_type_id = $pricing['service_id'];
        
        // If service_id is 0 or null, we need to create/find a procedure type
        if (!$procedure_type_id || $procedure_type_id == 0) {
            // First, try to find matching procedure type by name
            $match_sql = "SELECT procedure_type_id FROM ent_procedure_types 
                         WHERE procedure_name = ? LIMIT 1";
            $stmt = $conn->prepare($match_sql);
            $stmt->bind_param('s', $pricing['service_name']);
            $stmt->execute();
            $match_result = $stmt->get_result();
            
            if ($match_result->num_rows > 0) {
                // Found matching procedure type
                $procedure_type_id = $match_result->fetch_assoc()['procedure_type_id'];
            } else {
                // Create a new procedure type entry
                $create_type_sql = "INSERT INTO ent_procedure_types 
                    (procedure_code, procedure_name, category, description, standard_cost, 
                     duration_minutes, requires_anesthesia, is_active, created_at) 
                    VALUES (?, ?, 'THERAPEUTIC', ?, ?, 30, 0, 1, NOW())";
                
                // Generate procedure code
                $proc_code = 'PROC' . str_pad($pricing['pricing_id'], 4, '0', STR_PAD_LEFT);
                
                $stmt = $conn->prepare($create_type_sql);
                $stmt->bind_param('sssd', 
                    $proc_code, 
                    $pricing['service_name'], 
                    $pricing['service_name'],
                    $pricing['base_price']
                );
                
                if ($stmt->execute()) {
                    $procedure_type_id = $conn->insert_id;
                    
                    // Update service_pricing with the new procedure_type_id
                    $update_pricing_sql = "UPDATE service_pricing SET service_id = ? WHERE pricing_id = ?";
                    $stmt = $conn->prepare($update_pricing_sql);
                    $stmt->bind_param('ii', $procedure_type_id, $pricing_id);
                    $stmt->execute();
                } else {
                    $error_message = "Error creating procedure type: " . $conn->error;
                }
            }
        }
        
        // Only proceed if we have a valid procedure_type_id
        if ($procedure_type_id && !isset($error_message)) {
            // Insert procedure
            $insert_sql = "INSERT INTO patient_procedures 
                (procedure_number, visit_id, patient_id, procedure_type_id, performed_by, 
                 anesthesiologist_id, procedure_date, procedure_time, room_number, 
                 pre_procedure_notes, cost, status, created_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'SCHEDULED', NOW())";
            
            $stmt = $conn->prepare($insert_sql);
            $stmt->bind_param('siiiisisssd', 
                $procedure_number, $visit_id, $patient_id, $procedure_type_id, 
                $performed_by, $anesthesiologist_id, $procedure_date, $procedure_time, 
                $room_number, $pre_procedure_notes, $procedure_cost
            );
            
            if ($stmt->execute()) {
                $_SESSION['success_message'] = "Procedure scheduled successfully!";
                header("Location: list_procedures.php");
                exit();
            } else {
                $error_message = "Error scheduling procedure: " . $conn->error;
            }
        } elseif (!isset($error_message)) {
            $error_message = "Unable to create or find procedure type";
        }
    }
}

// Get patients with active visits
$patients_sql = "SELECT DISTINCT 
    p.patient_id, 
    u.full_name, 
    p.patient_number,
    p.registration_type,
    pv.visit_id,
    pv.visit_number
FROM patients p
INNER JOIN users u ON p.user_id = u.user_id
INNER JOIN patient_visits pv ON p.patient_id = pv.patient_id
WHERE pv.status IN ('REGISTERED', 'IN_CONSULTATION', 'WAITING')
ORDER BY u.full_name";
$patients_result = $conn->query($patients_sql);

// Get procedure services from service_pricing where service_type = 'PROCEDURE'
$procedures_sql = "SELECT sp.pricing_id, sp.service_id, sp.service_name, 
                          sp.base_price, sp.insurance_price, sp.corporate_price,
                          ept.procedure_code, ept.category, ept.subcategory, 
                          ept.duration_minutes, ept.requires_anesthesia, ept.anesthesia_type
                   FROM service_pricing sp
                   LEFT JOIN ent_procedure_types ept ON sp.service_id = ept.procedure_type_id
                   WHERE sp.service_type = 'PROCEDURE' AND sp.is_active = 1
                   ORDER BY sp.service_name";
$procedures = $conn->query($procedures_sql);

// Check if we have procedures
$procedure_count = $procedures->num_rows;

// Get doctors
$doctors_sql = "SELECT u.user_id, u.full_name, d.specialization 
    FROM users u 
    INNER JOIN doctors d ON u.user_id = d.user_id 
    WHERE u.status = 'ACTIVE'
    ORDER BY u.full_name";
$doctors = $conn->query($doctors_sql);

// Get anesthesiologists
$anesthesiologists_sql = "SELECT u.user_id, u.full_name 
    FROM users u 
    WHERE u.role_id IN (SELECT role_id FROM user_roles WHERE role_name LIKE '%Anesthesiologist%') 
    AND u.status = 'ACTIVE' 
    ORDER BY u.full_name";
$anesthesiologists = $conn->query($anesthesiologists_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Schedule Procedure')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.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;
        }
        
        .form-label {
            font-weight: 600;
            color: #475569;
            margin-bottom: 0.5rem;
        }
        
        .required::after {
            content: " *";
            color: #dc2626;
        }
        
        .btn-primary-custom {
            background: #2d7a2d;
            color: white;
            border: none;
        }
        
        .btn-primary-custom:hover {
            background: #245d24;
            color: white;
        }
        
        .price-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            margin-left: 0.5rem;
        }
        
        .price-base {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .price-insurance {
            background: #d1fae5;
            color: #065f46;
        }
        
        .price-corporate {
            background: #fef3c7;
            color: #92400e;
        }
    </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">Schedule Procedure</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">Schedule</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($procedure_count == 0): ?>
                    <div class="alert alert-warning alert-dismissible fade show" role="alert">
                        <i class="ri-alert-line me-2"></i><strong>No procedures found!</strong> 
                        Please ensure procedures are added to the service_pricing table with service_type = 'PROCEDURE'.
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Schedule Form -->
                    <form method="POST" action="" id="scheduleProcedureForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <div class="info-card">
                                    <h5><i class="ri-calendar-check-line me-2"></i>Procedure Details</h5>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label required">Patient</label>
                                            <select name="patient_id" id="patient_id" class="form-select select2" required>
                                                <option value="">Select Patient</option>
                                                <?php while ($patient = $patients_result->fetch_assoc()): ?>
                                                <option value="<?php echo $patient['patient_id']; ?>" 
                                                        data-visit-id="<?php echo $patient['visit_id']; ?>"
                                                        data-reg-type="<?php echo $patient['registration_type']; ?>">
                                                    <?php echo htmlspecialchars($patient['full_name']); ?> 
                                                    (<?php echo htmlspecialchars($patient['patient_number']); ?>) - 
                                                    Visit: <?php echo htmlspecialchars($patient['visit_number']); ?>
                                                    [<?php echo htmlspecialchars($patient['registration_type']); ?>]
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                            <input type="hidden" name="visit_id" id="visit_id">
                                            <input type="hidden" name="patient_reg_type" id="patient_reg_type">
                                        </div>
                                        
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label required">Procedure</label>
                                            <select name="pricing_id" id="pricing_id" class="form-select select2" required>
                                                <option value="">Select Procedure</option>
                                                <?php 
                                                $current_category = '';
                                                while ($proc = $procedures->fetch_assoc()): 
                                                    // Group by category if available
                                                    if ($proc['category'] && $current_category !== $proc['category']) {
                                                        if ($current_category !== '') echo '</optgroup>';
                                                        echo '<optgroup label="' . htmlspecialchars($proc['category']) . '">';
                                                        $current_category = $proc['category'];
                                                    }
                                                ?>
                                                <option value="<?php echo $proc['pricing_id']; ?>" 
                                                        data-base-price="<?php echo $proc['base_price']; ?>"
                                                        data-insurance-price="<?php echo $proc['insurance_price'] ?: ''; ?>"
                                                        data-corporate-price="<?php echo $proc['corporate_price'] ?: ''; ?>"
                                                        data-duration="<?php echo $proc['duration_minutes'] ?: 30; ?>"
                                                        data-anesthesia="<?php echo $proc['requires_anesthesia'] ?: 0; ?>"
                                                        data-code="<?php echo htmlspecialchars($proc['procedure_code'] ?: ''); ?>">
                                                    <?php echo htmlspecialchars($proc['service_name']); ?>
                                                    <?php if ($proc['procedure_code']): ?>
                                                        (<?php echo htmlspecialchars($proc['procedure_code']); ?>)
                                                    <?php endif; ?>
                                                    - KES <?php echo number_format($proc['base_price'], 2); ?>
                                                </option>
                                                <?php 
                                                endwhile; 
                                                if ($current_category !== '') echo '</optgroup>';
                                                ?>
                                            </select>
                                            <small class="text-muted">Total procedures available: <?php echo $procedure_count; ?></small>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label required">Performing Doctor</label>
                                            <select name="performed_by" class="form-select select2" required>
                                                <option value="">Select Doctor</option>
                                                <?php while ($doctor = $doctors->fetch_assoc()): ?>
                                                <option value="<?php echo $doctor['user_id']; ?>">
                                                    Dr. <?php echo htmlspecialchars($doctor['full_name']); ?>
                                                    <?php if ($doctor['specialization']): ?>
                                                        - <?php echo htmlspecialchars($doctor['specialization']); ?>
                                                    <?php endif; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="col-md-6 mb-3" id="anesthesiologist_section" style="display: none;">
                                            <label class="form-label">Anesthesiologist</label>
                                            <select name="anesthesiologist_id" class="form-select select2">
                                                <option value="">Select Anesthesiologist (Optional)</option>
                                                <?php while ($anes = $anesthesiologists->fetch_assoc()): ?>
                                                <option value="<?php echo $anes['user_id']; ?>">
                                                    Dr. <?php echo htmlspecialchars($anes['full_name']); ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label required">Procedure Date</label>
                                            <input type="date" name="procedure_date" class="form-control" 
                                                   min="<?php echo date('Y-m-d'); ?>" required>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label required">Procedure Time</label>
                                            <input type="time" name="procedure_time" class="form-control" required>
                                        </div>
                                        
                                        <div class="col-md-4 mb-3">
                                            <label class="form-label">Room Number</label>
                                            <input type="text" name="room_number" class="form-control" 
                                                   placeholder="e.g., Theatre 1, Room 205">
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Pre-Procedure Notes</label>
                                        <textarea name="pre_procedure_notes" class="form-control" rows="4" 
                                                  placeholder="Any special instructions or preparations required..."></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-lg-4">
                                <div class="info-card">
                                    <h5><i class="ri-information-line me-2"></i>Procedure Information</h5>
                                    
                                    <div id="procedure_info" class="text-muted text-center py-4">
                                        <i class="ri-file-list-3-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                                        <p class="mt-2">Select a patient and procedure to view pricing</p>
                                    </div>
                                </div>
                                
                                <div class="info-card">
                                    <div class="d-grid gap-2">
                                        <button type="submit" class="btn btn-primary-custom btn-lg">
                                            <i class="ri-calendar-check-line me-2"></i>Schedule Procedure
                                        </button>
                                        <a href="list_procedures.php" class="btn btn-light btn-lg">
                                            <i class="ri-close-line me-2"></i>Cancel
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>

                </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="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2
            $('.select2').select2({
                theme: 'bootstrap-5',
                width: '100%'
            });
            
            // Update visit_id and registration type when patient changes
            $('#patient_id').on('change', function() {
                const visitId = $(this).find(':selected').data('visit-id');
                const regType = $(this).find(':selected').data('reg-type');
                $('#visit_id').val(visitId);
                $('#patient_reg_type').val(regType);
                
                // Update pricing display if procedure already selected
                updateProcedureInfo();
            });
            
            // Show procedure information and calculate appropriate price
            $('#pricing_id').on('change', function() {
                updateProcedureInfo();
            });
            
            function updateProcedureInfo() {
                const selected = $('#pricing_id').find(':selected');
                const basePrice = parseFloat(selected.data('base-price'));
                const insurancePrice = selected.data('insurance-price');
                const corporatePrice = selected.data('corporate-price');
                const duration = selected.data('duration');
                const requiresAnesthesia = selected.data('anesthesia');
                const procedureCode = selected.data('code');
                const procedureName = selected.text().split('(')[0].split('-')[0].trim();
                const regType = $('#patient_reg_type').val();
                
                if (basePrice && regType) {
                    // Determine applicable price
                    let applicablePrice = basePrice;
                    let priceLabel = 'Base Price';
                    let priceClass = 'price-base';
                    
                    if (regType === 'INSURANCE' && insurancePrice) {
                        applicablePrice = parseFloat(insurancePrice);
                        priceLabel = 'Insurance Price';
                        priceClass = 'price-insurance';
                    } else if (regType === 'CORPORATE' && corporatePrice) {
                        applicablePrice = parseFloat(corporatePrice);
                        priceLabel = 'Corporate Price';
                        priceClass = 'price-corporate';
                    }
                    
                    let pricesHtml = '';
                    pricesHtml += '<div class="mb-2"><span class="text-muted">Base Price:</span> <strong class="float-end">KES ' + basePrice.toLocaleString() + '</strong></div>';
                    if (insurancePrice && insurancePrice > 0) {
                        pricesHtml += '<div class="mb-2"><span class="text-muted">Insurance Price:</span> <strong class="float-end">KES ' + parseFloat(insurancePrice).toLocaleString() + '</strong></div>';
                    }
                    if (corporatePrice && corporatePrice > 0) {
                        pricesHtml += '<div class="mb-2"><span class="text-muted">Corporate Price:</span> <strong class="float-end">KES ' + parseFloat(corporatePrice).toLocaleString() + '</strong></div>';
                    }
                    
                    let infoHtml = `
                        <div class="text-start">
                            <h6 class="mb-3">${procedureName}</h6>
                            ${procedureCode ? '<div class="mb-2"><span class="text-muted">Code:</span> <strong class="float-end">' + procedureCode + '</strong></div>' : ''}
                            <hr>
                            <h6 class="text-muted mb-2" style="font-size: 0.875rem;">Pricing</h6>
                            ${pricesHtml}
                            <hr>
                            <div class="alert alert-success mb-3">
                                <strong>Applicable Price:</strong><br>
                                <span class="price-badge ${priceClass}">${priceLabel}</span>
                                <div class="h4 mb-0 mt-2">KES ${applicablePrice.toLocaleString()}</div>
                            </div>
                            <div class="mb-2">
                                <span class="text-muted">Duration:</span>
                                <strong class="float-end">${duration} minutes</strong>
                            </div>
                            <div class="mb-2">
                                <span class="text-muted">Anesthesia:</span>
                                <strong class="float-end">${requiresAnesthesia == 1 ? 'Required' : 'Not Required'}</strong>
                            </div>
                        </div>
                    `;
                    $('#procedure_info').html(infoHtml);
                    
                    // Show/hide anesthesiologist field
                    if (requiresAnesthesia == 1) {
                        $('#anesthesiologist_section').show();
                    } else {
                        $('#anesthesiologist_section').hide();
                    }
                } else if (basePrice && !regType) {
                    $('#procedure_info').html(`
                        <div class="alert alert-warning">
                            <i class="ri-information-line me-1"></i>
                            <strong>Please select a patient first</strong> to see applicable pricing
                        </div>
                    `);
                } else {
                    $('#procedure_info').html(`
                        <i class="ri-file-list-3-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                        <p class="mt-2">Select a patient and procedure to view pricing</p>
                    `);
                    $('#anesthesiologist_section').hide();
                }
            }
            
            // Form validation
            $('#scheduleProcedureForm').on('submit', function(e) {
                if (!$('#visit_id').val()) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Please select a patient with an active visit'
                    });
                    return false;
                }
                
                if (!$('#patient_reg_type').val()) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Unable to determine patient registration type'
                    });
                    return false;
                }
            });
        });
    </script>
</body>
</html>
<?php $conn->close(); ?>