<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Edit User
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging (remove in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct base path dynamically
$base_path = null;

// Method 1: Try going up 3 levels from current file
// Current file: /admin/users/edit.php
// Target: /config/config.php
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = dirname(dirname(dirname(__DIR__)));
}

// Method 3: Try with document root
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = $_SERVER['DOCUMENT_ROOT'] . '/HMSPOS';
}

// Method 4: Try one more absolute path for XAMPP
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 5: Try with current directory structure
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = realpath(__DIR__ . '/../../..');
}

// Method 6: Last resort - try parent of parent of current directory
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = __DIR__ . '/../..';
}

// Method 7: Try with the path from the current file's location
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = str_replace('\\', '/', dirname(__DIR__, 3));
}

// Verify config file exists
if (!file_exists($base_path . '/config/config.php')) {
    die('Critical Error: Cannot locate config.php. Please check file paths. Base path: ' . $base_path . '<br>Current directory: ' . __DIR__);
}

// Initialize system with error handling
try {
    require_once $base_path . '/config/config.php';
    
    // Check if constants.php exists
    if (file_exists($base_path . '/config/constants.php')) {
        require_once $base_path . '/config/constants.php';
    }
    
    // Check if database.php exists
    if (file_exists($base_path . '/config/database.php')) {
        require_once $base_path . '/config/database.php';
    }
    
    // Check if helpers.php exists
    if (file_exists($base_path . '/config/helpers.php')) {
        require_once $base_path . '/config/helpers.php';
    }
    
    // Check if auth.php exists
    if (file_exists($base_path . '/config/auth.php')) {
        require_once $base_path . '/config/auth.php';
    }
    
    // Check if csrf.php exists
    if (file_exists($base_path . '/config/csrf.php')) {
        require_once $base_path . '/config/csrf.php';
    }
    
} catch (Exception $e) {
    die('Error loading system files: ' . $e->getMessage());
}

// Define base_url function if not exists
if (!function_exists('base_url')) {
    function base_url($path = '') {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
        $host = $_SERVER['HTTP_HOST'];
        $script_name = $_SERVER['SCRIPT_NAME'];
        $dir = dirname(dirname(dirname($script_name)));
        return $protocol . $host . rtrim($dir, '/') . '/' . ltrim($path, '/');
    }
}

// Define escape_html function if not exists
if (!function_exists('escape_html')) {
    function escape_html($string) {
        return htmlspecialchars($string ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if not exists
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
}

// Define validate_email function if not exists
if (!function_exists('validate_email')) {
    function validate_email($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
}

// Define validate_phone function if not exists
if (!function_exists('validate_phone')) {
    function validate_phone($phone) {
        // Basic phone validation - adjust regex as needed
        return preg_match('/^[0-9+\-\s()]{10,20}$/', $phone);
    }
}

// Define log_message function if not exists
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        $log_file = dirname($base_path) . '/logs/app.log';
        $timestamp = date('Y-m-d H:i:s');
        $log_entry = "[$timestamp] [$level] $message" . PHP_EOL;
        
        // Create logs directory if it doesn't exist
        $log_dir = dirname($log_file);
        if (!is_dir($log_dir)) {
            mkdir($log_dir, 0777, true);
        }
        
        file_put_contents($log_file, $log_entry, FILE_APPEND);
    }
}

// Define set_flash_message function if not exists
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
        $_SESSION['flash_message'] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if not exists
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . base_url($url));
        exit;
    }
}

// Define begin_transaction function if not exists
if (!function_exists('begin_transaction')) {
    function begin_transaction() {
        if (function_exists('db_begin_transaction')) {
            db_begin_transaction();
        }
    }
}

// Define commit_transaction function if not exists
if (!function_exists('commit_transaction')) {
    function commit_transaction() {
        if (function_exists('db_commit')) {
            db_commit();
        }
    }
}

// Define rollback_transaction function if not exists
if (!function_exists('rollback_transaction')) {
    function rollback_transaction() {
        if (function_exists('db_rollback')) {
            db_rollback();
        }
    }
}

// Define create_notification function if not exists
if (!function_exists('create_notification')) {
    function create_notification($user_id, $type, $title, $message) {
        // Implement notification logic or just log it
        log_message("Notification for user $user_id: $title - $message", 'INFO');
    }
}

// Define constants if not defined
if (!defined('ROLE_SUPER_ADMIN')) {
    define('ROLE_SUPER_ADMIN', 1);
}

if (!defined('DEPT_ADMIN')) define('DEPT_ADMIN', 'Administration');
if (!defined('DEPT_IT')) define('DEPT_IT', 'IT');
if (!defined('DEPT_FRONT_OFFICE')) define('DEPT_FRONT_OFFICE', 'Front Office');
if (!defined('DEPT_FNB')) define('DEPT_FNB', 'Food & Beverage');
if (!defined('DEPT_HOUSEKEEPING')) define('DEPT_HOUSEKEEPING', 'Housekeeping');
if (!defined('DEPT_MAINTENANCE')) define('DEPT_MAINTENANCE', 'Maintenance');
if (!defined('DEPT_INVENTORY')) define('DEPT_INVENTORY', 'Inventory');
if (!defined('DEPT_FINANCE')) define('DEPT_FINANCE', 'Finance');
if (!defined('DEPT_GUEST_SERVICES')) define('DEPT_GUEST_SERVICES', 'Guest Services');
if (!defined('DEPT_SALES')) define('DEPT_SALES', 'Sales & Marketing');
if (!defined('DEPT_SECURITY')) define('DEPT_SECURITY', 'Security');

if (!defined('NOTIFICATION_INFO')) define('NOTIFICATION_INFO', 'info');

if (!defined('REGEX_USERNAME')) define('REGEX_USERNAME', '/^[a-zA-Z0-9_]{3,50}$/');
if (!defined('REGEX_NAME')) define('REGEX_NAME', '/^[a-zA-Z\s\'-]{2,50}$/');
if (!defined('REGEX_PASSWORD')) define('REGEX_PASSWORD', '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/');
if (!defined('BCRYPT_COST')) define('BCRYPT_COST', 10);

// Require authentication with error handling
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: ' . base_url('login.php'));
        exit;
    }
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('users.edit');
} elseif (function_exists('has_permission')) {
    if (!has_permission('users.edit')) {
        die('Access denied: You do not have permission to edit users.');
    }
}

// Set page title
$page_title = 'Edit User';

// Get current user
$current_user = [];
if (function_exists('current_user')) {
    $current_user = current_user();
} elseif (isset($_SESSION)) {
    $current_user = $_SESSION;
}

// Get user ID from URL
$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$user_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid user ID');
    }
    if (function_exists('redirect')) {
        redirect('admin/users/index.php');
    } else {
        header('Location: ' . base_url('admin/users/index.php'));
        exit;
    }
}

// Get user data with error handling
$user = null;
try {
    if (function_exists('db_fetch_one')) {
        $user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$user_id]);
    }
} catch (Exception $e) {
    die('Error loading user data: ' . $e->getMessage());
}

if (!$user) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'User not found');
    }
    if (function_exists('redirect')) {
        redirect('admin/users/index.php');
    } else {
        header('Location: ' . base_url('admin/users/index.php'));
        exit;
    }
}

// Prevent editing super admin if not super admin
if (($user['role_id'] ?? 0) == ROLE_SUPER_ADMIN && ($current_user['role_id'] ?? 0) != ROLE_SUPER_ADMIN) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'You cannot edit super admin users');
    }
    if (function_exists('redirect')) {
        redirect('admin/users/index.php');
    } else {
        header('Location: ' . base_url('admin/users/index.php'));
        exit;
    }
}

// Get all roles for dropdown with error handling
$roles = [];
try {
    if (function_exists('db_fetch_all')) {
        $roles = db_fetch_all("SELECT role_id, role_name FROM roles ORDER BY role_name") ?: [];
    }
} catch (Exception $e) {
    log_message("Error loading roles: " . $e->getMessage(), 'ERROR');
}

// Departments list
$departments = [
    DEPT_ADMIN,
    DEPT_IT,
    DEPT_FRONT_OFFICE,
    DEPT_FNB,
    DEPT_HOUSEKEEPING,
    DEPT_MAINTENANCE,
    DEPT_INVENTORY,
    DEPT_FINANCE,
    DEPT_GUEST_SERVICES,
    DEPT_SALES,
    DEPT_SECURITY
];

// Handle form submission
$errors = [];
$form_data = [
    'username' => $user['username'] ?? '',
    'email' => $user['email'] ?? '',
    'first_name' => $user['first_name'] ?? '',
    'last_name' => $user['last_name'] ?? '',
    'phone' => $user['phone'] ?? '',
    'role_id' => $user['role_id'] ?? 0,
    'department' => $user['department'] ?? '',
    'is_active' => $user['is_active'] ?? 1
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    $csrf_valid = false;
    
    if (function_exists('verify_csrf_token')) {
        $csrf_valid = verify_csrf_token($_POST[CSRF_TOKEN_NAME ?? 'csrf_token'] ?? '');
    } else {
        // Simple CSRF check
        session_start();
        $csrf_valid = (isset($_POST['csrf_token']) && isset($_SESSION['csrf_token']) && 
                      $_POST['csrf_token'] === $_SESSION['csrf_token']);
    }
    
    if (!$csrf_valid) {
        $errors[] = 'Invalid security token. Please try again.';
    } else {
        // Get and validate input
        $form_data['username'] = isset($_POST['username']) ? sanitize_input($_POST['username']) : '';
        $form_data['email'] = isset($_POST['email']) ? sanitize_input($_POST['email']) : '';
        $form_data['first_name'] = isset($_POST['first_name']) ? sanitize_input($_POST['first_name']) : '';
        $form_data['last_name'] = isset($_POST['last_name']) ? sanitize_input($_POST['last_name']) : '';
        $form_data['phone'] = isset($_POST['phone']) ? sanitize_input($_POST['phone']) : '';
        $form_data['role_id'] = isset($_POST['role_id']) ? (int)$_POST['role_id'] : 0;
        $form_data['department'] = isset($_POST['department']) ? sanitize_input($_POST['department']) : '';
        $form_data['is_active'] = isset($_POST['is_active']) ? 1 : 0;
        
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        // Validate required fields
        if (empty($form_data['username'])) {
            $errors[] = 'Username is required';
        } elseif (defined('REGEX_USERNAME') && !preg_match(REGEX_USERNAME, $form_data['username'])) {
            $errors[] = 'Username must be 3-50 characters and contain only letters, numbers, and underscores';
        }
        
        if (empty($form_data['email'])) {
            $errors[] = 'Email is required';
        } elseif (!validate_email($form_data['email'])) {
            $errors[] = 'Invalid email format';
        }
        
        if (empty($form_data['first_name'])) {
            $errors[] = 'First name is required';
        } elseif (defined('REGEX_NAME') && !preg_match(REGEX_NAME, $form_data['first_name'])) {
            $errors[] = 'First name must be 2-50 characters and contain only letters, spaces, hyphens, and apostrophes';
        }
        
        if (empty($form_data['last_name'])) {
            $errors[] = 'Last name is required';
        } elseif (defined('REGEX_NAME') && !preg_match(REGEX_NAME, $form_data['last_name'])) {
            $errors[] = 'Last name must be 2-50 characters and contain only letters, spaces, hyphens, and apostrophes';
        }
        
        if (empty($form_data['role_id'])) {
            $errors[] = 'Role is required';
        }
        
        // Prevent changing own role if it would remove edit permission
        if ($user_id == ($current_user['user_id'] ?? 0) && $form_data['role_id'] != ($user['role_id'] ?? 0)) {
            // Check if new role has user.edit permission
            $has_permission = 0;
            try {
                if (function_exists('db_fetch_value')) {
                    $has_permission = db_fetch_value("
                        SELECT COUNT(*) FROM role_permissions rp
                        JOIN permissions p ON rp.permission_id = p.permission_id
                        WHERE rp.role_id = ? AND p.permission_key = 'users.edit'
                    ", [$form_data['role_id']]);
                }
            } catch (Exception $e) {
                log_message("Error checking permission: " . $e->getMessage(), 'ERROR');
            }
            
            if (!$has_permission) {
                $errors[] = 'You cannot change your role to one that cannot edit users';
            }
        }
        
        if (!empty($form_data['phone']) && !validate_phone($form_data['phone'])) {
            $errors[] = 'Invalid phone number format';
        }
        
        // Validate password if provided
        if (!empty($password)) {
            if (strlen($password) < 8) {
                $errors[] = 'Password must be at least 8 characters long';
            } elseif (defined('REGEX_PASSWORD') && !preg_match(REGEX_PASSWORD, $password)) {
                $errors[] = 'Password must contain at least one uppercase letter, one lowercase letter, one number, and one special character';
            } elseif ($password !== $confirm_password) {
                $errors[] = 'Passwords do not match';
            }
        }
        
        // Check uniqueness
        if (empty($errors)) {
            try {
                // Check username
                if (function_exists('db_fetch_value')) {
                    $exists = db_fetch_value("SELECT COUNT(*) FROM users WHERE username = ? AND user_id != ?", 
                                             [$form_data['username'], $user_id]);
                    if ($exists > 0) {
                        $errors[] = 'Username already exists';
                    }
                    
                    // Check email
                    $exists = db_fetch_value("SELECT COUNT(*) FROM users WHERE email = ? AND user_id != ?", 
                                             [$form_data['email'], $user_id]);
                    if ($exists > 0) {
                        $errors[] = 'Email already exists';
                    }
                }
            } catch (Exception $e) {
                $errors[] = 'Error checking user data: ' . $e->getMessage();
                log_message("Error checking uniqueness: " . $e->getMessage(), 'ERROR');
            }
        }
        
        // Update user
        if (empty($errors)) {
            try {
                if (function_exists('begin_transaction')) {
                    begin_transaction();
                }
                
                $update_data = [
                    'username' => $form_data['username'],
                    'email' => $form_data['email'],
                    'first_name' => $form_data['first_name'],
                    'last_name' => $form_data['last_name'],
                    'phone' => $form_data['phone'] ?: null,
                    'role_id' => $form_data['role_id'],
                    'department' => $form_data['department'] ?: null,
                    'is_active' => $form_data['is_active']
                ];
                
                // Update password if provided
                if (!empty($password)) {
                    $update_data['password_hash'] = password_hash($password, PASSWORD_DEFAULT, ['cost' => BCRYPT_COST ?? 10]);
                }
                
                if (function_exists('db_update')) {
                    $result = db_update('users', $update_data, 'user_id = ?', [$user_id]);
                }
                
                // Audit log
                if (function_exists('audit_log')) {
                    audit_log($current_user['user_id'] ?? 0, AUDIT_UPDATE ?? 'update', 'users', $user_id, $user, $update_data);
                }
                
                // Create notification
                if (function_exists('create_notification')) {
                    create_notification(
                        $user_id,
                        NOTIFICATION_INFO ?? 'info',
                        'Account Updated',
                        'Your account information has been updated by an administrator.'
                    );
                }
                
                if (function_exists('commit_transaction')) {
                    commit_transaction();
                }
                
                if (function_exists('set_flash_message')) {
                    set_flash_message('success', 'User updated successfully');
                }
                
                // If editing own account, refresh session data
                if ($user_id == ($current_user['user_id'] ?? 0)) {
                    session_start();
                    $_SESSION['username'] = $form_data['username'];
                    $_SESSION['user_role'] = $form_data['role_id'];
                }
                
                if (function_exists('redirect')) {
                    redirect('admin/users/view.php?id=' . $user_id);
                } else {
                    header('Location: ' . base_url('admin/users/view.php?id=' . $user_id));
                    exit;
                }
                
            } catch (Exception $e) {
                if (function_exists('rollback_transaction')) {
                    rollback_transaction();
                }
                $errors[] = 'Failed to update user: ' . $e->getMessage();
                log_message("User update failed: " . $e->getMessage(), 'ERROR');
            }
        }
    }
}

// Include header with error handling
$header_file = $base_path . '/views/partials/header.php';
if (file_exists($header_file)) {
    require_once $header_file;
} else {
    // Fallback header
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title><?php echo $page_title; ?></title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
        <style>
            .content-header { padding: 20px; background: #f4f6f9; }
            .card { box-shadow: 0 0 1px rgba(0,0,0,.125), 0 1px 3px rgba(0,0,0,.2); margin-bottom: 20px; }
        </style>
    </head>
    <body>
    <?php
}
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Edit User: <?php echo escape_html($user['username'] ?? ''); ?></h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/dashboard.php'); ?>">Admin</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/users/index.php'); ?>">Users</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/users/view.php?id=' . $user_id); ?>">View</a></li>
                    <li class="breadcrumb-item active">Edit</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <!-- Error Messages -->
                <?php if (!empty($errors)): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle mr-2"></i>
                        <strong>Please fix the following errors:</strong>
                        <ul class="mt-2 mb-0">
                            <?php foreach ($errors as $error): ?>
                                <li><?php echo $error; ?></li>
                            <?php endforeach; ?>
                        </ul>
                        <button type="button" class="close" data-dismiss="alert">&times;</button>
                    </div>
                <?php endif; ?>

                <!-- Warning for editing own account -->
                <?php if (($user_id ?? 0) == ($current_user['user_id'] ?? 0)): ?>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle mr-2"></i>
                        <strong>You are editing your own account.</strong> Be careful not to lock yourself out.
                    </div>
                <?php endif; ?>

                <!-- Edit User Form -->
                <div class="card card-warning">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-edit mr-1"></i>
                            Edit User Information
                        </h3>
                    </div>
                    
                    <form method="POST" id="editUserForm">
                        <?php 
                        if (function_exists('csrf_field')) {
                            echo csrf_field();
                        } else {
                            // Simple CSRF field
                            $csrf_token = bin2hex(random_bytes(32));
                            session_start();
                            $_SESSION['csrf_token'] = $csrf_token;
                            echo '<input type="hidden" name="csrf_token" value="' . $csrf_token . '">';
                        }
                        ?>
                        
                        <div class="card-body">
                            <!-- Basic Information -->
                            <h5 class="mb-3">Basic Information</h5>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="username">Username <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="username" name="username" 
                                               value="<?php echo escape_html($form_data['username'] ?? ''); ?>" 
                                               required maxlength="50">
                                        <small class="text-muted">3-50 characters, letters, numbers, and underscores only</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="email">Email <span class="text-danger">*</span></label>
                                        <input type="email" class="form-control" id="email" name="email" 
                                               value="<?php echo escape_html($form_data['email'] ?? ''); ?>" 
                                               required maxlength="100">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="first_name">First Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="first_name" name="first_name" 
                                               value="<?php echo escape_html($form_data['first_name'] ?? ''); ?>" 
                                               required maxlength="50">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="last_name">Last Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="last_name" name="last_name" 
                                               value="<?php echo escape_html($form_data['last_name'] ?? ''); ?>" 
                                               required maxlength="50">
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <label for="phone">Phone Number</label>
                                <input type="tel" class="form-control" id="phone" name="phone" 
                                       value="<?php echo escape_html($form_data['phone'] ?? ''); ?>" 
                                       maxlength="20" placeholder="+250788123456">
                            </div>
                            
                            <!-- Account Settings -->
                            <h5 class="mb-3 mt-4">Account Settings</h5>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="role_id">Role <span class="text-danger">*</span></label>
                                        <select class="form-control select2" id="role_id" name="role_id" required>
                                            <option value="">Select Role</option>
                                            <?php foreach ($roles as $role): ?>
                                                <option value="<?php echo $role['role_id'] ?? ''; ?>" 
                                                        <?php echo ($form_data['role_id'] ?? 0) == ($role['role_id'] ?? 0) ? 'selected' : ''; ?>
                                                        <?php echo (($role['role_id'] ?? 0) == ROLE_SUPER_ADMIN && ($current_user['role_id'] ?? 0) != ROLE_SUPER_ADMIN) ? 'disabled' : ''; ?>>
                                                    <?php echo escape_html($role['role_name'] ?? ''); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="department">Department</label>
                                        <select class="form-control select2" id="department" name="department">
                                            <option value="">Select Department</option>
                                            <?php foreach ($departments as $dept): ?>
                                                <option value="<?php echo $dept; ?>" 
                                                        <?php echo ($form_data['department'] ?? '') == $dept ? 'selected' : ''; ?>>
                                                    <?php echo $dept; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group">
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="is_active" name="is_active" 
                                           <?php echo ($form_data['is_active'] ?? 1) ? 'checked' : ''; ?>
                                           <?php echo (($user_id ?? 0) == ($current_user['user_id'] ?? 0)) ? 'disabled' : ''; ?>>
                                    <label class="custom-control-label" for="is_active">Active</label>
                                </div>
                                <?php if (($user_id ?? 0) == ($current_user['user_id'] ?? 0)): ?>
                                    <small class="text-muted">You cannot deactivate your own account</small>
                                <?php else: ?>
                                    <small class="text-muted">Inactive users cannot log in to the system</small>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Password Change (Optional) -->
                            <h5 class="mb-3 mt-4">Change Password</h5>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle mr-2"></i>
                                Leave password fields empty to keep current password.
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="password">New Password</label>
                                        <input type="password" class="form-control" id="password" name="password" 
                                               minlength="8">
                                        <div class="progress mt-2" style="height: 5px;">
                                            <div class="progress-bar" id="passwordStrength" role="progressbar" style="width: 0%;"></div>
                                        </div>
                                        <small class="text-muted" id="passwordStrengthText">Enter new password to change</small>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="confirm_password">Confirm New Password</label>
                                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" 
                                               minlength="8">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning" id="submitBtn">
                                <i class="fas fa-save mr-1"></i> Update User
                            </button>
                            <a href="<?php echo base_url('admin/users/view.php?id=' . $user_id); ?>" class="btn btn-secondary">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Include jQuery and Bootstrap -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
$(document).ready(function() {
    // Password strength checker
    $('#password').on('input', function() {
        const password = $(this).val();
        let strength = 0;
        const $strengthBar = $('#passwordStrength');
        const $strengthText = $('#passwordStrengthText');
        
        if (password.length === 0) {
            $strengthBar.css('width', '0%');
            $strengthText.text('Enter new password to change');
            return;
        }
        
        // Length check
        if (password.length >= 8) strength += 25;
        
        // Uppercase check
        if (/[A-Z]/.test(password)) strength += 25;
        
        // Lowercase check
        if (/[a-z]/.test(password)) strength += 25;
        
        // Number check
        if (/[0-9]/.test(password)) strength += 12.5;
        
        // Special character check
        if (/[@$!%*?&]/.test(password)) strength += 12.5;
        
        $strengthBar.css('width', strength + '%');
        
        if (strength < 50) {
            $strengthBar.removeClass('bg-success bg-info bg-warning').addClass('bg-danger');
            $strengthText.text('Weak password');
        } else if (strength < 75) {
            $strengthBar.removeClass('bg-danger bg-success bg-warning').addClass('bg-warning');
            $strengthText.text('Medium password');
        } else if (strength < 90) {
            $strengthBar.removeClass('bg-danger bg-warning bg-success').addClass('bg-info');
            $strengthText.text('Strong password');
        } else {
            $strengthBar.removeClass('bg-danger bg-warning bg-info').addClass('bg-success');
            $strengthText.text('Very strong password');
        }
    });
    
    // Password match validation
    $('#confirm_password').on('input', function() {
        const password = $('#password').val();
        const confirm = $(this).val();
        
        // Skip if both are empty (no password change)
        if (password === '' && confirm === '') {
            $(this).removeClass('is-invalid');
            $(this).next('.invalid-feedback').remove();
            return;
        }
        
        if (password !== confirm) {
            $(this).addClass('is-invalid');
            if ($(this).next('.invalid-feedback').length === 0) {
                $(this).after('<div class="invalid-feedback">Passwords do not match</div>');
            }
        } else {
            $(this).removeClass('is-invalid');
            $(this).next('.invalid-feedback').remove();
        }
    });
    
    // Form validation
    $('#editUserForm').on('submit', function(e) {
        const password = $('#password').val();
        const confirm = $('#confirm_password').val();
        
        // If password fields are not empty, validate them
        if (password !== '' || confirm !== '') {
            if (password !== confirm) {
                e.preventDefault();
                alert('Passwords do not match');
                return;
            }
            
            // Check password strength (at least 50%)
            const strength = calculatePasswordStrength(password);
            if (strength < 50) {
                e.preventDefault();
                alert('Password is too weak');
                return;
            }
        }
    });
    
    function calculatePasswordStrength(password) {
        let strength = 0;
        if (password.length >= 8) strength += 25;
        if (/[A-Z]/.test(password)) strength += 25;
        if (/[a-z]/.test(password)) strength += 25;
        if (/[0-9]/.test(password)) strength += 12.5;
        if (/[@$!%*?&]/.test(password)) strength += 12.5;
        return strength;
    }
    
    // Username availability check
    let usernameTimeout;
    $('#username').on('input', function() {
        clearTimeout(usernameTimeout);
        const username = $(this).val();
        const originalUsername = '<?php echo addslashes($user['username'] ?? ''); ?>';
        
        if (username.length < 3 || username === originalUsername) return;
        
        usernameTimeout = setTimeout(function() {
            $.get('<?php echo base_url('api/check-username.php'); ?>', { 
                username: username,
                exclude: <?php echo $user_id; ?>
            }, function(response) {
                const $username = $('#username');
                if (response && response.exists) {
                    $username.addClass('is-invalid');
                    if ($username.next('.invalid-feedback').length === 0) {
                        $username.after('<div class="invalid-feedback">Username already exists</div>');
                    }
                } else {
                    $username.removeClass('is-invalid');
                    $username.next('.invalid-feedback').remove();
                }
            }).fail(function() {
                // Silently fail if API doesn't exist
            });
        }, 500);
    });
    
    // Email availability check
    let emailTimeout;
    $('#email').on('input', function() {
        clearTimeout(emailTimeout);
        const email = $(this).val();
        const originalEmail = '<?php echo addslashes($user['email'] ?? ''); ?>';
        
        if (!email || !isValidEmail(email) || email === originalEmail) return;
        
        emailTimeout = setTimeout(function() {
            $.get('<?php echo base_url('api/check-email.php'); ?>', { 
                email: email,
                exclude: <?php echo $user_id; ?>
            }, function(response) {
                const $email = $('#email');
                if (response && response.exists) {
                    $email.addClass('is-invalid');
                    if ($email.next('.invalid-feedback').length === 0) {
                        $email.after('<div class="invalid-feedback">Email already exists</div>');
                    }
                } else {
                    $email.removeClass('is-invalid');
                    $email.next('.invalid-feedback').remove();
                }
            }).fail(function() {
                // Silently fail if API doesn't exist
            });
        }, 500);
    });
    
    function isValidEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
});
</script>

<?php
// Include footer with error handling
$footer_file = $base_path . '/views/partials/footer.php';
if (file_exists($footer_file)) {
    require_once $footer_file;
} else {
    echo '</body></html>';
}
?>