<div class="container-fluid">
<div class="row">
	<div class="col-12">
            
            <!-- Header Section -->
            <div class="card bg-primary text-white border-0 shadow-sm mb-4">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h4 class="fw-bold text-white mb-1">
                                <i class="bi bi-shield-check me-2"></i>
                                <?= !empty($user->id) ? __('admin.edit_admin_user') : __('admin.create_admin_user') ?>
                            </h4>
                            <p class="text-light opacity-75 mb-0">
                                <?= !empty($user->id) ? __('admin.update_admin_details') : __('admin.create_new_admin_desc') ?>
                            </p>
                        </div>
                        <a class="btn btn-light" href="<?= base_url('admincontrol/admin_user/') ?>">
                            <i class="bi bi-arrow-left me-2"></i><?= __('admin.back_to_admins') ?>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Form Section -->
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <div class="card shadow-sm border-0">
                        <div class="card-header bg-light border-0">
                            <h6 class="fw-bold mb-0">
                                <i class="bi bi-person-gear me-2"></i><?= __('admin.admin_information') ?>
                            </h6>
			</div>
                        <div class="card-body p-4">
                            <form id="admin-form" novalidate>
					<input type="hidden" name="user_id" value="<?= (int)$user->id ?>">

                                <!-- Personal Information -->
                                <div class="mb-4">
                                    <h6 class="fw-bold text-primary mb-3">
                                        <i class="bi bi-person me-2"></i><?= __('admin.personal_information') ?>
                                    </h6>
                                    
                                    <div class="row g-3 mb-3">
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <?= __('admin.first_name') ?> <span class="text-danger">*</span>
                                            </label>
                                            <input type="text" name="firstname" class="form-control form-control-lg" 
                                                   placeholder="<?= __('admin.enter_your_first_name') ?>"
                                                   value="<?= htmlspecialchars($user->firstname ?? '') ?>" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <?= __('admin.last_name') ?> <span class="text-danger">*</span>
                                            </label>
                                            <input type="text" name="lastname" class="form-control form-control-lg" 
                                                   placeholder="<?= __('admin.enter_your_last_name') ?>"
                                                   value="<?= htmlspecialchars($user->lastname ?? '') ?>" required>
							</div>
						</div>

                                    <div class="mb-3">
                                        <label class="form-label fw-bold">
                                            <i class="bi bi-telephone me-1"></i><?= __('admin.phone_number') ?>
                                        </label>
                                        <input type="tel" name="PhoneNumber" class="form-control" 
                                               placeholder="<?= __('admin.enter_your_mobile_number') ?>"
                                               value="<?= htmlspecialchars($user->PhoneNumber ?? '') ?>">
						</div>
					</div>

                                <!-- Account Information -->
                                <div class="mb-4">
                                    <h6 class="fw-bold text-primary mb-3">
                                        <i class="bi bi-key me-2"></i><?= __('admin.account_information') ?>
                                    </h6>
                                    
                                    <div class="mb-3">
                                        <label class="form-label fw-bold">
                                            <i class="bi bi-envelope me-1"></i><?= __('admin.email_address') ?> <span class="text-danger">*</span>
                                        </label>
                                        <input type="email" name="email" class="form-control form-control-lg" 
                                               placeholder="<?= __('admin.enter_your_email_address') ?>"
                                               value="<?= htmlspecialchars($user->email ?? '') ?>" required>
					</div>

                                    <div class="mb-3">
                                        <label class="form-label fw-bold">
                                            <i class="bi bi-person-badge me-1"></i><?= __('admin.username') ?> <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" name="username" class="form-control form-control-lg" 
                                               placeholder="<?= __('admin.enter_username_address') ?>"
                                               value="<?= htmlspecialchars($user->username ?? '') ?>" required>
					</div>

                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <i class="bi bi-lock me-1"></i><?= __('admin.password') ?>
                                                <?= empty($user->id) ? '<span class="text-danger">*</span>' : '' ?>
                                            </label>
                                            <input type="password" name="password" class="form-control" 
                                                   placeholder="<?= __('admin.enter_password') ?>"
                                                   <?= empty($user->id) ? 'required' : '' ?>>
                                            <?php if (!empty($user->id)): ?>
                                                <div class="form-text"><?= __('admin.leave_blank_keep_current') ?></div>
                                            <?php endif; ?>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <i class="bi bi-lock-fill me-1"></i><?= __('admin.confirm_password') ?>
                                                <?= empty($user->id) ? '<span class="text-danger">*</span>' : '' ?>
                                            </label>
                                            <input type="password" name="cpassword" class="form-control" 
                                                   placeholder="<?= __('admin.confirm_password') ?>"
                                                   <?= empty($user->id) ? 'required' : '' ?>>
                                        </div>
                                    </div>
					</div>

                                <!-- Location Information -->
                                <div class="mb-4">
                                    <h6 class="fw-bold text-primary mb-3">
                                        <i class="bi bi-geo-alt me-2"></i><?= __('admin.location_information') ?>
                                    </h6>
                                    
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <i class="bi bi-flag me-1"></i><?= __('admin.country') ?>
                                            </label>
                                            <select name="Country" class="form-select">
                                                <option value=""><?= __('admin.select_country') ?></option>
							<?php foreach($country as $countries): ?>
                                                    <option value="<?= $countries->id ?>" 
                                                        <?= (!empty($user->Country) && $user->Country == $countries->id) ? 'selected' : '' ?>>
                                                        <?= htmlspecialchars($countries->name) ?>
                                                    </option>
							<?php endforeach; ?> 
						</select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <i class="bi bi-building me-1"></i><?= __('admin.city') ?>
                                            </label>
                                            <input type="text" name="City" class="form-control" 
                                                   placeholder="<?= __('admin.enter_your_city') ?>"
                                                   value="<?= htmlspecialchars($user->City ?? '') ?>">
                                        </div>
					</div>
					
                                    <div class="mt-3">
                                        <label class="form-label fw-bold">
                                            <i class="bi bi-mailbox me-1"></i><?= __('admin.postal_code') ?>
                                        </label>
                                        <input type="text" name="Zip" class="form-control" 
                                               placeholder="<?= __('admin.enter_your_pincode') ?>"
                                               value="<?= htmlspecialchars($user->Zip ?? '') ?>">
                                    </div>
					</div>

                                <!-- Profile Image -->
                                <div class="mb-4">
                                    <h6 class="fw-bold text-primary mb-3">
                                        <i class="bi bi-image me-2"></i><?= __('admin.profile_image') ?>
                                    </h6>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <?= __('admin.choose_image') ?>
                                            </label>
                                            <input type="file" name="avatar" class="form-control" 
                                                   id="uploadBtn" accept="image/*">
                                            <div class="form-text">
                                                <?= __('admin.image_upload_help') ?>
							</div>		
						</div>
                                        <div class="col-md-6">
                                            <label class="form-label fw-bold">
                                                <?= __('admin.current_image') ?>
                                            </label>
                                            <div class="text-center">
                                                <?php $avatar = $user->avatar != '' ? 'users/' . $user->avatar : 'no-user_image.jpg'; ?>
                                                <img src="<?= base_url('assets/images/' . $avatar) ?>" 
                                                     id="blah" 
                                                     class="img-thumbnail border-3 border-primary" 
                                                     width="150" height="150"
                                                     style="object-fit: cover;">
                                            </div>
							</div>
						</div>
					</div>

                                <!-- Submit Section -->
                                <div class="d-flex justify-content-between align-items-center pt-3 border-top">
                                    <div class="loading-submit d-none">
                                        <div class="d-flex align-items-center text-primary">
                                            <div class="spinner-border spinner-border-sm me-2" role="status">
                                                <span class="visually-hidden"><?= __('admin.loading') ?></span>
                                            </div>
                                            <span class="loading-text"><?= __('admin.saving') ?></span>
						</div>
					</div>

                                    <div class="ms-auto">
                                        <a href="<?= base_url('admincontrol/admin_user/') ?>" class="btn btn-outline-secondary me-2">
                                            <i class="bi bi-x-circle me-2"></i><?= __('admin.cancel') ?>
                                        </a>
                                        <button type="button" class="btn btn-primary btn-lg btn-submit">
                                            <i class="bi bi-check-circle me-2"></i>
                                            <?= !empty($user->id) ? __('admin.update_admin') : __('admin.create_admin') ?>
                                        </button>
                                    </div>
					</div>
				</form>
			</div>
                    </div>
                </div>
            </div>

		</div> 
	</div> 
</div>


<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
    const uploadBtn = document.getElementById('uploadBtn');
    const previewImg = document.getElementById('blah');
    const submitBtn = document.querySelector('.btn-submit');
    const loadingSubmit = document.querySelector('.loading-submit');
    const form = document.getElementById('admin-form');

    // Image preview functionality
    uploadBtn.addEventListener('change', function(e) {
        if (this.files && this.files[0]) {
            const file = this.files[0];
            
            // Validate file size (5MB limit)
            if (file.size > 5 * 1024 * 1024) {
                showToast('<?= __('admin.error') ?>', '<?= __('admin.file_too_large') ?>', 'error', 4000);
                this.value = '';
                return;
            }

            // Validate file type
            if (!file.type.startsWith('image/')) {
                showToast('<?= __('admin.error') ?>', '<?= __('admin.invalid_file_type') ?>', 'error', 4000);
                this.value = '';
                return;
            }

            const reader = new FileReader();
        reader.onload = function(e) {
                previewImg.src = e.target.result;
                previewImg.style.transform = 'scale(1.05)';
                setTimeout(() => {
                    previewImg.style.transform = 'scale(1)';
                }, 200);
            };
            reader.readAsDataURL(file);
        }
    });

    // Form submission
    submitBtn.addEventListener('click', function(e) {
        e.preventDefault();
        
        // Clear previous errors
        clearErrors();
        
        // Validate form
        if (!validateForm()) {
            return;
        }

        const formData = new FormData(form);
        const originalText = submitBtn.innerHTML;
        
        setLoadingState(true);

        // Use fetch API for better error handling
        fetch('<?= base_url('admincontrol/admin_user_form') ?>', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(result => {
            setLoadingState(false);
            
            if (result.location) {
                showToast('<?= __('admin.success') ?>', '<?= __('admin.admin_saved_successfully') ?>', 'success', 2000);
                setTimeout(() => {
                    window.location = result.location;
                }, 1000);
            } else if (result.errors) {
                displayErrors(result.errors);
            } else if (result.error) {
                showToast('<?= __('admin.error') ?>', result.error, 'error', 4000);
            }
        })
        .catch(error => {
            setLoadingState(false);
            showToast('<?= __('admin.error') ?>', '<?= __('admin.something_wrong_try_again') ?>', 'error', 4000);
        });
    });

    function validateForm() {
        let isValid = true;
        
        // Required fields validation
        const requiredFields = ['firstname', 'lastname', 'email', 'username'];
        const userId = form.querySelector('[name="user_id"]').value;
        
        // Add password fields as required for new users
        if (!userId || userId === '0') {
            requiredFields.push('password', 'cpassword');
        }
        
        requiredFields.forEach(fieldName => {
            const field = form.querySelector(`[name="${fieldName}"]`);
            if (field && !field.value.trim()) {
                showFieldError(field, '<?= __('admin.field_required') ?>'.replace('%s', fieldName));
                isValid = false;
            }
        });

        // Email validation
        const emailField = form.querySelector('[name="email"]');
        if (emailField && emailField.value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(emailField.value)) {
                showFieldError(emailField, '<?= __('admin.invalid_email') ?>');
                isValid = false;
            }
        }

        // Password confirmation validation
        const passwordField = form.querySelector('[name="password"]');
        const confirmField = form.querySelector('[name="cpassword"]');
        
        if (passwordField && confirmField && passwordField.value) {
            if (passwordField.value !== confirmField.value) {
                showFieldError(confirmField, '<?= __('admin.passwords_not_match') ?>');
                isValid = false;
            }
            
            if (passwordField.value.length < 6) {
                showFieldError(passwordField, '<?= __('admin.password_min_length') ?>');
                isValid = false;
            }
        }

        return isValid;
    }

    function setLoadingState(loading) {
        if (loading) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i><?= __('admin.saving') ?>...';
            loadingSubmit.classList.remove('d-none');
            loadingSubmit.querySelector('.loading-text').textContent = '<?= __('admin.saving') ?>';
        } else {
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<?= !empty($user->id) ? __('admin.update_admin') : __('admin.create_admin') ?>';
            loadingSubmit.classList.add('d-none');
        }
    }

    function clearErrors() {
        form.querySelectorAll('.is-invalid').forEach(el => {
            el.classList.remove('is-invalid');
        });
        form.querySelectorAll('.invalid-feedback').forEach(el => {
            el.remove();
        });
    }

    function showFieldError(field, message) {
        field.classList.add('is-invalid');
        
        const feedback = document.createElement('div');
        feedback.className = 'invalid-feedback';
        feedback.textContent = message;
        
        field.parentNode.appendChild(feedback);
    }

    function displayErrors(errors) {
        Object.entries(errors).forEach(([fieldName, message]) => {
            const field = form.querySelector(`[name="${fieldName}"]`);
            if (field) {
                // Clean HTML from message
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = message;
                const plainText = tempDiv.textContent || tempDiv.innerText;
                showFieldError(field, plainText);
            }
        });

        // Focus first error field
        const firstError = form.querySelector('.is-invalid');
        if (firstError) {
            firstError.focus();
            firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
        }
    }
});
</script>
