<?php
/**
 * OTP Email Verification Page
 * User enters the OTP received via email
 * Supports both registration and profile verification
 */

session_start();
require_once 'config/config.php';
require_once 'classes/Database.php';
require_once 'classes/Auth.php';

$db = Database::getInstance();
$auth = new Auth($db);

// Determine if user is logged in (profile verification) or registering
$isProfileVerification = $auth->isLoggedIn();
$currentUser = null;

if ($isProfileVerification) {
    // Profile verification - user already logged in
    $currentUser = $auth->getCurrentUser();
    $email = $currentUser['email'] ?? '';
    $userName = $currentUser['name'] ?? '';
} else {
    // Registration verification
    $email = $_SESSION['registration_email'] ?? '';
    $userName = $_GET['name'] ?? $_SESSION['user_name'] ?? '';
    
    if (empty($email)) {
        header('Location: register.php');
        exit();
    }
}

$message = '';
$message_type = '';
$otp_verified = false;

// Process OTP submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_otp'])) {
    $otp = trim($_POST['otp'] ?? '');
    
    if (empty($otp)) {
        $message = '❌ Please enter the OTP code';
        $message_type = 'danger';
    } else if (strlen($otp) !== 6 || !ctype_digit($otp)) {
        $message = '❌ OTP must be 6 digits';
        $message_type = 'danger';
    } else {
        // Verify OTP from database
        $otpRecord = $db->fetch(
            'SELECT id, otp, attempts, expires_at FROM email_otps WHERE email = ? ORDER BY created_at DESC LIMIT 1',
            [$email]
        );
        
        if (!$otpRecord) {
            $message = '❌ No OTP found for this email. Please try again.';
            $message_type = 'danger';
        } else if (strtotime($otpRecord['expires_at']) < time()) {
            $message = '❌ OTP has expired. Please request a new one.';
            $message_type = 'danger';
        } else if ($otpRecord['attempts'] >= 5) {
            $message = '❌ Maximum verification attempts exceeded. Please request a new OTP.';
            $message_type = 'danger';
        } else if ($otpRecord['otp'] === $otp) {
            // OTP is correct - Mark email as verified
            $db->query(
                'UPDATE users SET email_verified = 1, email_verified_at = NOW(), is_active = 1 WHERE email = ?',
                [$email]
            );
            
            // Delete used OTP
            $db->query(
                'DELETE FROM email_otps WHERE email = ?',
                [$email]
            );
            
            $message = '✅ Email verified successfully!';
            $message_type = 'success';
            $otp_verified = true;
            
            // Clear session for registration
            if (!$isProfileVerification) {
                unset($_SESSION['registration_email']);
            }
        } else {
            // Wrong OTP - increment attempts
            $db->update(
                'email_otps',
                ['attempts' => $otpRecord['attempts'] + 1],
                'id = ?',
                [$otpRecord['id']]
            );
            
            $remaining = 5 - ($otpRecord['attempts'] + 1);
            if ($remaining > 0) {
                $message = "❌ Invalid OTP. You have $remaining attempts remaining.";
            } else {
                $message = '❌ Maximum attempts exceeded. Please request a new OTP.';
            }
            $message_type = 'danger';
        }
    }
}

// For development: Show OTP option
$showDevMode = getenv('APP_DEBUG') === 'true' || getenv('APP_DEBUG') === '1';
$testOTP = '';
if ($showDevMode) {
    $otpRecord = $db->fetch(
        'SELECT otp FROM email_otps WHERE email = ? ORDER BY created_at DESC LIMIT 1',
        [$email]
    );
    $testOTP = $otpRecord['otp'] ?? '';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify Email - <?php echo APP_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .verification-container {
            background: white;
            border-radius: 20px;
            padding: 50px;
            max-width: 450px;
            width: 100%;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .header-icon {
            width: 80px;
            height: 80px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
        }
        
        .header-icon svg {
            width: 40px;
            height: 40px;
            color: white;
            stroke-width: 1.5;
        }
        
        .header h2 {
            color: #333;
            margin: 0 0 10px 0;
            font-weight: 700;
        }
        
        .header p {
            color: #666;
            margin: 0;
            font-size: 14px;
        }
        
        .email-display {
            background: #f8f9ff;
            border: 1px solid #e0e7ff;
            border-radius: 10px;
            padding: 12px 15px;
            margin: 20px 0;
            text-align: center;
        }
        
        .email-display strong {
            color: #667eea;
            font-weight: 600;
        }
        
        .form-group {
            margin: 25px 0;
        }
        
        .form-group label {
            color: #333;
            font-weight: 600;
            margin-bottom: 10px;
            display: block;
            font-size: 14px;
        }
        
        .otp-input {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e7ff;
            border-radius: 10px;
            font-size: 16px;
            text-align: center;
            letter-spacing: 10px;
            font-weight: bold;
            font-family: 'Courier New', monospace;
            transition: all 0.3s ease;
        }
        
        .otp-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .btn-verify {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 10px;
            font-weight: 600;
            font-size: 16px;
            margin-top: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-verify:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }
        
        .btn-verify:active {
            transform: translateY(0);
        }
        
        .dev-mode {
            background: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 10px;
            padding: 15px;
            margin: 20px 0;
            text-align: center;
        }
        
        .dev-mode label {
            display: block;
            font-size: 12px;
            color: #856404;
            margin-bottom: 8px;
        }
        
        .dev-otp-code {
            background: #fff;
            border: 2px dashed #ffc107;
            padding: 10px;
            border-radius: 8px;
            font-size: 24px;
            font-weight: bold;
            color: #ffc107;
            letter-spacing: 5px;
            font-family: 'Courier New', monospace;
        }
        
        .back-link {
            text-align: center;
            margin-top: 20px;
        }
        
        .back-link a {
            color: #667eea;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
        }
        
        .back-link a:hover {
            text-decoration: underline;
        }
        
        .alert {
            border-radius: 10px;
            padding: 12px 15px;
            font-size: 14px;
            margin-bottom: 20px;
        }
        
        .success-message {
            text-align: center;
            padding: 30px 0;
        }
        
        .success-icon {
            font-size: 60px;
            color: #28a745;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <div class="verification-container">
        <?php if ($otp_verified): ?>
            <!-- Success Message -->
            <div class="success-message">
                <div class="success-icon">✅</div>
                <h3 style="color: #28a745; margin-bottom: 15px;">Email Verified!</h3>
                <p style="color: #666; margin-bottom: 25px;">
                    <?php 
                    if ($isProfileVerification) {
                        echo 'Your email has been successfully verified!';
                    } else {
                        echo 'Your email has been successfully verified. You can now log in to your account.';
                    }
                    ?>
                </p>
                <a href="<?php echo $isProfileVerification ? 'user/dashboard.php' : 'login.php'; ?>" class="btn btn-success" style="width: 100%; padding: 12px; border-radius: 10px; text-decoration: none; font-weight: 600;">
                    <?php echo $isProfileVerification ? 'Back to Dashboard →' : 'Go to Login →'; ?>
                </a>
            </div>
        <?php else: ?>
            <!-- Verification Form -->
            <div class="header">
                <div class="header-icon">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.3-4.3l2.6 2.6" />
                    </svg>
                </div>
                <h2>Verify Your Email</h2>
                <p>Enter the OTP code sent to your email</p>
            </div>
            
            <?php if (!empty($userName)): ?>
                <div class="email-display">
                    Hello, <strong><?php echo htmlspecialchars($userName); ?></strong>
                </div>
            <?php endif; ?>
            
            <div class="email-display">
                Email: <strong><?php echo htmlspecialchars($email); ?></strong>
            </div>
            
            <?php if (!empty($message)): ?>
                <div class="alert alert-<?php echo htmlspecialchars($message_type); ?>" role="alert">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label for="otp">OTP Code (6 digits)</label>
                    <input 
                        type="text" 
                        id="otp" 
                        name="otp" 
                        class="otp-input" 
                        placeholder="000000" 
                        maxlength="6" 
                        inputmode="numeric" 
                        pattern="[0-9]{6}"
                        autofocus
                        required
                    >
                </div>
                
                <button type="submit" name="verify_otp" class="btn-verify">
                    Verify OTP →
                </button>
            </form>
            
            <?php if ($showDevMode && !empty($testOTP)): ?>
                <div class="dev-mode">
                    <label>🧪 Development Mode - Test OTP:</label>
                    <div class="dev-otp-code"><?php echo htmlspecialchars($testOTP); ?></div>
                </div>
            <?php endif; ?>
            
            <div class="back-link">
                <a href="<?php echo $isProfileVerification ? 'user/dashboard.php' : 'register.php'; ?>">← Back <?php echo $isProfileVerification ? 'to Dashboard' : 'to Registration'; ?></a>
            </div>
        <?php endif; ?>
    </div>
</body>
</html>
