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

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

if (!$patient_id) {
    header('Location: list_patients.php');
    exit();
}

// Fetch patient details
$patient_sql = "SELECT 
                    p.*, u.*
                FROM patients p
                INNER JOIN users u ON p.user_id = u.user_id
                WHERE p.patient_id = ?";
$stmt = $conn->prepare($patient_sql);
$stmt->bind_param('i', $patient_id);
$stmt->execute();
$result = $stmt->get_result();

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

$patient = $result->fetch_assoc();

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    
    try {
        // Validate required fields
        $full_name = trim($_POST['full_name']);
        $phone_primary = trim($_POST['phone_primary']);
        $email = trim($_POST['email']);
        $date_of_birth = $_POST['date_of_birth'];
        $gender = $_POST['gender'];
        $registration_type = $_POST['registration_type'];
        
        if (empty($full_name) || empty($phone_primary) || empty($date_of_birth) || empty($gender)) {
            throw new Exception('Please fill all required fields');
        }
        
        // Check if email is being changed and if it's already in use
        if ($email !== $patient['email']) {
            $email_check = $conn->prepare("SELECT user_id FROM users WHERE email = ? AND user_id != ?");
            $email_check->bind_param('si', $email, $patient['user_id']);
            $email_check->execute();
            if ($email_check->get_result()->num_rows > 0) {
                throw new Exception('Email address is already in use');
            }
        }
        
        // Update users table
        $update_user_sql = "UPDATE users SET
                            full_name = ?,
                            email = ?,
                            phone_primary = ?,
                            phone_secondary = ?,
                            date_of_birth = ?,
                            gender = ?,
                            national_id = ?,
                            address = ?,
                            emergency_contact_name = ?,
                            emergency_contact_phone = ?,
                            updated_at = NOW()
                          WHERE user_id = ?";
        
        $stmt = $conn->prepare($update_user_sql);
        $stmt->bind_param('ssssssssssi',
            $full_name,
            $email,
            $phone_primary,
            $_POST['phone_secondary'],
            $date_of_birth,
            $gender,
            $_POST['national_id'],
            $_POST['address'],
            $_POST['emergency_contact_name'],
            $_POST['emergency_contact_phone'],
            $patient['user_id']
        );
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to update user information');
        }
        
        // Update patients table
        $insurance_provider_id = ($registration_type === 'INSURANCE' && !empty($_POST['insurance_provider_id'])) 
                                ? (int)$_POST['insurance_provider_id'] 
                                : null;
        $insurance_number = ($registration_type === 'INSURANCE') ? $_POST['insurance_number'] : null;
        $policy_number = ($registration_type === 'INSURANCE') ? $_POST['policy_number'] : null;
        
        $update_patient_sql = "UPDATE patients SET
                              registration_type = ?,
                              insurance_provider_id = ?,
                              insurance_number = ?,
                              policy_number = ?,
                              employer = ?,
                              occupation = ?,
                              monthly_income = ?,
                              marital_status = ?,
                              blood_group = ?,
                              allergies = ?,
                              chronic_conditions = ?,
                              current_medications = ?,
                              family_medical_history = ?,
                              ent_history = ?,
                              preferred_language = ?,
                              consent_research = ?,
                              consent_marketing = ?,
                              is_active = ?,
                              updated_at = NOW()
                            WHERE patient_id = ?";
        
        $stmt = $conn->prepare($update_patient_sql);
        
        $monthly_income = !empty($_POST['monthly_income']) ? (float)$_POST['monthly_income'] : null;
        $marital_status = !empty($_POST['marital_status']) ? $_POST['marital_status'] : null;
        $blood_group = !empty($_POST['blood_group']) ? $_POST['blood_group'] : null;
        $consent_research = isset($_POST['consent_research']) ? 1 : 0;
        $consent_marketing = isset($_POST['consent_marketing']) ? 1 : 0;
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $stmt->bind_param('sissssdssssssssiiii',
            $registration_type,
            $insurance_provider_id,
            $insurance_number,
            $policy_number,
            $_POST['employer'],
            $_POST['occupation'],
            $monthly_income,
            $marital_status,
            $blood_group,
            $_POST['allergies'],
            $_POST['chronic_conditions'],
            $_POST['current_medications'],
            $_POST['family_medical_history'],
            $_POST['ent_history'],
            $_POST['preferred_language'],
            $consent_research,
            $consent_marketing,
            $is_active,
            $patient_id
        );
        
        if (!$stmt->execute()) {
            throw new Exception('Failed to update patient information');
        }
        
        $conn->commit();
        
        $_SESSION['success_message'] = 'Patient information updated successfully';
        header('Location: patient_profile.php?id=' . $patient_id);
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Patient')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .form-section {
            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;
        }
        
        .form-section h5 {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.25rem;
            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;
        }
        
        .form-control, .form-select {
            border: 1px solid #cbd5e1;
            border-radius: 6px;
            padding: 0.625rem 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .required::after {
            content: '*';
            color: #ef4444;
            margin-left: 0.25rem;
        }
        
        .form-text {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        .btn-group-custom {
            display: flex;
            gap: 0.75rem;
        }
        
        .alert-custom {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #ef4444;
        }
        
        .insurance-fields {
            background: #f8fafc;
            padding: 1rem;
            border-radius: 8px;
            border: 1px solid #e2e8f0;
        }
        
        .patient-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 1.5rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 1.5rem;
        }
    </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">Edit Patient</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_patients.php">Patients</a></li>
                                        <li class="breadcrumb-item"><a href="patient_profile.php?id=<?php echo $patient_id; ?>">Profile</a></li>
                                        <li class="breadcrumb-item active">Edit</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Patient Header -->
                    <div class="patient-header">
                        <h5 class="mb-1">Editing: <?php echo htmlspecialchars($patient['full_name']); ?></h5>
                        <div class="small">
                            Patient Number: <?php echo htmlspecialchars($patient['patient_number']); ?>
                        </div>
                    </div>

                    <?php if (isset($error_message)): ?>
                    <div class="alert-custom alert-danger">
                        <i class="ri-error-warning-line" style="font-size: 1.5rem;"></i>
                        <div><?php echo htmlspecialchars($error_message); ?></div>
                    </div>
                    <?php endif; ?>

                    <form method="POST" id="editPatientForm">
                        <!-- Personal Information -->
                        <div class="form-section">
                            <h5>
                                <i class="ri-user-line"></i>
                                Personal Information
                            </h5>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label required">Full Name</label>
                                    <input type="text" class="form-control" name="full_name" 
                                           value="<?php echo htmlspecialchars($patient['full_name']); ?>" required>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label required">Date of Birth</label>
                                    <input type="date" class="form-control" name="date_of_birth" 
                                           value="<?php echo $patient['date_of_birth']; ?>" required>
                                </div>
                                <div class="col-md-3 mb-3">
                                    <label class="form-label required">Gender</label>
                                    <select class="form-select" name="gender" required>
                                        <option value="">Select Gender</option>
                                        <option value="MALE" <?php echo $patient['gender'] === 'MALE' ? 'selected' : ''; ?>>Male</option>
                                        <option value="FEMALE" <?php echo $patient['gender'] === 'FEMALE' ? 'selected' : ''; ?>>Female</option>
                                        <option value="OTHER" <?php echo $patient['gender'] === 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">National ID</label>
                                    <input type="text" class="form-control" name="national_id" 
                                           value="<?php echo htmlspecialchars($patient['national_id']); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Marital Status</label>
                                    <select class="form-select" name="marital_status">
                                        <option value="">Select Status</option>
                                        <option value="SINGLE" <?php echo $patient['marital_status'] === 'SINGLE' ? 'selected' : ''; ?>>Single</option>
                                        <option value="MARRIED" <?php echo $patient['marital_status'] === 'MARRIED' ? 'selected' : ''; ?>>Married</option>
                                        <option value="DIVORCED" <?php echo $patient['marital_status'] === 'DIVORCED' ? 'selected' : ''; ?>>Divorced</option>
                                        <option value="WIDOWED" <?php echo $patient['marital_status'] === 'WIDOWED' ? 'selected' : ''; ?>>Widowed</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Blood Group</label>
                                    <select class="form-select" name="blood_group">
                                        <option value="">Select Blood Group</option>
                                        <?php
                                        $blood_groups = ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'];
                                        foreach ($blood_groups as $bg):
                                        ?>
                                        <option value="<?php echo $bg; ?>" <?php echo $patient['blood_group'] === $bg ? 'selected' : ''; ?>>
                                            <?php echo $bg; ?>
                                        </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label">Address</label>
                                    <textarea class="form-control" name="address" rows="2"><?php echo htmlspecialchars($patient['address']); ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Contact Information -->
                        <div class="form-section">
                            <h5>
                                <i class="ri-contacts-line"></i>
                                Contact Information
                            </h5>
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">Primary Phone</label>
                                    <input type="tel" class="form-control" name="phone_primary" 
                                           value="<?php echo htmlspecialchars($patient['phone_primary']); ?>" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Secondary Phone</label>
                                    <input type="tel" class="form-control" name="phone_secondary" 
                                           value="<?php echo htmlspecialchars($patient['phone_secondary']); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Email Address</label>
                                    <input type="email" class="form-control" name="email" 
                                           value="<?php echo htmlspecialchars($patient['email']); ?>">
                                </div>
                            </div>
                        </div>

                        <!-- Emergency Contact -->
                        <div class="form-section">
                            <h5>
                                <i class="ri-alarm-warning-line"></i>
                                Emergency Contact
                            </h5>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Contact Name</label>
                                    <input type="text" class="form-control" name="emergency_contact_name" 
                                           value="<?php echo htmlspecialchars($patient['emergency_contact_name']); ?>">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Contact Phone</label>
                                    <input type="tel" class="form-control" name="emergency_contact_phone" 
                                           value="<?php echo htmlspecialchars($patient['emergency_contact_phone']); ?>">
                                </div>
                            </div>
                        </div>

                        <!-- Registration & Insurance -->
                        <div class="form-section">
                            <h5>
                                <i class="ri-shield-check-line"></i>
                                Registration & Insurance Information
                            </h5>
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label required">Registration Type</label>
                                    <select class="form-select" name="registration_type" id="registrationType" required>
                                        <option value="WALK_IN" <?php echo $patient['registration_type'] === 'WALK_IN' ? 'selected' : ''; ?>>Walk-in</option>
                                        <option value="INSURANCE" <?php echo $patient['registration_type'] === 'INSURANCE' ? 'selected' : ''; ?>>Insurance</option>
                                        <option value="CORPORATE" <?php echo $patient['registration_type'] === 'CORPORATE' ? 'selected' : ''; ?>>Corporate</option>
                                        <option value="REFERRAL" <?php echo $patient['registration_type'] === 'REFERRAL' ? 'selected' : ''; ?>>Referral</option>
                                        <option value="ONLINE" <?php echo $patient['registration_type'] === 'ONLINE' ? 'selected' : ''; ?>>Online</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div id="insuranceFields" class="insurance-fields" style="display: <?php echo $patient['registration_type'] === 'INSURANCE' ? 'block' : 'none'; ?>;">
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Insurance Provider</label>
                                        <select class="form-select" name="insurance_provider_id" id="insuranceProvider">
                                            <option value="">Select Provider</option>
                                            <?php while ($provider = $insurance_result->fetch_assoc()): ?>
                                            <option value="<?php echo $provider['provider_id']; ?>" 
                                                    <?php echo $patient['insurance_provider_id'] == $provider['provider_id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($provider['provider_name']); ?>
                                            </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Insurance Number</label>
                                        <input type="text" class="form-control" name="insurance_number" 
                                               value="<?php echo htmlspecialchars($patient['insurance_number']); ?>">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Policy Number</label>
                                        <input type="text" class="form-control" name="policy_number" 
                                               value="<?php echo htmlspecialchars($patient['policy_number']); ?>">
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Professional Information -->
                        <div class="form-section">
                            <h5>
                                <i class="ri-briefcase-line"></i>
                                Professional Information
                            </h5>
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Occupation</label>
                                    <input type="text" class="form-control" name="occupation" 
                                           value="<?php echo htmlspecialchars($patient['occupation']); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Employer</label>
                                    <input type="text" class="form-control" name="employer" 
                                           value="<?php echo htmlspecialchars($patient['employer']); ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Monthly Income (KES)</label>
                                    <input type="number" class="form-control" name="monthly_income" step="0.01"
                                           value="<?php echo $patient['monthly_income']; ?>">
                                </div>
                            </div>
                        </div>

                        <!-- Medical History -->
                        <div class="form-section">
                            <h5>
                                <i class="ri-medicine-bottle-line"></i>
                                Medical History
                            </h5>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Allergies</label>
                                    <textarea class="form-control" name="allergies" rows="3" 
                                              placeholder="List any known allergies..."><?php echo htmlspecialchars($patient['allergies']); ?></textarea>
                                    <small class="form-text">Separate multiple allergies with commas</small>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Chronic Conditions</label>
                                    <textarea class="form-control" name="chronic_conditions" rows="3" 
                                              placeholder="List any chronic conditions..."><?php echo htmlspecialchars($patient['chronic_conditions']); ?></textarea>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Current Medications</label>
                                    <textarea class="form-control" name="current_medications" rows="3" 
                                              placeholder="List current medications..."><?php echo htmlspecialchars($patient['current_medications']); ?></textarea>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Family Medical History</label>
                                    <textarea class="form-control" name="family_medical_history" rows="3" 
                                              placeholder="Any relevant family medical history..."><?php echo htmlspecialchars($patient['family_medical_history']); ?></textarea>
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label">ENT History</label>
                                    <textarea class="form-control" name="ent_history" rows="3" 
                                              placeholder="Previous ENT conditions, surgeries, treatments..."><?php echo htmlspecialchars($patient['ent_history']); ?></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- Additional Settings -->
                        <div class="form-section">
                            <h5>
                                <i class="ri-settings-3-line"></i>
                                Additional Settings
                            </h5>
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label class="form-label">Preferred Language</label>
                                    <select class="form-select" name="preferred_language">
                                        <option value="en" <?php echo $patient['preferred_language'] === 'en' ? 'selected' : ''; ?>>English</option>
                                        <option value="sw" <?php echo $patient['preferred_language'] === 'sw' ? 'selected' : ''; ?>>Swahili</option>
                                        <option value="fr" <?php echo $patient['preferred_language'] === 'fr' ? 'selected' : ''; ?>>French</option>
                                    </select>
                                </div>
                                <div class="col-md-8 mb-3">
                                    <label class="form-label">Consents</label>
                                    <div class="d-flex gap-4">
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="consent_research" 
                                                   id="consentResearch" <?php echo $patient['consent_research'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="consentResearch">
                                                Research Participation
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="consent_marketing" 
                                                   id="consentMarketing" <?php echo $patient['consent_marketing'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="consentMarketing">
                                                Marketing Communications
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="checkbox" name="is_active" 
                                                   id="isActive" <?php echo $patient['is_active'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="isActive">
                                                Active Status
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Form Actions -->
                        <div class="form-section">
                            <div class="btn-group-custom">
                                <button type="submit" class="btn btn-primary">
                                    <i class="ri-save-line me-1"></i> Save Changes
                                </button>
                                <a href="patient_profile.php?id=<?php echo $patient_id; ?>" class="btn btn-secondary">
                                    <i class="ri-close-line me-1"></i> Cancel
                                </a>
                                <a href="list_patients.php" class="btn btn-outline-secondary">
                                    <i class="ri-arrow-left-line me-1"></i> Back to List
                                </a>
                            </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="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Toggle insurance fields based on registration type
        $('#registrationType').on('change', function() {
            if ($(this).val() === 'INSURANCE') {
                $('#insuranceFields').slideDown();
                $('#insuranceProvider').prop('required', true);
            } else {
                $('#insuranceFields').slideUp();
                $('#insuranceProvider').prop('required', false);
            }
        });
        
        // Form validation
        $('#editPatientForm').on('submit', function(e) {
            const registrationType = $('#registrationType').val();
            
            if (registrationType === 'INSURANCE') {
                const providerId = $('#insuranceProvider').val();
                if (!providerId) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please select an insurance provider'
                    });
                    return false;
                }
            }
            
            // Show loading
            Swal.fire({
                title: 'Updating Patient...',
                html: 'Please wait while we update the patient information',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
        });
        
        // Confirm before leaving with unsaved changes
        let formChanged = false;
        $('#editPatientForm input, #editPatientForm select, #editPatientForm textarea').on('change', function() {
            formChanged = true;
        });
        
        $('a[href]').on('click', function(e) {
            if (formChanged && !$(this).hasClass('btn-primary')) {
                e.preventDefault();
                const href = $(this).attr('href');
                Swal.fire({
                    title: 'Unsaved Changes',
                    text: 'You have unsaved changes. Are you sure you want to leave?',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Yes, leave'
                }).then((result) => {
                    if (result.isConfirmed) {
                        window.location.href = href;
                    }
                });
            }
        });
    });
    </script>

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