<?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();
}

// Get user ID from URL
$edit_user_id = $_GET['id'] ?? 0;

if (!$edit_user_id) {
    header('Location: list_users.php');
    exit();
}

// Fetch current user details
$current_user_id = $_SESSION['user_id'];
$sql_current_user = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_current = $conn->prepare($sql_current_user);
$stmt_current->bind_param("i", $current_user_id);
$stmt_current->execute();
$current_user = $stmt_current->get_result()->fetch_assoc();

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate input
    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $full_name = trim($_POST['full_name']);
    $phone = trim($_POST['phone_number']);
    $role_id = $_POST['role_id'];
    $staff_number = trim($_POST['staff_number']);
    $license_number = trim($_POST['license_number']);
    $license_expiry = $_POST['license_expiry'] ?: null;
    $branch_id = $_POST['branch_id'] ?: null;
    $supervisor_id = $_POST['supervisor_id'] ?: null;
    $commission_rate = $_POST['commission_rate'] ?: 0;
    $status = $_POST['status'];
    $date_of_birth = $_POST['date_of_birth'] ?: null;
    $gender = $_POST['gender'] ?: null;
    $national_id = trim($_POST['national_id']);
    $address = trim($_POST['address']);
    $emergency_contact = trim($_POST['emergency_contact']);
    $emergency_phone = trim($_POST['emergency_phone']);
    $hire_date = $_POST['hire_date'] ?: null;

    // Validation
    if (empty($username)) {
        $errors[] = "Username is required";
    }
    if (empty($email)) {
        $errors[] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    if (empty($full_name)) {
        $errors[] = "Full name is required";
    }
    if (empty($phone)) {
        $errors[] = "Phone number is required";
    }
    if (empty($role_id)) {
        $errors[] = "Role is required";
    }

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

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

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

    // If no errors, update the user
    if (empty($errors)) {
        $sql = "UPDATE users SET username=?, email=?, 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=?, updated_at=CURRENT_TIMESTAMP
                WHERE user_id=?";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssississsssssssssi", 
            $username, $email, $full_name, $phone, $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, $edit_user_id
        );
        
        if ($stmt->execute()) {
            // Log the activity
            $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                            new_values, ip_address, user_agent) VALUES (?, 'UPDATE', 'USER', ?, 'USER', ?, ?, ?)";
            $activity_stmt = $conn->prepare($activity_sql);
            $new_values = json_encode(['username' => $username, 'email' => $email, 'full_name' => $full_name]);
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $user_agent = $_SERVER['HTTP_USER_AGENT'];
            $activity_stmt->bind_param("iisss", $current_user_id, $edit_user_id, $new_values, $ip_address, $user_agent);
            $activity_stmt->execute();
            
            // Update doctor details if applicable
            if (in_array($role_id, [3, 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;
                
                // Check if doctor record exists
                $check_doctor = $conn->prepare("SELECT doctor_id FROM doctors WHERE user_id = ?");
                $check_doctor->bind_param("i", $edit_user_id);
                $check_doctor->execute();
                $doctor_exists = $check_doctor->get_result()->num_rows > 0;
                
                if ($doctor_exists) {
                    $doctor_sql = "UPDATE doctors SET medical_license=?, specialization=?, 
                                  qualification=?, experience_years=?, consultation_fee=?, commission_rate=?
                                  WHERE user_id=?";
                    $doctor_stmt = $conn->prepare($doctor_sql);
                    $doctor_stmt->bind_param("sssiidi", $license_number, $specialization, $qualification, 
                                           $experience_years, $consultation_fee, $commission_rate, $edit_user_id);
                    $doctor_stmt->execute();
                } else {
                    $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", $edit_user_id, $license_number, $specialization, 
                                           $qualification, $experience_years, $consultation_fee, $commission_rate);
                    $doctor_stmt->execute();
                }
            }
            
            // Update nurse details if applicable
            if ($role_id == 5) { // Nurse
                $qualification = trim($_POST['qualification']);
                $shift_type = $_POST['shift_type'] ?: 'DAY';
                
                // Check if nurse record exists
                $check_nurse = $conn->prepare("SELECT nurse_id FROM nurses WHERE user_id = ?");
                $check_nurse->bind_param("i", $edit_user_id);
                $check_nurse->execute();
                $nurse_exists = $check_nurse->get_result()->num_rows > 0;
                
                if ($nurse_exists) {
                    $nurse_sql = "UPDATE nurses SET nursing_license=?, qualification=?, shift_type=?
                                 WHERE user_id=?";
                    $nurse_stmt = $conn->prepare($nurse_sql);
                    $nurse_stmt->bind_param("sssi", $license_number, $qualification, $shift_type, $edit_user_id);
                    $nurse_stmt->execute();
                } else {
                    $nurse_sql = "INSERT INTO nurses (user_id, nursing_license, qualification, shift_type) 
                                 VALUES (?, ?, ?, ?)";
                    $nurse_stmt = $conn->prepare($nurse_sql);
                    $nurse_stmt->bind_param("isss", $edit_user_id, $license_number, $qualification, $shift_type);
                    $nurse_stmt->execute();
                }
            }
            
            $success_message = "User updated successfully!";
            
            // Redirect after 2 seconds
            header("refresh:2;url=view_user.php?id=$edit_user_id");
        } else {
            $errors[] = "Error updating user: " . $conn->error;
        }
    }
}

// Fetch user details
$sql_user = "SELECT u.*, d.specialization, d.consultation_fee, d.qualification as doctor_qualification, 
             d.experience_years, n.qualification as nurse_qualification, n.shift_type
             FROM users u 
             LEFT JOIN doctors d ON u.user_id = d.user_id
             LEFT JOIN nurses n ON u.user_id = n.user_id
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $edit_user_id);
$stmt_user->execute();
$user = $stmt_user->get_result()->fetch_assoc();

if (!$user) {
    header('Location: list_users.php?error=User not found');
    exit();
}

// 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')
                     AND u.user_id != ?
                     ORDER BY u.full_name";
$supervisors_stmt = $conn->prepare($supervisors_query);
$supervisors_stmt->bind_param("i", $edit_user_id);
$supervisors_stmt->execute();
$supervisors_result = $supervisors_stmt->get_result();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit 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 add_user.php */
        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;
        }
        
        /* User Info Header */
        .user-info-header {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .user-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: #3b82f6;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1.25rem;
        }
        
        .user-basic-info h3 {
            margin: 0 0 0.25rem 0;
            color: #1e293b;
            font-size: 1.25rem;
            font-weight: 600;
        }
        
        .user-basic-info p {
            margin: 0;
            color: #64748b;
            font-size: 0.875rem;
        }
        
        /* 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">Edit User</h1>
                        <p class="page-subtitle">Update user information and settings</p>
                    </div>

                    <!-- Edit User Form -->
                    <div class="form-card">
                        <div class="user-info-header">
                            <div class="user-avatar">
                                <?php echo strtoupper(substr($user['full_name'], 0, 2)); ?>
                            </div>
                            <div class="user-basic-info">
                                <h3><?php echo htmlspecialchars($user['full_name']); ?></h3>
                                <p>@<?php echo htmlspecialchars($user['username']); ?> | <?php echo htmlspecialchars($user['email']); ?></p>
                            </div>
                        </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 user profile...</small>
                                </div>
                            <?php endif; ?>

                            <form method="POST" id="editUserForm">
                                <!-- 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($user['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($user['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($user['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($user['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 $user['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 $user['gender'] == 'MALE' ? 'selected' : ''; ?>>Male</option>
                                                <option value="FEMALE" <?php echo $user['gender'] == 'FEMALE' ? 'selected' : ''; ?>>Female</option>
                                                <option value="OTHER" <?php echo $user['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($user['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 $user['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 $user['status'] == 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                <option value="PENDING" <?php echo $user['status'] == 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                                <option value="INACTIVE" <?php echo $user['status'] == 'INACTIVE' ? 'selected' : ''; ?>>Inactive</option>
                                                <option value="SUSPENDED" <?php echo $user['status'] == 'SUSPENDED' ? 'selected' : ''; ?>>Suspended</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($user['staff_number']); ?>">
                                        </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 $user['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 $user['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 $user['hire_date']; ?>">
                                        </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 $user['commission_rate']; ?>" 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($user['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 $user['license_expiry']; ?>">
                                        </div>
                                    </div>
                                </div>

                                <!-- Doctor-specific fields -->
                                <div id="doctorFields" class="role-specific-fields <?php echo (in_array($user['role_id'], [3, 4])) ? 'show' : ''; ?>">
                                    <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($user['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 $user['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($user['doctor_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 $user['experience_years'] ?: '0'; ?>" min="0">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Nurse-specific fields -->
                                <div id="nurseFields" class="role-specific-fields <?php echo ($user['role_id'] == 5) ? 'show' : ''; ?>">
                                    <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($user['nurse_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 ($user['shift_type'] ?: 'DAY') == 'DAY' ? 'selected' : ''; ?>>Day Shift</option>
                                                    <option value="NIGHT" <?php echo $user['shift_type'] == 'NIGHT' ? 'selected' : ''; ?>>Night Shift</option>
                                                    <option value="ROTATING" <?php echo $user['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($user['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($user['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($user['emergency_phone']); ?>">
                                        </div>
                                    </div>
                                </div>

                                <!-- Form Actions -->
                                <div class="d-flex gap-3 mt-4">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="ph-floppy-disk me-1"></i> Update User
                                    </button>
                                    <a href="view_user.php?id=<?php echo $user['user_id']; ?>" class="btn btn-secondary">
                                        <i class="ph-arrow-left me-1"></i> Back to Profile
                                    </a>
                                    <a href="reset_password.php?id=<?php echo $user['user_id']; ?>" class="btn btn-warning"
                                       onclick="return confirm('Are you sure you want to reset this user\'s password?')">
                                        <i class="ph-lock-key me-1"></i> Reset Password
                                    </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');
                }
            }
            
            // Check when role changes
            $('#roleSelect').on('change', toggleRoleFields);
            
            // Form validation before submit
            $('#editUserForm').on('submit', function(e) {
                const username = $('input[name="username"]').val().trim();
                const email = $('input[name="email"]').val().trim();
                const fullName = $('input[name="full_name"]').val().trim();
                const phone = $('input[name="phone_number"]').val().trim();
                const role = $('select[name="role_id"]').val();
                
                if (!username || !email || !fullName || !phone || !role) {
                    e.preventDefault();
                    alert('Please fill in all required fields!');
                    return false;
                }
                
                // Email validation
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    e.preventDefault();
                    alert('Please enter a valid email address!');
                    return false;
                }
            });
        });
    </script>

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

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