<?= $this->extend('layouts/dashboard') ?>

<?= $this->section('content') ?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Verify Email Address</h1>
    <a href="<?= base_url('/admin/edit/' . $admin_id) ?>" class="btn btn-secondary">
        <i class="fas fa-arrow-left me-2"></i> Back to Edit
    </a>
</div>

<!-- Success/Error Messages -->
<?php if (session()->getFlashdata('success')): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <strong>Success!</strong> <?= session()->getFlashdata('success') ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<?php if (session()->getFlashdata('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <strong>Error!</strong> <?= session()->getFlashdata('error') ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- OTP Verification Form -->
<div class="card border-0 shadow-sm">
    <div class="card-body">
        <div class="mb-4">
            <p class="text-muted">
                We've sent a 6-digit OTP to the email address you provided. Please enter the code below to verify your email and complete the admin account update.
            </p>
        </div>
        
        <form id="otpForm" action="<?= base_url('/admin/process-update-otp/' . $admin_id) ?>" method="POST">
            <?= csrf_field() ?>
            
            <div class="mb-4">
                <label class="form-label fw-medium" for="otp">
                    OTP Code
                </label>
                <input class="form-control <?= isset($validation) && $validation->hasError('otp') ? 'is-invalid' : '' ?>" 
                       id="otp" 
                       type="text" 
                       name="otp" 
                       maxlength="6"
                       placeholder="Enter 6-digit code">
                <?php if (isset($validation) && $validation->hasError('otp')): ?>
                    <div class="invalid-feedback"><?= $validation->getError('otp') ?></div>
                <?php endif; ?>
            </div>
            
            <div class="d-flex flex-column flex-md-row align-items-center justify-content-between gap-3">
                <button id="submitBtn" class="btn btn-primary w-100 w-md-auto" type="submit">
                    <span id="submitText">Verify OTP</span>
                    <span id="submitSpinner" class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                </button>
                <div class="d-flex flex-column flex-md-row align-items-center gap-2 w-100 w-md-auto">
                    <button id="resendBtn" type="button" class="btn btn-link">
                        Resend OTP
                    </button>
                    <span id="countdown" class="d-none text-muted">Resend in <span id="countdownTimer">60</span>s</span>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
    // Resend OTP functionality with countdown
    document.getElementById('resendBtn').addEventListener('click', function() {
        const resendBtn = document.getElementById('resendBtn');
        const countdown = document.getElementById('countdown');
        const countdownTimer = document.getElementById('countdownTimer');
        
        // Disable resend button and show countdown
        resendBtn.classList.add('d-none');
        countdown.classList.remove('d-none');
        
        let seconds = 60;
        countdownTimer.textContent = seconds;
        
        const timer = setInterval(function() {
            seconds--;
            countdownTimer.textContent = seconds;
            
            if (seconds <= 0) {
                clearInterval(timer);
                countdown.classList.add('d-none');
                resendBtn.classList.remove('d-none');
            }
        }, 1000);
        
        // Send AJAX request to resend OTP
        fetch('<?= base_url('/admin/resend-update-otp/' . $admin_id) ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
            },
            body: JSON.stringify({
                <?= csrf_token() ?>: '<?= csrf_hash() ?>'
            })
        })
        .then(response => response.json())
        .then(data => {
            // Remove any existing alerts
            const existingAlerts = document.querySelectorAll('.ajax-alert');
            existingAlerts.forEach(alert => alert.remove());
            
            if (data.status === 'success') {
                // Show success message
                const successAlert = document.createElement('div');
                successAlert.className = 'ajax-alert alert alert-success alert-dismissible fade show';
                successAlert.innerHTML = '<strong>Success!</strong> ' + data.message + '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                document.querySelector('.content').insertBefore(successAlert, document.querySelector('.content').firstChild);
                
                // Remove alert after 5 seconds
                setTimeout(() => {
                    if (successAlert.parentNode) {
                        successAlert.remove();
                    }
                }, 5000);
            } else {
                // Show error message
                const errorAlert = document.createElement('div');
                errorAlert.className = 'ajax-alert alert alert-danger alert-dismissible fade show';
                errorAlert.innerHTML = '<strong>Error!</strong> ' + data.message + '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                document.querySelector('.content').insertBefore(errorAlert, document.querySelector('.content').firstChild);
                
                // Remove alert after 5 seconds
                setTimeout(() => {
                    if (errorAlert.parentNode) {
                        errorAlert.remove();
                    }
                }, 5000);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            // Remove any existing alerts
            const existingAlerts = document.querySelectorAll('.ajax-alert');
            existingAlerts.forEach(alert => alert.remove());
            
            // Show error message
            const errorAlert = document.createElement('div');
            errorAlert.className = 'ajax-alert alert alert-danger alert-dismissible fade show';
            errorAlert.innerHTML = '<strong>Error!</strong> Failed to resend OTP. Please try again.<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
            document.querySelector('.content').insertBefore(errorAlert, document.querySelector('.content').firstChild);
            
            // Remove alert after 5 seconds
            setTimeout(() => {
                if (errorAlert.parentNode) {
                    errorAlert.remove();
                }
            }, 5000);
        });
    });
    
    // Form submission with loading indicator
    document.getElementById('otpForm').addEventListener('submit', function(e) {
        const submitBtn = document.getElementById('submitBtn');
        const submitText = document.getElementById('submitText');
        const submitSpinner = document.getElementById('submitSpinner');
        
        // Show loading indicator
        submitText.classList.add('d-none');
        submitSpinner.classList.remove('d-none');
        submitBtn.disabled = true;
    });
</script>
<?= $this->endSection() ?>