<?php
require_once 'functions.php';

// Check if OTP session exists
if (!isset($_SESSION['otp_user_id']) || !isset($_SESSION['otp_code'])) {
    header('Location: index.php');
    exit();
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $enteredOTP = ($_POST['otp1'] ?? '') . ($_POST['otp2'] ?? '') . ($_POST['otp3'] ?? '') . ($_POST['otp4'] ?? '');
    
    if (strlen($enteredOTP) !== 4) {
        $error = 'Please enter the complete 4-digit code.';
    } elseif ($enteredOTP === $_SESSION['otp_code']) {
        // OTP verified - log user in
        $userId = $_SESSION['otp_user_id'];
        
        $db = getDB();
        $stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
        $stmt->bind_param('i', $userId);
        $stmt->execute();
        $user = $stmt->get_result()->fetch_assoc();
        
        if ($user) {
            // Update last login
            $stmt = $db->prepare("UPDATE users SET last_login = NOW(), last_login_ip = ? WHERE id = ?");
            $ip = $_SERVER['REMOTE_ADDR'];
            $stmt->bind_param('si', $ip, $userId);
            $stmt->execute();
            
            // Log activity
            logLogin($userId, 'user', 'success');
            
            // Set session
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_type'] = 'user';
            $_SESSION['user_name'] = $user['first_name'] . ' ' . $user['last_name'];
            
            // Clear OTP session
            unset($_SESSION['otp_user_id'], $_SESSION['otp_email'], $_SESSION['otp_code'], $_SESSION['otp_purpose']);
            
            createNotification($userId, 'Login Successful', 'You have successfully logged in to your account.', 'success');
            
            header('Location: dashboard.php');
            exit();
        }
    } else {
        $error = 'Invalid verification code. Please try again.';
    }
}

// Resend OTP
if (isset($_GET['resend'])) {
    $_SESSION['otp_code'] = generateOTP();
    $email = $_SESSION['otp_email'] ?? '';
    $otpBody = "Your Flexi Access login verification code is: <strong>" . $_SESSION['otp_code'] . "</strong><br><br>This code will expire in 10 minutes.";
    @sendMail($email, 'Login Verification Code', $otpBody);
    $success = 'A new verification code has been sent to your email.';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verify OTP - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        .otp-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, var(--dark) 0%, var(--secondary) 50%, var(--dark-800) 100%);
        }
        .otp-card {
            background: var(--white);
            border-radius: var(--border-radius-lg);
            padding: 40px;
            box-shadow: var(--shadow-xl);
            max-width: 440px;
            width: 100%;
            text-align: center;
        }
        .otp-icon {
            width: 64px;
            height: 64px;
            border-radius: 50%;
            background: var(--primary-light);
            color: var(--primary);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 28px;
        }
    </style>
</head>
<body>
    <div class="otp-container">
        <div class="otp-card">
            <div class="otp-icon">🔐</div>
            <h2 style="font-size: 22px; font-weight: 700; margin-bottom: 8px;">Verification Required</h2>
            <p style="color: var(--gray); margin-bottom: 24px; font-size: 14px;">
                We've sent a 4-digit verification code to<br>
                <strong><?php echo e($_SESSION['otp_email'] ?? ''); ?></strong>
            </p>
            
            <?php if ($error): ?>
                <div class="alert alert-danger" style="margin-bottom: 20px; text-align: left;">
                    <span>⚠</span> <?php echo e($error); ?>
                </div>
            <?php endif; ?>
            
            <?php if (isset($success)): ?>
                <div class="alert alert-success" style="margin-bottom: 20px; text-align: left;">
                    <span>✓</span> <?php echo e($success); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="pin-inputs" style="margin-bottom: 24px;">
                    <input type="text" name="otp1" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" required autofocus>
                    <input type="text" name="otp2" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" required>
                    <input type="text" name="otp3" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" required>
                    <input type="text" name="otp4" class="pin-input" maxlength="1" pattern="[0-9]" inputmode="numeric" required>
                </div>
                
                <button type="submit" class="btn btn-primary btn-block" style="padding: 14px; margin-bottom: 16px;">
                    Verify Code
                </button>
            </form>
            
            <p style="font-size: 13px; color: var(--gray);">
                Didn't receive the code? <a href="?resend=1" style="color: var(--primary); font-weight: 600;">Resend Code</a>
            </p>
            
            <a href="index.php" style="display: inline-block; margin-top: 16px; font-size: 13px; color: var(--gray);">
                ← Back to Login
            </a>
        </div>
    </div>
    
    <script src="assets/js/main.js"></script>
</body>
</html>
