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

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

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

$user_id = $_SESSION['user_id'];
$patient_id = isset($_GET['patient_id']) ? (int)$_GET['patient_id'] : 0;

// Fetch patient details
if ($patient_id) {
    $patient_sql = "SELECT 
                        p.*,
                        u.full_name,
                        u.phone_primary,
                        u.email,
                        u.date_of_birth,
                        u.gender,
                        ip.provider_name,
                        ip.coverage_percentage
                    FROM patients p
                    INNER 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.patient_id = ? AND p.is_active = 1";
    
    $stmt = $conn->prepare($patient_sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $patient = $stmt->get_result()->fetch_assoc();
    
    if (!$patient) {
        $_SESSION['error_message'] = 'Patient not found or inactive';
        header('Location: list_patients.php');
        exit();
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    
    try {
        $visit_type = $_POST['visit_type'];
        $visit_source = $_POST['visit_source'];
        $registration_type = $_POST['registration_type'];
        $priority = $_POST['priority'];
        $triage_notes = trim($_POST['triage_notes']);
        $appointment_id = !empty($_POST['appointment_id']) ? (int)$_POST['appointment_id'] : null;
        
        // Generate visit number
        $visit_number_sql = "SELECT GenerateVisitNumber() as visit_number";
        $visit_number = $conn->query($visit_number_sql)->fetch_assoc()['visit_number'];
        
        // Prepare insurance details if applicable
        $insurance_details = null;
        if ($registration_type === 'INSURANCE' && $patient['insurance_provider_id']) {
            $insurance_details = json_encode([
                'provider_id' => $patient['insurance_provider_id'],
                'provider_name' => $patient['provider_name'],
                'insurance_number' => $patient['insurance_number'],
                'policy_number' => $patient['policy_number'],
                'coverage_percentage' => $patient['coverage_percentage']
            ]);
        }
        
        // Insert visit
        $insert_sql = "INSERT INTO patient_visits (
                        visit_number,
                        patient_id,
                        appointment_id,
                        visit_type,
                        visit_source,
                        registration_type,
                        insurance_details,
                        status,
                        priority,
                        triage_notes,
                        registered_by,
                        registration_date,
                        created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, 'REGISTERED', ?, ?, ?, NOW(), NOW())";
        
        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param("siissssssi",
            $visit_number,
            $patient_id,
            $appointment_id,
            $visit_type,
            $visit_source,
            $registration_type,
            $insurance_details,
            $priority,
            $triage_notes,
            $user_id
        );
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to create visit: ' . $stmt->error);
        }
        
        $visit_id = $conn->insert_id;
        
        // Log activity
        $log_sql = "INSERT INTO activity_log (
                        user_id, action, module, record_id, record_type, 
                        new_values, ip_address, user_agent, session_id, logged_at
                    ) VALUES (?, 'CREATE', 'PATIENT_VISITS', ?, 'VISIT', ?, ?, ?, ?, NOW())";
        
        $new_values = json_encode([
            'visit_number' => $visit_number,
            'patient_id' => $patient_id,
            'visit_type' => $visit_type,
            'registration_type' => $registration_type
        ]);
        
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        $session_id = session_id();
        
        $stmt = $conn->prepare($log_sql);
        $stmt->bind_param("iissss", $user_id, $visit_id, $new_values, $ip_address, $user_agent, $session_id);
        $stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = 'Patient visit registered successfully';
        
        // Redirect based on next action
        $next_action = $_POST['next_action'] ?? 'view';
        
        if ($next_action === 'consultation') {
            header("Location: new_consultation.php?visit_id=$visit_id");
        } else {
            header("Location: patient_profile.php?id=$patient_id&visit_created=1");
        }
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}

// Fetch patient's pending appointments
$appointments_sql = "SELECT 
                        appointment_id,
                        appointment_number,
                        appointment_date,
                        appointment_time,
                        appointment_type
                    FROM appointments
                    WHERE patient_id = ?
                    AND status IN ('SCHEDULED', 'CONFIRMED')
                    AND appointment_date >= CURDATE()
                    ORDER BY appointment_date ASC, appointment_time ASC
                    LIMIT 5";

$stmt = $conn->prepare($appointments_sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$appointments = $stmt->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Register Patient Visit')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #3b82f6;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --info: #06b6d4;
        }

        .page-header {
            background: linear-gradient(135deg, var(--primary) 0%, #2563eb 100%);
            color: white;
            border-radius: 16px;
            padding: 2rem;
            margin-bottom: 2rem;
        }

        .patient-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
            border-left: 4px solid var(--info);
        }

        .form-section {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }

        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .form-label {
            font-weight: 600;
            color: #475569;
            margin-bottom: 0.5rem;
        }

        .required::after {
            content: '*';
            color: var(--danger);
            margin-left: 0.25rem;
        }

        .radio-card {
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            padding: 1rem;
            cursor: pointer;
            transition: all 0.2s;
        }

        .radio-card:hover {
            border-color: var(--primary);
            background: #f0f9ff;
        }

        .radio-card input[type="radio"]:checked + label {
            color: var(--primary);
            font-weight: 600;
        }

        .radio-card input[type="radio"]:checked ~ * {
            border-color: var(--primary);
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
        }

        .info-item {
            padding: 0.75rem;
            background: #f8fafc;
            border-radius: 8px;
        }

        .info-item small {
            display: block;
            color: #64748b;
            font-size: 0.75rem;
            margin-bottom: 0.25rem;
            text-transform: uppercase;
            font-weight: 600;
        }

        .info-item div {
            color: #1e293b;
            font-weight: 500;
        }
    </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 Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h1 class="mb-1">
                                    <i class="ri-hospital-line me-2"></i>
                                    Register Patient Visit
                                </h1>
                                <p class="mb-0 opacity-90">Create a new visit record for patient consultation</p>
                            </div>
                            <a href="list_patients.php" class="btn btn-light">
                                <i class="ri-arrow-left-line me-1"></i> Back to Patients
                            </a>
                        </div>
                    </div>

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

                    <?php if ($patient): ?>
                    
                    <!-- Patient Information -->
                    <div class="patient-card">
                        <h5 class="mb-3">
                            <i class="ri-user-heart-line me-2"></i>
                            Patient Information
                        </h5>
                        <div class="info-grid">
                            <div class="info-item">
                                <small>Full Name</small>
                                <div><?php echo htmlspecialchars($patient['full_name']); ?></div>
                            </div>
                            <div class="info-item">
                                <small>Patient Number</small>
                                <div><?php echo htmlspecialchars($patient['patient_number']); ?></div>
                            </div>
                            <div class="info-item">
                                <small>Phone</small>
                                <div><?php echo htmlspecialchars($patient['phone_primary']); ?></div>
                            </div>
                            <div class="info-item">
                                <small>Age / Gender</small>
                                <div>
                                    <?php 
                                    if ($patient['date_of_birth']) {
                                        $dob = new DateTime($patient['date_of_birth']);
                                        $now = new DateTime();
                                        echo $now->diff($dob)->y . ' years';
                                    } else {
                                        echo 'N/A';
                                    }
                                    echo ' / ' . ucfirst(strtolower($patient['gender']));
                                    ?>
                                </div>
                            </div>
                            <div class="info-item">
                                <small>Registration Type</small>
                                <div><?php echo str_replace('_', ' ', $patient['registration_type']); ?></div>
                            </div>
                            <?php if ($patient['provider_name']): ?>
                            <div class="info-item">
                                <small>Insurance Provider</small>
                                <div><?php echo htmlspecialchars($patient['provider_name']); ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <!-- Visit Registration Form -->
                    <form method="POST" id="visitForm">
                        <div class="form-section">
                            <div class="section-title">
                                <i class="ri-file-list-3-line"></i>
                                Visit Details
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">Visit Type</label>
                                    <select class="form-select" name="visit_type" required>
                                        <option value="">Select Visit Type</option>
                                        <option value="CONSULTATION">Consultation</option>
                                        <option value="FOLLOW_UP">Follow-up</option>
                                        <option value="EMERGENCY">Emergency</option>
                                        <option value="PROCEDURE">Procedure</option>
                                        <option value="ADMISSION">Admission</option>
                                    </select>
                                </div>

                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">Visit Source</label>
                                    <select class="form-select" name="visit_source" required>
                                        <option value="">Select Source</option>
                                        <option value="WALK_IN">Walk-in</option>
                                        <option value="APPOINTMENT">From Appointment</option>
                                        <option value="REFERRAL">Referral</option>
                                        <option value="EMERGENCY">Emergency</option>
                                        <option value="TELEMEDICINE">Telemedicine</option>
                                    </select>
                                </div>

                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">Registration/Payment Type</label>
                                    <select class="form-select" name="registration_type" required>
                                        <option value="">Select Type</option>
                                        <option value="CASH">Cash Payment</option>
                                        <option value="INSURANCE" <?php echo $patient['insurance_provider_id'] ? '' : 'disabled'; ?>>
                                            Insurance <?php echo !$patient['insurance_provider_id'] ? '(Not Available)' : ''; ?>
                                        </option>
                                        <option value="CORPORATE">Corporate</option>
                                        <option value="NHIF">NHIF</option>
                                        <option value="CHARITY">Charity/Free</option>
                                    </select>
                                </div>

                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">Priority</label>
                                    <select class="form-select" name="priority" required>
                                        <option value="NORMAL">Normal</option>
                                        <option value="URGENT">Urgent</option>
                                        <option value="EMERGENCY">Emergency</option>
                                    </select>
                                </div>

                                <?php if ($appointments->num_rows > 0): ?>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Link to Appointment (Optional)</label>
                                    <select class="form-select" name="appointment_id">
                                        <option value="">No appointment selected</option>
                                        <?php while ($apt = $appointments->fetch_assoc()): ?>
                                        <option value="<?php echo $apt['appointment_id']; ?>">
                                            <?php echo $apt['appointment_number']; ?> - 
                                            <?php echo date('M d, Y h:i A', strtotime($apt['appointment_date'] . ' ' . $apt['appointment_time'])); ?> -
                                            <?php echo $apt['appointment_type']; ?>
                                        </option>
                                        <?php endwhile; ?>
                                    </select>
                                    <small class="text-muted">Select if this visit is related to a scheduled appointment</small>
                                </div>
                                <?php endif; ?>

                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Triage / Initial Notes</label>
                                    <textarea class="form-control" name="triage_notes" rows="4" 
                                              placeholder="Enter vital signs, chief complaint, or initial observations..."></textarea>
                                    <small class="text-muted">Document initial assessment or reason for visit</small>
                                </div>
                            </div>
                        </div>

                        <!-- Next Action -->
                        <div class="form-section">
                            <div class="section-title">
                                <i class="ri-direction-line"></i>
                                Next Action
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <div class="radio-card">
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="next_action" 
                                                   value="consultation" id="actionConsultation" checked>
                                            <label class="form-check-label" for="actionConsultation">
                                                <strong>Proceed to Consultation</strong>
                                                <p class="mb-0 small text-muted">Start consultation immediately</p>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <div class="radio-card">
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="next_action" 
                                                   value="view" id="actionView">
                                            <label class="form-check-label" for="actionView">
                                                <strong>View Patient Profile</strong>
                                                <p class="mb-0 small text-muted">Return to patient details</p>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Submit Buttons -->
                        <div class="form-section">
                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-success btn-lg">
                                    <i class="ri-check-line me-2"></i>Register Visit
                                </button>
                                <a href="list_patients.php" class="btn btn-secondary btn-lg">
                                    <i class="ri-close-line me-1"></i>Cancel
                                </a>
                            </div>
                        </div>
                    </form>

                    <?php else: ?>
                    <div class="alert alert-warning">
                        <i class="ri-error-warning-line me-2"></i>
                        Patient not found. Please select a valid patient from the patient list.
                    </div>
                    <?php endif; ?>
                </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>
    $('#visitForm').on('submit', function(e) {
        e.preventDefault();
        
        Swal.fire({
            title: 'Register Visit?',
            text: 'Create a new visit record for this patient?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Register',
            confirmButtonColor: '#10b981'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Registering Visit...',
                    html: 'Please wait',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
                this.submit();
            }
        });
    });
    </script>

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