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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name, b.branch_name, b.branch_code 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     LEFT JOIN branches b ON u.branch_id = b.branch_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
    $branch_name = $user_details['branch_name'];
    $staff_number = $user_details['staff_number'];
}

$errors = array();
$success_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate input
    $new_username = trim($_POST['username']);
    $new_email = trim($_POST['email']);
    $new_full_name = trim($_POST['full_name']);
    $new_phone = trim($_POST['phone_number']);
    $new_role_id = $_POST['role_id'];
    $new_staff_number = trim($_POST['staff_number']);
    $new_license_number = trim($_POST['license_number']);
    $new_license_expiry = $_POST['license_expiry'];
    $new_branch_id = $_POST['branch_id'] ?: null;
    $new_supervisor_id = $_POST['supervisor_id'] ?: null;
    $new_commission_rate = $_POST['commission_rate'] ?: 0;
    $new_status = $_POST['status'];
    $new_date_of_birth = $_POST['date_of_birth'];
    $new_gender = $_POST['gender'];
    $new_national_id = trim($_POST['national_id']);
    $new_address = trim($_POST['address']);
    $new_emergency_contact = trim($_POST['emergency_contact']);
    $new_emergency_phone = trim($_POST['emergency_phone']);
    $new_hire_date = $_POST['hire_date'];
    $new_password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];

    // Validation
    if (empty($new_username)) {
        $errors[] = "Username is required";
    }
    if (empty($new_email)) {
        $errors[] = "Email is required";
    } elseif (!filter_var($new_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    if (empty($new_full_name)) {
        $errors[] = "Full name is required";
    }
    if (empty($new_phone)) {
        $errors[] = "Phone number is required";
    }
    if (empty($new_role_id)) {
        $errors[] = "Role is required";
    }
    if (empty($new_password)) {
        $errors[] = "Password is required";
    } elseif (strlen($new_password) < 6) {
        $errors[] = "Password must be at least 6 characters";
    }
    if ($new_password !== $confirm_password) {
        $errors[] = "Passwords do not match";
    }

    // Check for duplicate username
    if (!empty($new_username)) {
        $check_username = $conn->prepare("SELECT user_id FROM users WHERE username = ?");
        $check_username->bind_param("s", $new_username);
        $check_username->execute();
        if ($check_username->get_result()->num_rows > 0) {
            $errors[] = "Username already exists";
        }
    }

    // Check for duplicate email
    if (!empty($new_email)) {
        $check_email = $conn->prepare("SELECT user_id FROM users WHERE email = ?");
        $check_email->bind_param("s", $new_email);
        $check_email->execute();
        if ($check_email->get_result()->num_rows > 0) {
            $errors[] = "Email already exists";
        }
    }

    // Check for duplicate staff number
    if (!empty($new_staff_number)) {
        $check_staff = $conn->prepare("SELECT user_id FROM users WHERE staff_number = ?");
        $check_staff->bind_param("s", $new_staff_number);
        $check_staff->execute();
        if ($check_staff->get_result()->num_rows > 0) {
            $errors[] = "Staff number already exists";
        }
    }

    // If no errors, insert the user
    if (empty($errors)) {
        $password_hash = password_hash($new_password, PASSWORD_DEFAULT);
        
        $sql = "INSERT INTO users (username, email, password_hash, full_name, phone_number, role_id, 
                staff_number, license_number, license_expiry, branch_id, supervisor_id, 
                commission_rate, status, date_of_birth, gender, national_id, address, 
                emergency_contact, emergency_phone, hire_date) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssisssissssssssss", 
            $new_username, $new_email, $password_hash, $new_full_name, $new_phone, 
            $new_role_id, $new_staff_number, $new_license_number, $new_license_expiry, 
            $new_branch_id, $new_supervisor_id, $new_commission_rate, $new_status, 
            $new_date_of_birth, $new_gender, $new_national_id, $new_address, 
            $new_emergency_contact, $new_emergency_phone, $new_hire_date
        );
        
        if ($stmt->execute()) {
            $new_user_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, user_agent) VALUES (?, 'CREATE', 'USER', ?, 'USER', ?, ?, ?)";
            $activity_stmt = $conn->prepare($activity_sql);
            $new_values = json_encode(['username' => $new_username, 'email' => $new_email, 'full_name' => $new_full_name]);
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            $activity_stmt->bind_param("iisss", $user_id, $new_user_id, $new_values, $ip_address, $user_agent);
            $activity_stmt->execute();
            
            $success_message = "User created successfully!";
            
            // If it's a doctor, create doctor record
            if ($new_role_id == 3 || $new_role_id == 4) { // Doctor or Senior Doctor
                $consultation_fee = $_POST['consultation_fee'] ?: 2000;
                $specialization = trim($_POST['specialization']);
                $qualification = trim($_POST['qualification']);
                $experience_years = $_POST['experience_years'] ?: 0;
                
                $doctor_sql = "INSERT INTO doctors (user_id, medical_license, specialization, 
                              qualification, experience_years, consultation_fee, commission_rate) 
                              VALUES (?, ?, ?, ?, ?, ?, ?)";
                $doctor_stmt = $conn->prepare($doctor_sql);
                $doctor_stmt->bind_param("isssidd", $new_user_id, $new_license_number, $specialization, 
                                       $qualification, $experience_years, $consultation_fee, $new_commission_rate);
                $doctor_stmt->execute();
            }
            
            // If it's a nurse, create nurse record
            if ($new_role_id == 5) { // Nurse
                $qualification = trim($_POST['qualification']);
                $shift_type = $_POST['shift_type'] ?: 'DAY';
                
                $nurse_sql = "INSERT INTO nurses (user_id, nursing_license, qualification, shift_type) 
                             VALUES (?, ?, ?, ?)";
                $nurse_stmt = $conn->prepare($nurse_sql);
                $nurse_stmt->bind_param("isss", $new_user_id, $new_license_number, $qualification, $shift_type);
                $nurse_stmt->execute();
            }
            
            // Redirect after 2 seconds
            header("refresh:2;url=list_users.php");
        } else {
            $errors[] = "Error creating user: " . $conn->error;
        }
    }
}

// Get roles for dropdown
$roles_query = "SELECT role_id, role_name FROM user_roles WHERE is_active = 1 ORDER BY role_name";
$roles_result = $conn->query($roles_query);

// Get branches for dropdown
$branches_query = "SELECT branch_id, branch_name FROM branches WHERE is_active = 1 ORDER BY branch_name";
$branches_result = $conn->query($branches_query);

// Get supervisors (users with supervisor roles)
$supervisors_query = "SELECT u.user_id, u.full_name FROM users u 
                     JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.status = 'ACTIVE' AND ur.role_name IN ('Super Admin', 'Hospital Admin', 'Medical Director', 'Senior Doctor', 'Lab Manager')
                     ORDER BY u.full_name";
$supervisors_result = $conn->query($supervisors_query);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add User - Healthcare EMR System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        /* Use the same styling from dashboard */
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Form Card */
        .form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        .form-header {
            padding: 1.5rem;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .form-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .form-body {
            padding: 2rem;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
            outline: none;
        }
        
        .form-text {
            font-size: 0.75rem;
            color: #64748b;
            margin-top: 0.25rem;
        }
        
        /* Alert Messages */
        .alert {
            border-radius: 8px;
            border: none;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        /* Buttons */
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-block;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            color: white;
        }
        
        .btn-secondary {
            background: #64748b;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #475569;
            color: white;
        }
        
        /* Required field indicator */
        .required {
            color: #dc2626;
        }
        
        /* Section headers */
        .section-header {
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
            margin: 2rem 0 1rem 0;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .section-header:first-child {
            margin-top: 0;
        }
        
        /* Role-specific fields */
        .role-specific-fields {
            display: none;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1.5rem;
            margin-top: 1rem;
        }
        
        .role-specific-fields.show {
            display: block;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .form-body {
                padding: 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 Header -->
                    <div class="page-header">
                        <h1 class="page-title">Add New User</h1>
                        <p class="page-subtitle">Create a new user account and assign roles</p>
                    </div>

                    <!-- Add User Form -->
                    <div class="form-card">
                        <div class="form-header">
                            <h3 class="form-title">User Information</h3>
                        </div>
                        
                        <div class="form-body">
                            <?php if (!empty($errors)): ?>
                                <div class="alert alert-danger">
                                    <ul class="mb-0">
                                        <?php foreach ($errors as $error): ?>
                                            <li><?php echo htmlspecialchars($error); ?></li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            <?php endif; ?>

                            <?php if ($success_message): ?>
                                <div class="alert alert-success">
                                    <?php echo htmlspecialchars($success_message); ?>
                                    <br><small>Redirecting to users list...</small>
                                </div>
                            <?php endif; ?>

                            <form method="POST" id="addUserForm">
                                <!-- Basic Information -->
                                <div class="section-header">Basic Information</div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Full Name <span class="required">*</span></label>
                                            <input type="text" class="form-control" name="full_name" value="<?php echo htmlspecialchars($_POST['full_name'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Username <span class="required">*</span></label>
                                            <input type="text" class="form-control" name="username" value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>" required>
                                            <div class="form-text">Username must be unique</div>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Email Address <span class="required">*</span></label>
                                            <input type="email" class="form-control" name="email" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Phone Number <span class="required">*</span></label>
                                            <input type="tel" class="form-control" name="phone_number" value="<?php echo htmlspecialchars($_POST['phone_number'] ?? ''); ?>" required>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Date of Birth</label>
                                            <input type="date" class="form-control" name="date_of_birth" value="<?php echo htmlspecialchars($_POST['date_of_birth'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Gender</label>
                                            <select class="form-select" name="gender">
                                                <option value="">Select Gender</option>
                                                <option value="MALE" <?php echo ($_POST['gender'] ?? '') == 'MALE' ? 'selected' : ''; ?>>Male</option>
                                                <option value="FEMALE" <?php echo ($_POST['gender'] ?? '') == 'FEMALE' ? 'selected' : ''; ?>>Female</option>
                                                <option value="OTHER" <?php echo ($_POST['gender'] ?? '') == 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">National ID</label>
                                            <input type="text" class="form-control" name="national_id" value="<?php echo htmlspecialchars($_POST['national_id'] ?? ''); ?>">
                                        </div>
                                    </div>
                                </div>

                                <!-- Work Information -->
                                <div class="section-header">Work Information</div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Role <span class="required">*</span></label>
                                            <select class="form-select" name="role_id" id="roleSelect" required>
                                                <option value="">Select Role</option>
                                                <?php while ($role = $roles_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $role['role_id']; ?>" <?php echo ($_POST['role_id'] ?? '') == $role['role_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($role['role_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Status <span class="required">*</span></label>
                                            <select class="form-select" name="status" required>
                                                <option value="ACTIVE" <?php echo ($_POST['status'] ?? 'ACTIVE') == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                <option value="PENDING" <?php echo ($_POST['status'] ?? '') == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="INACTIVE" <?php echo ($_POST['status'] ?? '') == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Staff Number</label>
                                            <input type="text" class="form-control" name="staff_number" value="<?php echo htmlspecialchars($_POST['staff_number'] ?? ''); ?>">
                                            <div class="form-text">Leave empty to auto-generate</div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Branch</label>
                                            <select class="form-select" name="branch_id">
                                                <option value="">Select Branch</option>
                                                <?php while ($branch = $branches_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $branch['branch_id']; ?>" <?php echo ($_POST['branch_id'] ?? '') == $branch['branch_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($branch['branch_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="mb-3">
                                            <label class="form-label">Supervisor</label>
                                            <select class="form-select" name="supervisor_id">
                                                <option value="">Select Supervisor</option>
                                                <?php while ($supervisor = $supervisors_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $supervisor['user_id']; ?>" <?php echo ($_POST['supervisor_id'] ?? '') == $supervisor['user_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($supervisor['full_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Hire Date</label>
                                            <input type="date" class="form-control" name="hire_date" value="<?php echo htmlspecialchars($_POST['hire_date'] ?? date('Y-m-d')); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Commission Rate (%)</label>
                                            <input type="number" class="form-control" name="commission_rate" value="<?php echo htmlspecialchars($_POST['commission_rate'] ?? '0'); ?>" min="0" max="100" step="0.01">
                                            <div class="form-text">For doctors and other commission-based roles</div>
                                        </div>
                                    </div>
                                </div>

                                <!-- License Information -->
                                <div class="section-header">License & Professional Information</div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">License Number</label>
                                            <input type="text" class="form-control" name="license_number" value="<?php echo htmlspecialchars($_POST['license_number'] ?? ''); ?>">
                                            <div class="form-text">Medical/Nursing license number</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">License Expiry</label>
                                            <input type="date" class="form-control" name="license_expiry" value="<?php echo htmlspecialchars($_POST['license_expiry'] ?? ''); ?>">
                                        </div>
                                    </div>
                                </div>

                                <!-- Doctor-specific fields -->
                                <div id="doctorFields" class="role-specific-fields">
                                    <h5 style="color: #1e293b; margin-bottom: 1rem;">Doctor Information</h5>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">Specialization</label>
                                                <input type="text" class="form-control" name="specialization" value="<?php echo htmlspecialchars($_POST['specialization'] ?? ''); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">Consultation Fee (KES)</label>
                                                <input type="number" class="form-control" name="consultation_fee" value="<?php echo htmlspecialchars($_POST['consultation_fee'] ?? '2000'); ?>" min="0" step="50">
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">Qualification</label>
                                                <textarea class="form-control" name="qualification" rows="2"><?php echo htmlspecialchars($_POST['qualification'] ?? ''); ?></textarea>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">Experience (Years)</label>
                                                <input type="number" class="form-control" name="experience_years" value="<?php echo htmlspecialchars($_POST['experience_years'] ?? '0'); ?>" min="0">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Nurse-specific fields -->
                                <div id="nurseFields" class="role-specific-fields">
                                    <h5 style="color: #1e293b; margin-bottom: 1rem;">Nurse Information</h5>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">Qualification</label>
                                                <input type="text" class="form-control" name="qualification" value="<?php echo htmlspecialchars($_POST['qualification'] ?? ''); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">Shift Type</label>
                                                <select class="form-select" name="shift_type">
                                                    <option value="DAY" <?php echo ($_POST['shift_type'] ?? 'DAY') == 'DAY' ? 'selected' : ''; ?>>Day Shift</option>
                                                    <option value="NIGHT" <?php echo ($_POST['shift_type'] ?? '') == 'NIGHT' ? 'selected' : ''; ?>>Night Shift</option>
                                                    <option value="ROTATING" <?php echo ($_POST['shift_type'] ?? '') == 'ROTATING' ? 'selected' : ''; ?>>Rotating Shift</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Contact Information -->
                                <div class="section-header">Contact & Address Information</div>
                                
                                <div class="row">
                                    <div class="col-md-12">
                                        <div class="mb-3">
                                            <label class="form-label">Address</label>
                                            <textarea class="form-control" name="address" rows="3"><?php echo htmlspecialchars($_POST['address'] ?? ''); ?></textarea>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Emergency Contact Name</label>
                                            <input type="text" class="form-control" name="emergency_contact" value="<?php echo htmlspecialchars($_POST['emergency_contact'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Emergency Contact Phone</label>
                                            <input type="tel" class="form-control" name="emergency_phone" value="<?php echo htmlspecialchars($_POST['emergency_phone'] ?? ''); ?>">
                                        </div>
                                    </div>
                                </div>

                                <!-- Security Information -->
                                <div class="section-header">Security Information</div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Password <span class="required">*</span></label>
                                            <input type="password" class="form-control" name="password" required minlength="6">
                                            <div class="form-text">Minimum 6 characters</div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="mb-3">
                                            <label class="form-label">Confirm Password <span class="required">*</span></label>
                                            <input type="password" class="form-control" name="confirm_password" required minlength="6">
                                        </div>
                                    </div>
                                </div>

                                <!-- Form Actions -->
                                <div class="d-flex gap-3 mt-4">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="ph-user-plus me-1"></i> Create User
                                    </button>
                                    <a href="list_users.php" class="btn btn-secondary">
                                        <i class="ph-arrow-left me-1"></i> Back to Users
                                    </a>
                                </div>
                            </form>
                        </div>
                    </div>
                </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>
        $(document).ready(function() {
            // Show/hide role-specific fields
            function toggleRoleFields() {
                const roleId = $('#roleSelect').val();
                const roleName = $('#roleSelect option:selected').text();
                
                // Hide all role-specific fields
                $('.role-specific-fields').removeClass('show');
                
                // Show relevant fields based on role
                if (roleName.includes('Doctor')) {
                    $('#doctorFields').addClass('show');
                } else if (roleName.includes('Nurse')) {
                    $('#nurseFields').addClass('show');
                }
            }
            
            // Initial check
            toggleRoleFields();
            
            // Check when role changes
            $('#roleSelect').on('change', toggleRoleFields);
            
            // Password confirmation validation
            $('input[name="confirm_password"]').on('keyup', function() {
                const password = $('input[name="password"]').val();
                const confirmPassword = $(this).val();
                
                if (password !== confirmPassword) {
                    $(this).addClass('is-invalid');
                    if (!$(this).next('.invalid-feedback').length) {
                        $(this).after('<div class="invalid-feedback">Passwords do not match</div>');
                    }
                } else {
                    $(this).removeClass('is-invalid');
                    $(this).next('.invalid-feedback').remove();
                }
            });
            
            // Form validation before submit
            $('#addUserForm').on('submit', function(e) {
                const password = $('input[name="password"]').val();
                const confirmPassword = $('input[name="confirm_password"]').val();
                
                if (password !== confirmPassword) {
                    e.preventDefault();
                    alert('Passwords do not match!');
                    return false;
                }
                
                if (password.length < 6) {
                    e.preventDefault();
                    alert('Password must be at least 6 characters long!');
                    return false;
                }
            });
            
            // Auto-generate staff number based on role
            $('#roleSelect').on('change', function() {
                const roleName = $(this).find('option:selected').text();
                const staffNumberField = $('input[name="staff_number"]');
                
                if (staffNumberField.val() === '') {
                    let prefix = '';
                    const year = new Date().getFullYear();
                    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                    
                    switch(roleName) {
                        case 'Doctor':
                        case 'Senior Doctor':
                            prefix = 'DOC';
                            break;
                        case 'Nurse':
                            prefix = 'NURSE';
                            break;
                        case 'Receptionist':
                            prefix = 'REC';
                            break;
                        case 'Lab Technician':
                        case 'Lab Manager':
                            prefix = 'LAB';
                            break;
                        case 'Billing Clerk':
                            prefix = 'BILL';
                            break;
                        default:
                            prefix = 'STAFF';
                    }
                    
                    staffNumberField.val(prefix + year + random);
                }
            });
        });
    </script>

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

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