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

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

// Fetch hospital branches
$sql_branches = "SELECT * FROM hospital_branches WHERE is_active = 1 ORDER BY branch_name";
$result_branches = $conn->query($sql_branches);

// Fetch nurse roles
$sql_roles = "SELECT * FROM user_roles WHERE role_code IN ('HEAD_NURSE', 'ENT_NURSE') AND is_active = 1";
$result_roles = $conn->query($sql_roles);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $conn->begin_transaction();
    
    try {
        // Insert into users table
        $username = $_POST['username'];
        $email = $_POST['email'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $full_name = $_POST['full_name'];
        $phone_primary = $_POST['phone_primary'];
        $phone_secondary = $_POST['phone_secondary'] ?? null;
        $role_id = $_POST['role_id'];
        $branch_id = $_POST['branch_id'];
        $date_of_birth = $_POST['date_of_birth'];
        $gender = $_POST['gender'];
        $national_id = $_POST['national_id'];
        $address = $_POST['address'];
        $emergency_contact_name = $_POST['emergency_contact_name'];
        $emergency_contact_phone = $_POST['emergency_contact_phone'];
        $hire_date = $_POST['hire_date'];
        
        // Generate staff number
        $staff_prefix = 'NRS';
        $year = date('Y');
        $sql_count = "SELECT COUNT(*) as count FROM users WHERE staff_number LIKE 'NRS{$year}%'";
        $count_result = $conn->query($sql_count);
        $count = $count_result->fetch_assoc()['count'] + 1;
        $staff_number = $staff_prefix . $year . str_pad($count, 4, '0', STR_PAD_LEFT);
        
        $sql_user = "INSERT INTO users (user_type, username, email, password_hash, full_name, phone_primary, phone_secondary, 
                     role_id, staff_number, branch_id, status, date_of_birth, gender, national_id, address, 
                     emergency_contact_name, emergency_contact_phone, hire_date) 
                     VALUES ('STAFF', ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ACTIVE', ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt_user = $conn->prepare($sql_user);
        $stmt_user->bind_param("ssssssisssssssss", $username, $email, $password, $full_name, $phone_primary, 
                               $phone_secondary, $role_id, $staff_number, $branch_id, $date_of_birth, 
                               $gender, $national_id, $address, $emergency_contact_name, 
                               $emergency_contact_phone, $hire_date);
        $stmt_user->execute();
        $user_id = $conn->insert_id;
        
        // Insert into nurses table
        $nursing_license = $_POST['nursing_license'];
        $qualification = $_POST['qualification'];
        $specialization = $_POST['specialization'] ?? null;
        $department = $_POST['department'];
        $shift_type = $_POST['shift_type'];
        $certifications = json_encode($_POST['certifications'] ?? []);
        $is_head_nurse = isset($_POST['is_head_nurse']) ? 1 : 0;
        
        $sql_nurse = "INSERT INTO nurses (user_id, nursing_license, qualification, specialization, department, 
                      shift_type, certifications, is_head_nurse, is_active) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)";
        
        $stmt_nurse = $conn->prepare($sql_nurse);
        $stmt_nurse->bind_param("issssssi", $user_id, $nursing_license, $qualification, $specialization, 
                                $department, $shift_type, $certifications, $is_head_nurse);
        $stmt_nurse->execute();
        
        // Log activity
        $action = "CREATE";
        $module = "NURSES";
        $record_id = $conn->insert_id;
        $ip_address = $_SERVER['REMOTE_ADDR'];
        
        $sql_log = "INSERT INTO activity_log (user_id, action, module, record_id, ip_address) 
                    VALUES (?, ?, ?, ?, ?)";
        $stmt_log = $conn->prepare($sql_log);
        $stmt_log->bind_param("issis", $_SESSION['user_id'], $action, $module, $record_id, $ip_address);
        $stmt_log->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = "Nurse added successfully!";
        header('Location: list_nurses.php');
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "Error adding nurse: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add New Nurse')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</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">Add New ENT Nurse</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_nurses.php">Nurses</a></li>
                                        <li class="breadcrumb-item active">Add Nurse</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <form method="POST" id="addNurseForm">
                        <div class="row">
                            <div class="col-lg-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Nurse Information</h5>
                                    </div>
                                    <div class="card-body">
                                        <!-- Personal Information -->
                                        <h6 class="mb-3 fw-semibold text-uppercase">Personal Information</h6>
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Full Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="full_name" required>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Gender <span class="text-danger">*</span></label>
                                                <select class="form-select" name="gender" required>
                                                    <option value="">Select Gender</option>
                                                    <option value="MALE">Male</option>
                                                    <option value="FEMALE">Female</option>
                                                    <option value="OTHER">Other</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Date of Birth <span class="text-danger">*</span></label>
                                                <input type="date" class="form-control" name="date_of_birth" required>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">National ID <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="national_id" required>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Primary Phone <span class="text-danger">*</span></label>
                                                <input type="tel" class="form-control" name="phone_primary" placeholder="+254700000000" 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" placeholder="+254700000000">
                                            </div>
                                            <div class="col-md-12 mb-3">
                                                <label class="form-label">Address <span class="text-danger">*</span></label>
                                                <textarea class="form-control" name="address" rows="2" required></textarea>
                                            </div>
                                        </div>

                                        <hr class="my-4">

                                        <!-- Emergency Contact -->
                                        <h6 class="mb-3 fw-semibold text-uppercase">Emergency Contact</h6>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Emergency Contact Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="emergency_contact_name" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Emergency Contact Phone <span class="text-danger">*</span></label>
                                                <input type="tel" class="form-control" name="emergency_contact_phone" required>
                                            </div>
                                        </div>

                                        <hr class="my-4">

                                        <!-- Professional Information -->
                                        <h6 class="mb-3 fw-semibold text-uppercase">Professional Information</h6>
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Nursing License <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="nursing_license" required>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Qualification <span class="text-danger">*</span></label>
                                                <select class="form-select" name="qualification" required>
                                                    <option value="">Select Qualification</option>
                                                    <option value="Diploma in Nursing">Diploma in Nursing</option>
                                                    <option value="Bachelor of Science in Nursing">BSc Nursing</option>
                                                    <option value="Master of Science in Nursing">MSc Nursing</option>
                                                    <option value="Registered Nurse">Registered Nurse (RN)</option>
                                                    <option value="Licensed Practical Nurse">Licensed Practical Nurse (LPN)</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Specialization</label>
                                                <select class="form-select" name="specialization">
                                                    <option value="">Select Specialization</option>
                                                    <option value="ENT Nursing">ENT Nursing</option>
                                                    <option value="Surgical Nursing">Surgical Nursing</option>
                                                    <option value="Pediatric Nursing">Pediatric Nursing</option>
                                                    <option value="Emergency Nursing">Emergency Nursing</option>
                                                    <option value="Critical Care">Critical Care</option>
                                                    <option value="General Nursing">General Nursing</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Department <span class="text-danger">*</span></label>
                                                <select class="form-select" name="department" required>
                                                    <option value="ENT">ENT</option>
                                                    <option value="Outpatient">Outpatient</option>
                                                    <option value="Inpatient">Inpatient</option>
                                                    <option value="Surgery">Surgery</option>
                                                    <option value="Emergency">Emergency</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Shift Type <span class="text-danger">*</span></label>
                                                <select class="form-select" name="shift_type" required>
                                                    <option value="">Select Shift</option>
                                                    <option value="DAY">Day Shift (6AM - 6PM)</option>
                                                    <option value="NIGHT">Night Shift (6PM - 6AM)</option>
                                                    <option value="ROTATING">Rotating Shifts</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Certifications</label>
                                                <div class="mt-2">
                                                    <div class="form-check form-check-inline">
                                                        <input class="form-check-input" type="checkbox" name="certifications[]" value="BLS" id="cert1">
                                                        <label class="form-check-label" for="cert1">BLS</label>
                                                    </div>
                                                    <div class="form-check form-check-inline">
                                                        <input class="form-check-input" type="checkbox" name="certifications[]" value="ACLS" id="cert2">
                                                        <label class="form-check-label" for="cert2">ACLS</label>
                                                    </div>
                                                    <div class="form-check form-check-inline">
                                                        <input class="form-check-input" type="checkbox" name="certifications[]" value="PALS" id="cert3">
                                                        <label class="form-check-label" for="cert3">PALS</label>
                                                    </div>
                                                    <div class="form-check form-check-inline">
                                                        <input class="form-check-input" type="checkbox" name="certifications[]" value="Wound Care" id="cert4">
                                                        <label class="form-check-label" for="cert4">Wound Care</label>
                                                    </div>
                                                    <div class="form-check form-check-inline">
                                                        <input class="form-check-input" type="checkbox" name="certifications[]" value="IV Therapy" id="cert5">
                                                        <label class="form-check-label" for="cert5">IV Therapy</label>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-12 mb-3">
                                                <div class="form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" name="is_head_nurse" id="isHeadNurse">
                                                    <label class="form-check-label" for="isHeadNurse">
                                                        <strong>Designate as Head Nurse / Nurse In-Charge</strong>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>

                                        <hr class="my-4">

                                        <!-- Account Information -->
                                        <h6 class="mb-3 fw-semibold text-uppercase">Account Information</h6>
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Username <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="username" required>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Email <span class="text-danger">*</span></label>
                                                <input type="email" class="form-control" name="email" required>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">User Role <span class="text-danger">*</span></label>
                                                <select class="form-select" name="role_id" required>
                                                    <option value="">Select Role</option>
                                                    <?php while($role = $result_roles->fetch_assoc()): ?>
                                                        <option value="<?php echo $role['role_id']; ?>">
                                                            <?php echo htmlspecialchars($role['role_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Password <span class="text-danger">*</span></label>
                                                <input type="password" class="form-control" name="password" minlength="8" required>
                                                <small class="text-muted">Minimum 8 characters</small>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Confirm Password <span class="text-danger">*</span></label>
                                                <input type="password" class="form-control" name="confirm_password" minlength="8" required>
                                            </div>
                                        </div>

                                        <hr class="my-4">

                                        <!-- Employment Details -->
                                        <h6 class="mb-3 fw-semibold text-uppercase">Employment Details</h6>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Hospital Branch <span class="text-danger">*</span></label>
                                                <select class="form-select" name="branch_id" required>
                                                    <option value="">Select Branch</option>
                                                    <?php while($branch = $result_branches->fetch_assoc()): ?>
                                                        <option value="<?php echo $branch['branch_id']; ?>">
                                                            <?php echo htmlspecialchars($branch['branch_name']); ?>
                                                        </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Hire Date <span class="text-danger">*</span></label>
                                                <input type="date" class="form-control" name="hire_date" required>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-footer">
                                        <div class="d-flex justify-content-end gap-2">
                                            <a href="list_nurses.php" class="btn btn-secondary">
                                                <i class="ri-close-line align-middle me-1"></i> Cancel
                                            </a>
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line align-middle me-1"></i> Add Nurse
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        document.getElementById('addNurseForm').addEventListener('submit', function(e) {
            const password = document.querySelector('input[name="password"]').value;
            const confirmPassword = document.querySelector('input[name="confirm_password"]').value;
            
            if (password !== confirmPassword) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Password Mismatch',
                    text: 'Password and Confirm Password do not match!'
                });
                return false;
            }
        });

        <?php if(isset($_SESSION['error_message'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '<?php echo $_SESSION['error_message']; ?>'
            });
            <?php unset($_SESSION['error_message']); ?>
        <?php endif; ?>
    </script>
</body>
</html>

<?php $conn->close(); ?>