<?php
/**
 * ============================================================================
 * auth/verify-otp.php
 * OTP Verification Page
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once '../config/config.php';

// Redirect if already logged in
if (isLoggedIn()) {
    header('Location: ../dashboard/');
    exit();
}

// Get phone from URL
$phone = $_GET['phone'] ?? '';
if (empty($phone)) {
    header('Location: login.php');
    exit();
}

$pageTitle = 'Verify OTP - AIMS';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #059669;
            --primary-dark: #047857;
            --primary-light: #10b981;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .auth-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            max-width: 450px;
            width: 100%;
            overflow: hidden;
            animation: fadeInUp 0.6s ease;
        }
        
        .auth-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-light) 100%);
            padding: 40px 30px;
            text-align: center;
            color: white;
        }
        
        .auth-logo {
            font-size: 4rem;
            margin-bottom: 15px;
        }
        
        .auth-body {
            padding: 35px 30px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            border: none;
            padding: 12px;
            font-weight: 600;
            border-radius: 10px;
        }
        
        @keyframes fadeInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
    </style>
</head>
<body>
    <div class="auth-card">
        <div class="auth-header">
            <div class="auth-logo">📱</div>
            <h1 class="h2 fw-bold">Verify Phone</h1>
            <p class="mb-0">Enter the OTP sent to your phone</p>
        </div>
        
        <div class="auth-body">
            <div class="alert alert-info" role="alert">
                <i class="bi bi-info-circle me-2"></i>
                We've sent a 6-digit code to <strong id="phoneDisplay"><?php echo htmlspecialchars($phone); ?></strong>
            </div>
            
            <form id="otpForm" novalidate>
                <div class="mb-3">
                    <div class="form-floating">
                        <input type="text" class="form-control text-center" id="otpCode" placeholder="000000" maxlength="6" pattern="[0-9]{6}" required style="font-size: 1.5rem; letter-spacing: 0.5rem;">
                        <label for="otpCode"><i class="bi bi-shield-lock me-2"></i>Enter OTP</label>
                        <div class="invalid-feedback">Please enter a valid 6-digit OTP</div>
                    </div>
                </div>
                
                <button type="submit" class="btn btn-primary w-100 mb-3">
                    <i class="bi bi-check-circle me-2"></i>Verify OTP
                </button>
                
                <div class="text-center">
                    <p class="mb-2">Didn't receive the code?</p>
                    <button type="button" class="btn btn-link text-decoration-none" id="resendOTP">
                        <i class="bi bi-arrow-clockwise me-2"></i>Resend OTP
                    </button>
                </div>
            </form>
            
            <hr>
            
            <p class="text-center mb-0">
                <a href="login.php" class="text-decoration-none">← Back to Login</a>
            </p>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
    
    <script>
        const APP_URL = '<?php echo APP_URL; ?>';
        const phone = '<?php echo htmlspecialchars($phone); ?>';
        
        function showToast(message, type = 'info') {
            const colors = {
                success: 'linear-gradient(135deg, #22c55e 0%, #16a34a 100%)',
                error: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)',
                warning: 'linear-gradient(135deg, #f59e0b 0%, #d97706 100%)',
                info: 'linear-gradient(135deg, #3b82f6 0%, #2563eb 100%)'
            };
            
            Toastify({
                text: message,
                duration: 3000,
                gravity: "top",
                position: "right",
                style: { background: colors[type], borderRadius: "10px", padding: "15px 20px" },
                stopOnFocus: true
            }).showToast();
        }
        
        $('#otpCode').on('input', function() {
            this.value = this.value.replace(/\D/g, '');
        });
        
        $('#otpForm').submit(function(e) {
            e.preventDefault();
            
            if (!this.checkValidity()) {
                e.stopPropagation();
                $(this).addClass('was-validated');
                return;
            }
            
            const btn = $(this).find('button[type="submit"]');
            btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Verifying...');
            
            $.ajax({
                url: APP_URL + '/api/auth.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'verify_otp',
                    phone: phone,
                    otp: $('#otpCode').val()
                },
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Success!',
                            text: 'Phone verified successfully!',
                            icon: 'success',
                            confirmButtonColor: '#059669'
                        }).then(() => {
                            window.location.href = APP_URL + '/dashboard/';
                        });
                    } else {
                        showToast(response.message || 'Invalid OTP', 'error');
                        btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i>Verify OTP');
                    }
                },
                error: function(xhr) {
                    console.error(xhr);
                    showToast('Connection error. Please try again.', 'error');
                    btn.prop('disabled', false).html('<i class="bi bi-check-circle me-2"></i>Verify OTP');
                }
            });
        });
        
        $('#resendOTP').click(function() {
            const btn = $(this);
            btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span>Sending...');
            
            $.ajax({
                url: APP_URL + '/api/auth.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'resend_otp',
                    phone: phone
                },
                success: function(response) {
                    if (response.success) {
                        showToast(response.message || 'OTP sent successfully!', 'success');
                        
                        // Show OTP in development mode
                        if (response.otp) {
                            Swal.fire({
                                title: 'Development Mode',
                                text: 'Your OTP is: ' + response.otp,
                                icon: 'info',
                                confirmButtonColor: '#059669'
                            });
                        }
                        
                        $('#otpCode').val('').focus();
                    } else {
                        showToast(response.message || 'Failed to resend OTP', 'error');
                    }
                    btn.prop('disabled', false).html('<i class="bi bi-arrow-clockwise me-2"></i>Resend OTP');
                },
                error: function(xhr) {
                    console.error(xhr);
                    showToast('Connection error. Please try again.', 'error');
                    btn.prop('disabled', false).html('<i class="bi bi-arrow-clockwise me-2"></i>Resend OTP');
                }
            });
        });
    </script>
</body>
</html>