<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'RECEPTIONIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$errors = [];
$success_message = '';

// Fetch insurance providers
$insurance_providers_sql = "SELECT provider_id, provider_name, provider_code, coverage_percentage FROM insurance_providers WHERE is_active = 1 ORDER BY provider_name";
$insurance_providers = $conn->query($insurance_providers_sql);

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $patient_search = trim($_POST['patient_search'] ?? '');
    $patient_id = $_POST['patient_id'] ?? '';
    $visit_type = $_POST['visit_type'] ?? '';
    $visit_source = $_POST['visit_source'] ?? '';
    $registration_type = $_POST['registration_type'] ?? '';
    $priority = $_POST['priority'] ?? 'NORMAL';
    $triage_notes = trim($_POST['triage_notes'] ?? '');
    
    // Insurance details
    $insurance_provider_id = $_POST['insurance_provider_id'] ?? null;
    $insurance_number = trim($_POST['insurance_number'] ?? '');
    $policy_holder_name = trim($_POST['policy_holder_name'] ?? '');
    $employer_name = trim($_POST['employer_name'] ?? '');
    
    // Vitals
    $temperature = $_POST['temperature'] ?? '';
    $blood_pressure_systolic = $_POST['blood_pressure_systolic'] ?? '';
    $blood_pressure_diastolic = $_POST['blood_pressure_diastolic'] ?? '';
    $heart_rate = $_POST['heart_rate'] ?? '';
    $respiratory_rate = $_POST['respiratory_rate'] ?? '';
    $weight = $_POST['weight'] ?? '';
    $height = $_POST['height'] ?? '';
    $oxygen_saturation = $_POST['oxygen_saturation'] ?? '';
    
    // Validation
    if (empty($patient_id)) {
        $errors[] = "Please select a patient";
    }
    
    if (empty($visit_type)) {
        $errors[] = "Visit type is required";
    }
    
    if (empty($visit_source)) {
        $errors[] = "Visit source is required";
    }
    
    if (empty($registration_type)) {
        $errors[] = "Registration type is required";
    }
    
    // Insurance validation
    if ($registration_type === 'INSURANCE') {
        if (empty($insurance_provider_id)) {
            $errors[] = "Insurance provider is required for insurance registration";
        }
        if (empty($insurance_number)) {
            $errors[] = "Insurance number is required for insurance registration";
        }
    }
    
    // Check if patient already has an active visit today
    if (empty($errors)) {
        $active_visit_sql = "SELECT visit_id FROM patient_visits 
                            WHERE patient_id = ? AND DATE(registration_date) = CURDATE() 
                            AND status IN ('REGISTERED', 'WAITING', 'IN_CONSULTATION')";
        $stmt = $conn->prepare($active_visit_sql);
        $stmt->bind_param("i", $patient_id);
        $stmt->execute();
        
        if ($stmt->get_result()->num_rows > 0) {
            $errors[] = "Patient already has an active visit today";
        }
    }
    
    // If no errors, register the visit
    if (empty($errors)) {
        try {
            $conn->begin_transaction();
            
            // Get patient details for calculations
            $patient_details_sql = "SELECT p.*, ip.coverage_percentage 
                                   FROM patients p 
                                   LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id 
                                   WHERE p.patient_id = ?";
            $stmt = $conn->prepare($patient_details_sql);
            $stmt->bind_param("i", $patient_id);
            $stmt->execute();
            $patient_details = $stmt->get_result()->fetch_assoc();
            
            // Calculate estimated amounts based on registration type
            $consultation_fee = 3000; // Default ENT consultation fee
            $total_amount = $consultation_fee;
            $insurance_covered = 0;
            $patient_portion = $total_amount;
            
            if ($registration_type === 'INSURANCE' && $insurance_provider_id) {
                $provider_sql = "SELECT coverage_percentage FROM insurance_providers WHERE provider_id = ?";
                $stmt = $conn->prepare($provider_sql);
                $stmt->bind_param("i", $insurance_provider_id);
                $stmt->execute();
                $coverage = $stmt->get_result()->fetch_assoc();
                
                if ($coverage) {
                    $coverage_percent = $coverage['coverage_percentage'] / 100;
                    $insurance_covered = $total_amount * $coverage_percent;
                    $patient_portion = $total_amount - $insurance_covered;
                }
            }
            
            // Generate visit number
            $visit_number_sql = "SELECT GenerateVisitNumber() as visit_number";
            $visit_number_result = $conn->query($visit_number_sql);
            $visit_number = $visit_number_result->fetch_assoc()['visit_number'];
            
            // Prepare insurance details JSON
            $insurance_details = null;
            if ($registration_type === 'INSURANCE') {
                $insurance_details = json_encode([
                    'provider_id' => $insurance_provider_id,
                    'insurance_number' => $insurance_number,
                    'policy_holder_name' => $policy_holder_name,
                    'employer_name' => $employer_name
                ]);
            }
            
            // Prepare vital signs JSON
            $vital_signs = json_encode([
                'temperature' => $temperature,
                'blood_pressure' => [
                    'systolic' => $blood_pressure_systolic,
                    'diastolic' => $blood_pressure_diastolic
                ],
                'heart_rate' => $heart_rate,
                'respiratory_rate' => $respiratory_rate,
                'weight' => $weight,
                'height' => $height,
                'oxygen_saturation' => $oxygen_saturation,
                'recorded_by' => $user_id,
                'recorded_at' => date('Y-m-d H:i:s')
            ]);
            
            // Insert visit record
            $visit_sql = "INSERT INTO patient_visits (visit_number, patient_id, visit_type, visit_source, 
                         registration_type, insurance_details, total_amount, insurance_covered, 
                         patient_portion, balance, status, priority, triage_notes, vital_signs, 
                         registered_by, registration_date, created_at) 
                         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'REGISTERED', ?, ?, ?, ?, NOW(), NOW())";
            
            $stmt = $conn->prepare($visit_sql);
            $stmt->bind_param("sisssddddssssi", 
                $visit_number, $patient_id, $visit_type, $visit_source, $registration_type, 
                $insurance_details, $total_amount, $insurance_covered, $patient_portion, 
                $patient_portion, $priority, $triage_notes, $vital_signs, $user_id
            );
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to register visit");
            }
            
            $visit_id = $conn->insert_id;
            
            // Log the activity
            $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                           new_values, ip_address, logged_at) 
                           VALUES (?, 'CREATE', 'VISIT', ?, 'VISIT', ?, ?, NOW())";
            
            $new_values = json_encode([
                'visit_number' => $visit_number,
                'patient_id' => $patient_id,
                'visit_type' => $visit_type,
                'registration_type' => $registration_type,
                'total_amount' => $total_amount
            ]);
            
            $ip_address = $_SERVER['REMOTE_ADDR'];
            
            $stmt = $conn->prepare($activity_sql);
            $stmt->bind_param("iiss", $user_id, $visit_id, $new_values, $ip_address);
            $stmt->execute();
            
            $conn->commit();
            
            $success_message = "Visit registered successfully! Visit Number: " . $visit_number;
            
            // Clear form data after successful submission
            $_POST = array();
            
        } catch (Exception $e) {
            $conn->rollback();
            $errors[] = "Registration failed: " . $e->getMessage();
        }
    }
}

// AJAX endpoint for patient search
if (isset($_GET['action']) && $_GET['action'] === 'search_patients') {
    $search_term = $_GET['term'] ?? '';
    
    if (strlen($search_term) >= 2) {
        $search_sql = "SELECT p.patient_id, p.patient_number, u.full_name, u.phone_primary, 
                      p.insurance_provider_id, ip.provider_name, p.insurance_number
                      FROM patients p 
                      JOIN users u ON p.user_id = u.user_id 
                      LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
                      WHERE p.is_active = 1 
                      AND (u.full_name LIKE ? OR p.patient_number LIKE ? OR u.phone_primary LIKE ?) 
                      ORDER BY u.full_name LIMIT 10";
        
        $search_term_like = '%' . $search_term . '%';
        $stmt = $conn->prepare($search_sql);
        $stmt->bind_param("sss", $search_term_like, $search_term_like, $search_term_like);
        $stmt->execute();
        $result = $stmt->get_result();
        
        $patients = [];
        while ($row = $result->fetch_assoc()) {
            $patients[] = [
                'id' => $row['patient_id'],
                'text' => $row['full_name'] . ' (' . $row['patient_number'] . ') - ' . $row['phone_primary'],
                'insurance_provider_id' => $row['insurance_provider_id'],
                'provider_name' => $row['provider_name'],
                'insurance_number' => $row['insurance_number']
            ];
        }
        
        header('Content-Type: application/json');
        echo json_encode($patients);
        exit();
    }
    
    header('Content-Type: application/json');
    echo json_encode([]);
    exit();
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Register Visit')); ?>
    <?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" />
    
    <style>
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            border-radius: 12px 12px 0 0;
        }
        
        .form-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .form-body {
            padding: 1.5rem;
        }
        
        .registration-type-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .registration-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .registration-card:hover {
            border-color: #059669;
            background: #f0fdf4;
        }
        
        .registration-card.active {
            border-color: #059669;
            background: #ecfdf5;
        }
        
        .registration-icon {
            font-size: 2rem;
            margin-bottom: 0.5rem;
            color: #059669;
        }
        
        .visit-type-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .visit-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .visit-card:hover {
            border-color: #3b82f6;
            background: #f8faff;
        }
        
        .visit-card.active {
            border-color: #3b82f6;
            background: #eff6ff;
        }
        
        .visit-icon {
            font-size: 1.5rem;
            margin-bottom: 0.5rem;
            color: #3b82f6;
        }
        
        .priority-cards {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .priority-card {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .priority-card:hover {
            border-color: #6b7280;
            background: #f9fafb;
        }
        
        .priority-card.active {
            border-color: #6b7280;
            background: #f3f4f6;
        }
        
        .priority-card.normal { border-color: #10b981; }
        .priority-card.normal.active { background: #ecfdf5; border-color: #10b981; }
        
        .priority-card.urgent { border-color: #f59e0b; }
        .priority-card.urgent.active { background: #fffbeb; border-color: #f59e0b; }
        
        .priority-card.emergency { border-color: #ef4444; }
        .priority-card.emergency.active { background: #fef2f2; border-color: #ef4444; }
        
        .vitals-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }
        
        .insurance-fields {
            display: none;
            animation: fadeIn 0.3s ease-in;
        }
        
        .insurance-fields.show {
            display: block;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .select2-container {
            width: 100% !important;
        }
        
        .select2-selection {
            border: 1px solid #d1d5db !important;
            border-radius: 8px !important;
            height: 42px !important;
        }
        
        .select2-selection__rendered {
            line-height: 40px !important;
            padding-left: 12px !important;
        }
        
        .select2-selection__arrow {
            height: 40px !important;
        }
        
        .required {
            color: #ef4444;
        }
        
        .patient-info-card {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
            display: none;
        }
        
        .patient-info-card.show {
            display: block;
            animation: fadeIn 0.3s ease-in;
        }
    </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">Register Patient Visit</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="todays_visits.php">Visits</a></li>
                                        <li class="breadcrumb-item active">Register Visit</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alerts -->
                    <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Registration Failed!</strong>
                        <ul class="mb-0 mt-2">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo htmlspecialchars($error); ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>Success!</strong> <?php echo htmlspecialchars($success_message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Visit Registration Form -->
                    <form id="visitRegistrationForm" method="POST" action="">
                        <!-- Patient Selection -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Select Patient</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-8 mb-3">
                                        <label class="form-label">Search Patient <span class="required">*</span></label>
                                        <select class="form-control" id="patientSelect" name="patient_id" required>
                                            <option value="">Search by name, patient number, or phone...</option>
                                        </select>
                                        <small class="text-muted">Type at least 2 characters to search</small>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">&nbsp;</label>
                                        <div>
                                            <a href="register_patient.php" class="btn btn-outline-primary w-100">
                                                <i class="ri-user-add-line me-1"></i> Register New Patient
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Patient Info Display -->
                                <div id="patientInfo" class="patient-info-card">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <h6 class="text-primary mb-2">Patient Information</h6>
                                            <p class="mb-1"><strong>Name:</strong> <span id="patientName">-</span></p>
                                            <p class="mb-1"><strong>Patient #:</strong> <span id="patientNumber">-</span></p>
                                            <p class="mb-0"><strong>Phone:</strong> <span id="patientPhone">-</span></p>
                                        </div>
                                        <div class="col-md-6">
                                            <h6 class="text-primary mb-2">Insurance Information</h6>
                                            <p class="mb-1"><strong>Provider:</strong> <span id="insuranceProvider">-</span></p>
                                            <p class="mb-0"><strong>Insurance #:</strong> <span id="insuranceNumber">-</span></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Visit Type Selection -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Visit Type & Source</h5>
                            </div>
                            <div class="form-body">
                                <h6 class="mb-3">Visit Type <span class="required">*</span></h6>
                                <div class="visit-type-cards">
                                    <div class="visit-card" data-type="CONSULTATION">
                                        <div class="visit-icon">👨‍⚕️</div>
                                        <h6>Consultation</h6>
                                        <input type="radio" name="visit_type" value="CONSULTATION" style="display: none;">
                                    </div>
                                    <div class="visit-card" data-type="FOLLOW_UP">
                                        <div class="visit-icon">🔄</div>
                                        <h6>Follow-up</h6>
                                        <input type="radio" name="visit_type" value="FOLLOW_UP" style="display: none;">
                                    </div>
                                    <div class="visit-card" data-type="EMERGENCY">
                                        <div class="visit-icon">🚨</div>
                                        <h6>Emergency</h6>
                                        <input type="radio" name="visit_type" value="EMERGENCY" style="display: none;">
                                    </div>
                                    <div class="visit-card" data-type="PROCEDURE">
                                        <div class="visit-icon">⚕️</div>
                                        <h6>Procedure</h6>
                                        <input type="radio" name="visit_type" value="PROCEDURE" style="display: none;">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Visit Source <span class="required">*</span></label>
                                        <select class="form-select" name="visit_source" required>
                                            <option value="">Select Visit Source</option>
                                            <option value="WALK_IN">Walk-in</option>
                                            <option value="APPOINTMENT">Appointment</option>
                                            <option value="REFERRAL">Referral</option>
                                            <option value="EMERGENCY">Emergency</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Registration Type -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Registration Type</h5>
                            </div>
                            <div class="form-body">
                                <div class="registration-type-cards">
                                    <div class="registration-card" data-type="CASH">
                                        <div class="registration-icon">💰</div>
                                        <h6>Cash Payment</h6>
                                        <p class="text-muted small mb-0">Direct payment</p>
                                        <input type="radio" name="registration_type" value="CASH" style="display: none;">
                                    </div>
                                    <div class="registration-card" data-type="INSURANCE">
                                        <div class="registration-icon">🛡️</div>
                                        <h6>Insurance</h6>
                                        <p class="text-muted small mb-0">Medical insurance</p>
                                        <input type="radio" name="registration_type" value="INSURANCE" style="display: none;">
                                    </div>
                                    <div class="registration-card" data-type="CORPORATE">
                                        <div class="registration-icon">🏢</div>
                                        <h6>Corporate</h6>
                                        <p class="text-muted small mb-0">Company sponsored</p>
                                        <input type="radio" name="registration_type" value="CORPORATE" style="display: none;">
                                    </div>
                                    <div class="registration-card" data-type="NHIF">
                                        <div class="registration-icon">🏥</div>
                                        <h6>NHIF</h6>
                                        <p class="text-muted small mb-0">National insurance</p>
                                        <input type="radio" name="registration_type" value="NHIF" style="display: none;">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Insurance Information (shown when Insurance is selected) -->
                        <div class="form-card insurance-fields" id="insuranceFields">
                            <div class="form-header">
                                <h5 class="form-title">Insurance Details</h5>
                            </div>
                            <div class="form-body">
                                <div class="row">
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Insurance Provider <span class="required">*</span></label>
                                        <select class="form-select" name="insurance_provider_id" id="insuranceProviderSelect">
                                            <option value="">Select Provider</option>
                                            <?php while ($provider = $insurance_providers->fetch_assoc()): ?>
                                                <option value="<?php echo $provider['provider_id']; ?>" 
                                                        data-coverage="<?php echo $provider['coverage_percentage']; ?>">
                                                    <?php echo htmlspecialchars($provider['provider_name'] . ' (' . $provider['provider_code'] . ')'); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Insurance Number <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="insurance_number" 
                                               placeholder="Member number">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Policy Holder Name</label>
                                        <input type="text" class="form-control" name="policy_holder_name" 
                                               placeholder="Policy holder name">
                                    </div>
                                    <div class="col-md-3 mb-3">
                                        <label class="form-label">Employer</label>
                                        <input type="text" class="form-control" name="employer_name" 
                                               placeholder="Employer name">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Priority Level -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Priority Level</h5>
                            </div>
                            <div class="form-body">
                                <div class="priority-cards">
                                    <div class="priority-card normal active" data-priority="NORMAL">
                                        <div style="font-size: 1.5rem; color: #10b981;">✅</div>
                                        <h6>Normal</h6>
                                        <p class="text-muted small mb-0">Regular visit</p>
                                        <input type="radio" name="priority" value="NORMAL" checked style="display: none;">
                                    </div>
                                    <div class="priority-card urgent" data-priority="URGENT">
                                        <div style="font-size: 1.5rem; color: #f59e0b;">⚠️</div>
                                        <h6>Urgent</h6>
                                        <p class="text-muted small mb-0">Needs attention</p>
                                        <input type="radio" name="priority" value="URGENT" style="display: none;">
                                    </div>
                                    <div class="priority-card emergency" data-priority="EMERGENCY">
                                        <div style="font-size: 1.5rem; color: #ef4444;">🚨</div>
                                        <h6>Emergency</h6>
                                        <p class="text-muted small mb-0">Immediate care</p>
                                        <input type="radio" name="priority" value="EMERGENCY" style="display: none;">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Vital Signs -->
                        <div class="form-card">
                            <div class="form-header">
                                <h5 class="form-title">Vital Signs & Triage</h5>
                            </div>
                            <div class="form-body">
                                <div class="vitals-grid mb-4">
                                    <div>
                                        <label class="form-label">Temperature (°C)</label>
                                        <input type="number" step="0.1" class="form-control" name="temperature" 
                                               placeholder="36.5" min="30" max="45">
                                    </div>
                                    <div>
                                        <label class="form-label">Blood Pressure (mmHg)</label>
                                        <div class="input-group">
                                            <input type="number" class="form-control" name="blood_pressure_systolic" 
                                                   placeholder="120" min="60" max="300">
                                            <span class="input-group-text">/</span>
                                            <input type="number" class="form-control" name="blood_pressure_diastolic" 
                                                   placeholder="80" min="40" max="200">
                                        </div>
                                    </div>
                                    <div>
                                        <label class="form-label">Heart Rate (bpm)</label>
                                        <input type="number" class="form-control" name="heart_rate" 
                                               placeholder="72" min="40" max="200">
                                    </div>
                                    <div>
                                        <label class="form-label">Respiratory Rate (/min)</label>
                                        <input type="number" class="form-control" name="respiratory_rate" 
                                               placeholder="16" min="8" max="60">
                                    </div>
                                    <div>
                                        <label class="form-label">Weight (kg)</label>
                                        <input type="number" step="0.1" class="form-control" name="weight" 
                                               placeholder="70.0" min="1" max="300">
                                    </div>
                                    <div>
                                        <label class="form-label">Height (cm)</label>
                                        <input type="number" class="form-control" name="height" 
                                               placeholder="170" min="50" max="250">
                                    </div>
                                    <div>
                                        <label class="form-label">Oxygen Saturation (%)</label>
                                        <input type="number" class="form-control" name="oxygen_saturation" 
                                               placeholder="98" min="70" max="100">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-12 mb-3">
                                        <label class="form-label">Triage Notes</label>
                                        <textarea class="form-control" name="triage_notes" rows="3" 
                                                  placeholder="Initial assessment notes, chief complaint, observations..."><?php echo htmlspecialchars($_POST['triage_notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="form-card">
                            <div class="form-body">
                                <div class="d-flex justify-content-between">
                                    <a href="todays_visits.php" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line me-1"></i> Back to Visits
                                    </a>
                                    <div>
                                        <button type="button" class="btn btn-secondary me-2" onclick="clearForm()">
                                            <i class="ri-refresh-line me-1"></i> Clear Form
                                        </button>
                                        <button type="submit" class="btn btn-success">
                                            <i class="ri-check-line me-1"></i> Register Visit
                                        </button>
                                    </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>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize Select2 for patient search
        $('#patientSelect').select2({
            ajax: {
                url: 'register_visit.php?action=search_patients',
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        term: params.term
                    };
                },
                processResults: function (data) {
                    return {
                        results: data
                    };
                },
                cache: true
            },
            minimumInputLength: 2,
            placeholder: 'Search by name, patient number, or phone...'
        });
        
        // Handle patient selection
        $('#patientSelect').on('select2:select', function (e) {
            const data = e.params.data;
            const patientInfo = document.getElementById('patientInfo');
            
            // Show patient info
            patientInfo.classList.add('show');
            
            // Update patient info display
            document.getElementById('patientName').textContent = data.text.split(' (')[0];
            document.getElementById('patientNumber').textContent = data.text.match(/\(([^)]+)\)/)[1];
            document.getElementById('patientPhone').textContent = data.text.split('- ')[1];
            document.getElementById('insuranceProvider').textContent = data.provider_name || 'None';
            document.getElementById('insuranceNumber').textContent = data.insurance_number || 'None';
            
            // Pre-fill insurance fields if patient has insurance
            if (data.insurance_provider_id) {
                document.getElementById('insuranceProviderSelect').value = data.insurance_provider_id;
                document.querySelector('input[name="insurance_number"]').value = data.insurance_number || '';
                
                // Auto-select insurance registration type
                document.querySelector('[data-type="INSURANCE"]').click();
            }
        });
        
        // Visit type selection
        const visitCards = document.querySelectorAll('.visit-card');
        visitCards.forEach(card => {
            card.addEventListener('click', function() {
                visitCards.forEach(c => c.classList.remove('active'));
                this.classList.add('active');
                const radioInput = this.querySelector('input[type="radio"]');
                radioInput.checked = true;
            });
        });
        
        // Registration type selection
        const registrationCards = document.querySelectorAll('.registration-card');
        const insuranceFields = document.getElementById('insuranceFields');
        
        registrationCards.forEach(card => {
            card.addEventListener('click', function() {
                registrationCards.forEach(c => c.classList.remove('active'));
                this.classList.add('active');
                const radioInput = this.querySelector('input[type="radio"]');
                radioInput.checked = true;
                
                const type = this.getAttribute('data-type');
                
                // Show/hide insurance fields
                if (type === 'INSURANCE' || type === 'NHIF') {
                    insuranceFields.classList.add('show');
                    document.getElementById('insuranceProviderSelect').required = true;
                    document.querySelector('input[name="insurance_number"]').required = true;
                } else {
                    insuranceFields.classList.remove('show');
                    document.getElementById('insuranceProviderSelect').required = false;
                    document.querySelector('input[name="insurance_number"]').required = false;
                }
            });
        });
        
        // Priority level selection
        const priorityCards = document.querySelectorAll('.priority-card');
        priorityCards.forEach(card => {
            card.addEventListener('click', function() {
                priorityCards.forEach(c => c.classList.remove('active'));
                this.classList.add('active');
                const radioInput = this.querySelector('input[type="radio"]');
                radioInput.checked = true;
            });
        });
        
        // Form validation
        const form = document.getElementById('visitRegistrationForm');
        form.addEventListener('submit', function(e) {
            // Check if patient is selected
            if (!document.querySelector('select[name="patient_id"]').value) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Patient Required',
                    text: 'Please select a patient for the visit.'
                });
                return;
            }
            
            // Check if visit type is selected
            if (!document.querySelector('input[name="visit_type"]:checked')) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Visit Type Required',
                    text: 'Please select a visit type.'
                });
                return;
            }
            
            // Check if registration type is selected
            if (!document.querySelector('input[name="registration_type"]:checked')) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Registration Type Required',
                    text: 'Please select a registration type.'
                });
                return;
            }
            
            // Validate insurance fields if insurance registration
            const registrationType = document.querySelector('input[name="registration_type"]:checked').value;
            if (registrationType === 'INSURANCE' || registrationType === 'NHIF') {
                const insuranceProvider = document.getElementById('insuranceProviderSelect').value;
                const insuranceNumber = document.querySelector('input[name="insurance_number"]').value;
                
                if (!insuranceProvider || !insuranceNumber) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'warning',
                        title: 'Insurance Information Required',
                        text: 'Please fill in the insurance provider and insurance number.'
                    });
                    return;
                }
            }
            
            // Validate vitals ranges
            const temperature = parseFloat(document.querySelector('input[name="temperature"]').value);
            if (temperature && (temperature < 30 || temperature > 45)) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Invalid Temperature',
                    text: 'Please enter a valid temperature (30-45°C).'
                });
                return;
            }
            
            const systolic = parseInt(document.querySelector('input[name="blood_pressure_systolic"]').value);
            const diastolic = parseInt(document.querySelector('input[name="blood_pressure_diastolic"]').value);
            if (systolic && diastolic && systolic <= diastolic) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Invalid Blood Pressure',
                    text: 'Systolic pressure should be higher than diastolic pressure.'
                });
                return;
            }
            
            // Show loading state
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="ri-loader-2-line me-1 spin"></i> Registering...';
            submitBtn.disabled = true;
            
            // Re-enable button after a delay in case of errors
            setTimeout(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }, 5000);
        });
        
        // Calculate BMI when weight and height are entered
        const weightInput = document.querySelector('input[name="weight"]');
        const heightInput = document.querySelector('input[name="height"]');
        
        function calculateBMI() {
            const weight = parseFloat(weightInput.value);
            const height = parseFloat(heightInput.value);
            
            if (weight && height) {
                const heightInMeters = height / 100;
                const bmi = weight / (heightInMeters * heightInMeters);
                
                // You can add a BMI display element if needed
                console.log('BMI:', bmi.toFixed(1));
            }
        }
        
        weightInput?.addEventListener('input', calculateBMI);
        heightInput?.addEventListener('input', calculateBMI);
        
        // Set initial values if form was submitted with errors
        <?php if (!empty($_POST['visit_type'])): ?>
        document.querySelector('[data-type="<?php echo $_POST['visit_type']; ?>"]')?.click();
        <?php endif; ?>
        
        <?php if (!empty($_POST['registration_type'])): ?>
        document.querySelector('[data-type="<?php echo $_POST['registration_type']; ?>"]')?.click();
        <?php endif; ?>
        
        <?php if (!empty($_POST['priority'])): ?>
        document.querySelector('[data-priority="<?php echo $_POST['priority']; ?>"]')?.click();
        <?php endif; ?>
        
        // Auto-fill current date and time for emergency visits
        document.querySelector('[data-type="EMERGENCY"]')?.addEventListener('click', function() {
            document.querySelector('[data-priority="EMERGENCY"]')?.click();
        });
    });
    
    // Clear form function
    function clearForm() {
        Swal.fire({
            title: 'Clear Form?',
            text: 'This will clear all entered data. Are you sure?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, clear it!'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('visitRegistrationForm').reset();
                $('#patientSelect').val(null).trigger('change');
                
                // Reset all cards
                document.querySelectorAll('.visit-card, .registration-card, .priority-card').forEach(card => {
                    card.classList.remove('active');
                });
                
                // Set default priority to normal
                document.querySelector('[data-priority="NORMAL"]').classList.add('active');
                document.querySelector('input[value="NORMAL"]').checked = true;
                
                // Hide patient info and insurance fields
                document.getElementById('patientInfo').classList.remove('show');
                document.getElementById('insuranceFields').classList.remove('show');
                
                Swal.fire({
                    icon: 'success',
                    title: 'Form Cleared',
                    text: 'All fields have been cleared.',
                    timer: 1500,
                    showConfirmButton: false
                });
            }
        });
    }
    
    // Add CSS for loading animation
    const style = document.createElement('style');
    style.textContent = `
        .spin {
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
    `;
    document.head.appendChild(style);
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>