<?php
$title = 'Edit User';
$active = 'users';
require_once __DIR__ . '/../layouts/header.php';
require_once __DIR__ . '/../layouts/sidebar.php';

// Check if user exists
if (!isset($user) || empty($user)) {
    $_SESSION['error'] = 'User not found';
    header('Location: ' . BASE_URL . '/users');
    exit;
}

$errors = Session::get('errors', []);
Session::remove('errors');

// Get user's current role IDs
$userRoleIds = [];
if (!empty($user['id'])) {
    $userRoles = Database::fetchAll("SELECT role_id FROM user_roles WHERE user_id = ?", [$user['id']]);
    if ($userRoles) {
        $userRoleIds = array_column($userRoles, 'role_id');
    }
}

// NIS Ranks in hierarchical order
$nisRanks = [
    'CGIS' => 'Comptroller General of Immigration Service',
    'DCG' => 'Deputy Comptroller General',
    'ACG' => 'Assistant Comptroller General',
    'CIS' => 'Comptroller of Immigration Service',
    'DCI' => 'Deputy Comptroller of Immigration',
    'ACI' => 'Assistant Comptroller of Immigration',
    'CSI' => 'Chief Superintendent of Immigration',
    'SI' => 'Superintendent of Immigration',
    'DSI' => 'Deputy Superintendent of Immigration',
    'ASI-1' => 'Assistant Superintendent of Immigration I',
    'ASI-2' => 'Assistant Superintendent of Immigration II',
    'II' => 'Inspector of Immigration',
    'AII' => 'Assistant Inspector of Immigration',
    'IA1' => 'Immigration Assistant I',
    'IA2' => 'Immigration Assistant II',
    'IA3' => 'Immigration Assistant III'
];

// Get all zones for dropdown
$zones = Database::fetchAll("SELECT * FROM zones ORDER BY zone_name");
if ($zones === false) $zones = [];

// Get all roles
$roles = Database::fetchAll("SELECT * FROM roles ORDER BY role_name");
if ($roles === false) $roles = [];

// Get user's current zone (if they have a command)
$currentZoneId = null;
if (!empty($user['command_id'])) {
    $command = Database::fetchOne("SELECT zone_id FROM commands WHERE id = ?", [$user['command_id']]);
    $currentZoneId = $command ? $command['zone_id'] : null;
}

// Generate CSRF token
$csrfToken = isset($_SESSION['csrf_token']) ? $_SESSION['csrf_token'] : bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $csrfToken;
?>

<div class="container-fluid">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-content">
            <h1>
                <i class="fas fa-user-edit"></i>
                Edit User: <?php echo htmlspecialchars($user['username'] ?? ''); ?>
            </h1>
            <p>Update user account information</p>
        </div>
        <div class="header-actions">
            <a href="<?php echo BASE_URL; ?>/users/show/<?php echo $user['id'] ?? ''; ?>" class="btn btn-info">
                <i class="fas fa-eye"></i> View Details
            </a>
            <a href="<?php echo BASE_URL; ?>/users" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Users
            </a>
        </div>
    </div>

    <!-- Display any errors -->
    <?php if (!empty($errors)): ?>
    <div class="alert alert-danger">
        <h4>Please fix the following errors:</h4>
        <ul>
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars(is_array($error) ? implode(', ', $error) : $error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>

    <!-- User Form -->
    <div class="form-section">
        <form method="POST" action="<?php echo BASE_URL; ?>/users/update/<?php echo $user['id'] ?? ''; ?>" id="userForm">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
            
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-user-circle"></i> Account Information</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Username</label>
                        <input type="text" name="username" id="username" 
                               value="<?php echo htmlspecialchars($user['username'] ?? ''); ?>" 
                               required maxlength="50" class="form-control <?php echo isset($errors['username']) ? 'error' : ''; ?>">
                        <?php if (isset($errors['username'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['username']); ?></small>
                        <?php endif; ?>
                        <small class="form-hint">3-50 characters, letters, numbers, and underscore only</small>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Email Address</label>
                        <input type="email" name="email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" 
                               required maxlength="100" class="form-control <?php echo isset($errors['email']) ? 'error' : ''; ?>">
                        <?php if (isset($errors['email'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['email']); ?></small>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label>New Password (leave blank to keep current)</label>
                        <div class="input-with-icon">
                            <i class="fas fa-lock"></i>
                            <input type="password" name="password" id="password" 
                                   minlength="8" class="form-control <?php echo isset($errors['password']) ? 'error' : ''; ?>">
                            <button type="button" class="password-toggle" data-target="password">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <?php if (isset($errors['password'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['password']); ?></small>
                        <?php endif; ?>
                        <small class="form-hint">Minimum 8 characters with uppercase, lowercase, number and special character</small>
                        <div class="strength-meter" id="passwordStrength"></div>
                    </div>
                    
                    <div class="form-group">
                        <label>Confirm New Password</label>
                        <div class="input-with-icon">
                            <i class="fas fa-lock"></i>
                            <input type="password" name="confirm_password" id="confirm_password" 
                                   class="form-control <?php echo isset($errors['confirm_password']) ? 'error' : ''; ?>">
                            <button type="button" class="password-toggle" data-target="confirm_password">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <?php if (isset($errors['confirm_password'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['confirm_password']); ?></small>
                        <?php endif; ?>
                        <small id="passwordMatch" class="form-hint"></small>
                    </div>
                </div>
            </div>
            
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-id-card"></i> Personal Information</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Full Name</label>
                        <input type="text" name="full_name" value="<?php echo htmlspecialchars($user['full_name'] ?? ''); ?>" 
                               required maxlength="100" class="form-control <?php echo isset($errors['full_name']) ? 'error' : ''; ?>">
                        <?php if (isset($errors['full_name'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['full_name']); ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">NIS Number</label>
                        <input type="text" name="nis_number" value="<?php echo htmlspecialchars($user['nis_number'] ?? ''); ?>" 
                               required maxlength="50" class="form-control <?php echo isset($errors['nis_number']) ? 'error' : ''; ?>">
                        <?php if (isset($errors['nis_number'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['nis_number']); ?></small>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Rank</label>
                        <select name="rank" id="rank" required class="form-control <?php echo isset($errors['rank']) ? 'error' : ''; ?>">
                            <option value="">Select Rank</option>
                            <?php foreach ($nisRanks as $rankCode => $rankTitle): ?>
                                <option value="<?php echo $rankCode; ?>" <?php echo ($user['rank'] ?? '') == $rankCode ? 'selected' : ''; ?>>
                                    <?php echo $rankCode . ' - ' . $rankTitle; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (isset($errors['rank'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['rank']); ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Phone Number</label>
                        <input type="tel" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" 
                               required maxlength="20" class="form-control <?php echo isset($errors['phone']) ? 'error' : ''; ?>">
                        <?php if (isset($errors['phone'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['phone']); ?></small>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-building"></i> Command Assignment</h3>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">Zone</label>
                        <select name="zone_id" id="zone_id" required 
                                class="form-control <?php echo isset($errors['zone_id']) ? 'error' : ''; ?>">
                            <option value="">Select Zone</option>
                            <?php foreach ($zones as $zone): ?>
                            <option value="<?php echo $zone['id']; ?>" 
                                    <?php echo ($currentZoneId == $zone['id']) ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($zone['zone_name'] . ' - ' . ($zone['zone_headquarters'] ?? '')); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (isset($errors['zone_id'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['zone_id']); ?></small>
                        <?php endif; ?>
                    </div>
                    
                    <div class="form-group">
                        <label class="required">Command</label>
                        <select name="command_id" id="command_id" required 
                                class="form-control <?php echo isset($errors['command_id']) ? 'error' : ''; ?>">
                            <option value="">Select Zone First</option>
                        </select>
                        <?php if (isset($errors['command_id'])): ?>
                            <small class="error-text"><?php echo htmlspecialchars($errors['command_id']); ?></small>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <div class="form-section-inner">
                <div class="section-title">
                    <h3><i class="fas fa-user-tag"></i> Role Assignment</h3>
                </div>
                
                <div class="checkbox-group">
                    <?php foreach ($roles as $role): ?>
                    <label class="checkbox-container">
                        <input type="checkbox" name="roles[]" value="<?php echo $role['id']; ?>" 
                               <?php echo in_array($role['id'], $userRoleIds) ? 'checked' : ''; ?>>
                        <span class="checkmark"></span>
                        <span class="checkbox-label">
                            <strong><?php echo htmlspecialchars($role['role_name']); ?></strong>
                            <?php if ($role['description']): ?>
                                <br><small><?php echo htmlspecialchars($role['description']); ?></small>
                            <?php endif; ?>
                        </span>
                    </label>
                    <?php endforeach; ?>
                </div>
                <?php if (isset($errors['roles'])): ?>
                    <small class="error-text"><?php echo htmlspecialchars($errors['roles']); ?></small>
                <?php endif; ?>
            </div>
            
            <div class="form-group">
                <label class="checkbox-container">
                    <input type="checkbox" name="is_active" value="1" <?php echo ($user['is_active'] ?? 0) ? 'checked' : ''; ?>>
                    <span class="checkmark"></span>
                    <span class="checkbox-label">Account Active</span>
                </label>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-success submit-btn">
                    <i class="fas fa-save"></i> Update User
                </button>
                <a href="<?php echo BASE_URL; ?>/users" class="btn btn-secondary">
                    <i class="fas fa-times"></i> Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<style>
/* Add alert styles */
.alert {
    padding: 15px 20px;
    border-radius: 6px;
    margin-bottom: 20px;
}

.alert-danger {
    background: #fee;
    color: #c00;
    border-left: 4px solid #c00;
}

.alert-danger ul {
    margin: 10px 0 0 20px;
}

.alert-danger li {
    color: #c00;
}

:root {
    --primary-color: #2c3e50;
    --primary-light: #27ae60;
    --secondary-color: #27ae60;
    --secondary-dark: #219a52;
    --success-color: #27ae60;
    --danger-color: #e53e3e;
    --warning-color: #f39c12;
    --info-color: #3498db;
    --light-bg: #f8f9fa;
    --border-color: #e2e8f0;
    --text-primary: #2c3e50;
    --text-secondary: #7f8c8d;
}

.form-section {
    background: white;
    border-radius: 10px;
    padding: 25px;
    margin-bottom: 25px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.form-section-inner {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--border-color);
}

.form-section-inner:last-child {
    border-bottom: none;
    margin-bottom: 0;
    padding-bottom: 0;
}

.section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.section-title h3 {
    margin: 0;
    font-size: 1.2rem;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 8px;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    margin-bottom: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-group label {
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 8px;
}

.required::after {
    content: " *";
    color: var(--danger-color);
}

.form-control, .form-group select, .form-group input {
    padding: 10px 12px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    font-size: 0.95rem;
    transition: all 0.3s;
    width: 100%;
}

.form-control:focus, .form-group select:focus, .form-group input:focus {
    outline: none;
    border-color: var(--success-color);
    box-shadow: 0 0 0 3px rgba(39, 174, 96, 0.2);
}

.form-control.error, .form-group select.error, .form-group input.error {
    border-color: var(--danger-color);
    background-color: #fff5f5;
}

.error-text {
    color: var(--danger-color);
    font-size: 0.85rem;
    margin-top: 5px;
}

.form-hint {
    font-size: 0.8rem;
    color: var(--text-secondary);
    margin-top: 5px;
}

.input-with-icon {
    position: relative;
    display: flex;
    align-items: center;
}

.input-with-icon i {
    position: absolute;
    left: 12px;
    color: #999;
}

.input-with-icon input {
    padding-left: 35px;
    padding-right: 35px;
}

.password-toggle {
    position: absolute;
    right: 8px;
    background: transparent;
    border: none;
    color: #999;
    cursor: pointer;
    padding: 5px;
}

.password-toggle:hover {
    color: var(--success-color);
}

.strength-meter {
    margin-top: 5px;
    font-size: 0.8rem;
    font-weight: 600;
}

.checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 10px;
    max-height: 300px;
    overflow-y: auto;
    padding: 10px;
    border: 1px solid var(--border-color);
    border-radius: 6px;
}

.checkbox-container {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    cursor: pointer;
    padding: 8px;
    border-radius: 4px;
    transition: background 0.3s;
}

.checkbox-container:hover {
    background: var(--light-bg);
}

.checkbox-container input[type="checkbox"] {
    display: none;
}

.checkmark {
    width: 18px;
    height: 18px;
    border: 2px solid var(--success-color);
    border-radius: 3px;
    margin-top: 2px;
    position: relative;
    flex-shrink: 0;
}

.checkbox-container input[type="checkbox"]:checked + .checkmark {
    background: var(--success-color);
    border-color: var(--success-color);
}

.checkbox-container input[type="checkbox"]:checked + .checkmark::after {
    content: '✓';
    position: absolute;
    color: white;
    font-size: 12px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.checkbox-label {
    font-size: 0.9rem;
    line-height: 1.4;
}

.checkbox-label strong {
    color: var(--text-primary);
}

.checkbox-label small {
    color: var(--text-secondary);
}

.form-actions {
    display: flex;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid var(--border-color);
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
}

.btn-info {
    background: var(--info-color);
    color: white;
}

.btn-info:hover {
    background: #2980b9;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(52, 152, 219, 0.3);
}

.btn-success {
    background: var(--success-color);
    color: white;
}

.btn-success:hover {
    background: var(--secondary-dark);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(39, 174, 96, 0.3);
}

.btn-secondary {
    background: var(--text-secondary);
    color: white;
}

.btn-secondary:hover {
    background: #6c757d;
}

.submit-btn {
    min-width: 150px;
}

.text-success {
    color: var(--success-color);
}

.text-danger {
    color: var(--danger-color);
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
        gap: 15px;
    }
    
    .form-actions {
        flex-direction: column;
    }
    
    .form-actions .btn {
        width: 100%;
    }
    
    .page-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
    
    .header-actions {
        width: 100%;
        flex-direction: column;
    }
    
    .header-actions .btn {
        width: 100%;
        justify-content: center;
    }
}
</style>

<script>
// Define base URL for API calls
const baseUrl = '<?php echo BASE_URL; ?>';

function debug(message, data = null) {
    console.log(message, data);
}

document.addEventListener('DOMContentLoaded', function() {
    debug('Page loaded');
    debug('Base URL:', baseUrl);
    
    // Password toggle
    document.querySelectorAll('.password-toggle').forEach(button => {
        button.addEventListener('click', function() {
            const targetId = this.dataset.target;
            const input = document.getElementById(targetId);
            const icon = this.querySelector('i');
            
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        });
    });

    // Password strength checker
    function checkPasswordStrength(password) {
        let strength = 0;
        
        if (password.length >= 8) strength++;
        if (password.length >= 12) strength++;
        if (/[A-Z]/.test(password)) strength++;
        if (/[a-z]/.test(password)) strength++;
        if (/[0-9]/.test(password)) strength++;
        if (/[^A-Za-z0-9]/.test(password)) strength++;
        
        return Math.min(strength, 4);
    }

    const passwordInput = document.getElementById('password');
    if (passwordInput) {
        passwordInput.addEventListener('input', function() {
            const strength = checkPasswordStrength(this.value);
            const meter = document.getElementById('passwordStrength');
            
            const messages = ['Weak', 'Fair', 'Good', 'Strong', 'Very Strong'];
            const colors = ['#e74c3c', '#e67e22', '#f39c12', '#27ae60', '#2ecc71'];
            
            meter.textContent = 'Password Strength: ' + messages[strength];
            meter.style.color = colors[strength];
        });
    }

    // Password match validation
    const confirmPassword = document.getElementById('confirm_password');
    const password = document.getElementById('password');
    const passwordMatch = document.getElementById('passwordMatch');
    
    if (confirmPassword && password) {
        confirmPassword.addEventListener('input', function() {
            const newPass = password.value;
            
            if (this.value === newPass) {
                passwordMatch.innerHTML = '<span class="text-success">✓ Passwords match</span>';
                this.setCustomValidity('');
            } else {
                passwordMatch.innerHTML = '<span class="text-danger">✗ Passwords do not match</span>';
                this.setCustomValidity('Passwords do not match');
            }
        });
    }

    // Username validation
    const usernameInput = document.getElementById('username');
    if (usernameInput) {
        usernameInput.addEventListener('input', function() {
            this.value = this.value.replace(/[^a-zA-Z0-9_]/g, '');
        });
    }
    
    // Zone to Command dropdown
    const zoneSelect = document.getElementById('zone_id');
    const commandSelect = document.getElementById('command_id');
    
    if (zoneSelect && commandSelect) {
        debug('Zone select found');
        
        zoneSelect.addEventListener('change', function() {
            const zoneId = this.value;
            debug('Zone selected:', zoneId);
            
            if (!zoneId) {
                commandSelect.innerHTML = '<option value="">Select Zone First</option>';
                commandSelect.disabled = true;
                return;
            }
            
            // Show loading
            commandSelect.innerHTML = '<option value="">Loading commands...</option>';
            commandSelect.disabled = true;
            
            // Construct the API URL correctly
            const apiUrl = baseUrl + '/api/get_commands.php?zone_id=' + zoneId;
            debug('Fetching commands from:', apiUrl);
            
            fetch(apiUrl)
                .then(response => {
                    debug('Response status:', response.status);
                    if (!response.ok) {
                        throw new Error('HTTP error! status: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    debug('Received data:', data);
                    
                    commandSelect.innerHTML = '<option value="">Select Command</option>';
                    
                    if (data && data.length > 0) {
                        data.forEach(command => {
                            const option = document.createElement('option');
                            option.value = command.id;
                            option.textContent = command.command_name;
                            commandSelect.appendChild(option);
                        });
                        debug('Added ' + data.length + ' commands');
                        
                        // Set the previously selected command if any
                        <?php if (!empty($user['command_id'])): ?>
                        commandSelect.value = '<?php echo $user['command_id']; ?>';
                        <?php endif; ?>
                        
                        commandSelect.disabled = false;
                    } else {
                        commandSelect.innerHTML = '<option value="">No commands found for this zone</option>';
                        commandSelect.disabled = true;
                        debug('No commands found');
                    }
                })
                .catch(error => {
                    console.error('Fetch Error:', error);
                    debug('Fetch Error:', error.message);
                    commandSelect.innerHTML = '<option value="">Error loading commands: ' + error.message + '</option>';
                    commandSelect.disabled = true;
                });
        });
        
        // Trigger change to load commands for the current zone
        <?php if (!empty($currentZoneId)): ?>
        setTimeout(function() {
            zoneSelect.value = '<?php echo $currentZoneId; ?>';
            zoneSelect.dispatchEvent(new Event('change'));
        }, 100);
        <?php endif; ?>
    } else {
        debug('Zone select or command select not found');
    }

    // Form validation
    const userForm = document.getElementById('userForm');
    if (userForm) {
        userForm.addEventListener('submit', function(e) {
            const password = document.getElementById('password').value;
            const confirm = document.getElementById('confirm_password').value;
            
            if (password || confirm) {
                if (password !== confirm) {
                    e.preventDefault();
                    alert('Passwords do not match');
                    return false;
                }
                
                if (password.length < 8 && password.length > 0) {
                    e.preventDefault();
                    alert('Password must be at least 8 characters');
                    return false;
                }
            }
            
            // Check if at least one role is selected
            const roles = document.querySelectorAll('input[name="roles[]"]:checked');
            if (roles.length === 0) {
                e.preventDefault();
                alert('Please select at least one role');
                return false;
            }
            
            const command = document.getElementById('command_id').value;
            if (!command || command === '') {
                e.preventDefault();
                alert('Please select a command');
                return false;
            }
        });
    }
});
</script>

<?php
require_once __DIR__ . '/../layouts/footer.php';
?>