<?php
$page_title = "Email Verification";
require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';

require_once '../vendor/phpmailer/phpmailer/src/PHPMailer.php';
require_once '../vendor/phpmailer/phpmailer/src/SMTP.php';
require_once '../vendor/phpmailer/phpmailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;



$db = Database::getInstance()->connect();
if (!$auth->isLoggedIn()) {
    header("Location: ../login.php");
    exit();
}
$user_id = $auth->getCurrentUserId();

// Get user data
$user_stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$user = $user_stmt->fetch();

if (!$user) {
    $_SESSION['error'] = "User not found";
    header('Location: dashboard.php');
    exit();
}

// Handle email verification resend
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['resend_verification'])) {
    // Generate new verification token
    $verification_token = bin2hex(random_bytes(32));
    $token_expiry = date('Y-m-d H:i:s', strtotime('+24 hours'));

    $update_stmt = $db->prepare("
        UPDATE users SET
            email_verification_token = ?,
            email_verification_expiry = ?,
            updated_at = NOW()
        WHERE id = ?
    ");
    $result = $update_stmt->execute([$verification_token, $token_expiry, $user_id]);

    if ($result) {
        // Send verification email
        $verification_link = SITE_URL . "/user/verify-email.php?token=" . $verification_token;
        $subject = "Verify Your Email - " . SITE_NAME;
        $message = "
        <html>
        <head>
            <title>Verify Your Email</title>
        </head>
        <body>
            <h2>Welcome to " . SITE_NAME . "</h2>
            <p>Thank you for registering! Please verify your email address to complete your account setup.</p>
            <p>Click the link below to verify your email:</p>
            <p><a href='" . $verification_link . "' style='background-color: #667eea; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Verify Email</a></p>
            <p>If the button doesn't work, copy and paste this link into your browser:</p>
            <p>" . $verification_link . "</p>
            <p>This link will expire in 24 hours.</p>
            <p>If you didn't create an account, please ignore this email.</p>
            <br>
            <p>Best regards,<br>" . SITE_NAME . " Team</p>
        </body>
        </html>
        ";

        // Send verification email using PHPMailer
        $mail = new PHPMailer(true);
        try {
            $mail->isSMTP();
            $mail->Host = SMTP_HOST;
            $mail->SMTPAuth = true;
            $mail->Username = SMTP_USERNAME;
            $mail->Password = SMTP_PASSWORD;
            $mail->SMTPSecure = SMTP_ENCRYPTION;
            $mail->Port = SMTP_PORT;

            $mail->setFrom(SITE_EMAIL, SITE_NAME);
            $mail->addAddress($user['email']);

            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $message;

            $mail->send();
            $_SESSION['success'] = "Verification email sent successfully. Please check your inbox.";
        } catch (Exception $e) {
            $_SESSION['error'] = "Failed to send verification email: " . $mail->ErrorInfo;
        }
    } else {
        $_SESSION['error'] = "Failed to generate verification token";
    }

    header('Location: verify-email.php');
    exit();
}

// Handle email verification via token
if (isset($_GET['token'])) {
    $token = $_GET['token'];

    // Check if token is valid and not expired
    $verify_stmt = $db->prepare("
        SELECT id FROM users
        WHERE email_verification_token = ?
        AND email_verification_expiry > NOW()
        AND id = ?
    ");
    $verify_stmt->execute([$token, $user_id]);
    $verified_user = $verify_stmt->fetch();

    if ($verified_user) {
        // Update user as verified
        $update_stmt = $db->prepare("
            UPDATE users SET
                email_verified = 1,
                email_verification_token = NULL,
                email_verification_expiry = NULL,
                email_verified_at = NOW(),
                updated_at = NOW()
            WHERE id = ?
        ");
        $result = $update_stmt->execute([$user_id]);

        if ($result) {
            // Log the verification
            $log_stmt = $db->prepare("
                INSERT INTO activity_logs (user_id, action, description, ip_address, details, created_at)
                VALUES (?, 'email_verified', 'Email address verified successfully', ?, ?, NOW())
            ");
            $log_stmt->execute([$user_id, $_SERVER['REMOTE_ADDR'] ?? '', json_encode(['details' => 'Email address verified successfully'])]);

            $_SESSION['success'] = "Email verified successfully! You can now access all platform features.";
            header('Location: dashboard.php');
            exit();
        } else {
            $_SESSION['error'] = "Failed to verify email. Please try again.";
        }
    } else {
        $_SESSION['error'] = "Invalid or expired verification token.";
    }

    header('Location: verify-email.php');
    exit();
}

// Check if email is already verified
if ($user['email_verified']) {
    $_SESSION['success'] = "Your email is already verified.";
    header('Location: dashboard.php');
    exit();
}
?>

<?php require_once '../includes/header_user.php'; ?>

<div class="max-w-2xl mx-auto">
    <div class="bg-white rounded-lg shadow-md p-8">
        <div class="text-center mb-8">
            <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <span class="text-3xl font-bold text-blue-600"><?php echo strtoupper(substr(SITE_NAME, 0, 1)); ?></span>
            </div>
            <h1 class="text-2xl font-bold text-gray-800">Verify Your Email</h1>
            <p class="text-gray-600 mt-2">Please verify your email address to complete your account setup</p>
        </div>

        <!-- Email Status -->
        <div class="mb-6">
            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                <div class="flex items-start">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-400 text-xl"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-yellow-800">Email Verification Required</h3>
                        <div class="mt-2 text-sm text-yellow-700">
                            <p>We've sent a verification email to:</p>
                            <p class="font-medium"><?php echo htmlspecialchars($user['email']); ?></p>
                            <p class="mt-2">Please check your inbox and click the verification link to complete your registration.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Verification Steps -->
        <div class="mb-8">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">What to do next:</h2>
            <div class="space-y-3">
                <div class="flex items-start">
                    <div class="flex-shrink-0 w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center mt-0.5">
                        <span class="text-sm font-medium text-purple-600">1</span>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-gray-700">Check your email inbox (and spam folder) for a message from <?php echo SITE_NAME; ?></p>
                    </div>
                </div>

                <div class="flex items-start">
                    <div class="flex-shrink-0 w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center mt-0.5">
                        <span class="text-sm font-medium text-purple-600">2</span>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-gray-700">Click the "Verify Email" button in the email</p>
                    </div>
                </div>

                <div class="flex items-start">
                    <div class="flex-shrink-0 w-8 h-8 bg-purple-100 rounded-full flex items-center justify-center mt-0.5">
                        <span class="text-sm font-medium text-purple-600">3</span>
                    </div>
                    <div class="ml-3">
                        <p class="text-sm text-gray-700">You'll be redirected back here and your account will be fully activated</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Resend Verification -->
        <div class="border-t pt-6">
            <div class="text-center">
                <p class="text-gray-600 mb-4">Didn't receive the email? Check your spam folder or request a new one.</p>

                <form method="POST" class="inline-block">
                    <button type="submit" name="resend_verification" class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-md font-medium transition-colors">
                        <i class="fas fa-envelope mr-2"></i>Resend Verification Email
                    </button>
                </form>

                <div class="mt-4">
                    <a href="profile.php" class="text-purple-600 hover:text-purple-700 text-sm">
                        <i class="fas fa-arrow-left mr-1"></i>Back to Profile
                    </a>
                </div>
            </div>
        </div>

        <!-- Help Section -->
        <div class="mt-8 bg-gray-50 rounded-lg p-4">
            <h3 class="text-sm font-medium text-gray-800 mb-2">Need Help?</h3>
            <p class="text-sm text-gray-600 mb-3">
                If you're having trouble verifying your email, please contact our support team.
            </p>
            <a href="support.php" class="inline-flex items-center text-sm text-purple-600 hover:text-purple-700">
                <i class="fas fa-headset mr-1"></i>Contact Support
            </a>
        </div>
    </div>

    <!-- Email Preview (for development/debugging) -->
    <?php if (defined('ENVIRONMENT') && ENVIRONMENT === 'development'): ?>
    <div class="mt-8 bg-gray-100 rounded-lg p-6">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Development: Email Preview</h3>
        <div class="bg-white border rounded-lg p-4 text-sm">
            <p><strong>Subject:</strong> Verify Your Email - <?php echo SITE_NAME; ?></p>
            <p><strong>To:</strong> <?php echo htmlspecialchars($user['email']); ?></p>
            <p><strong>From:</strong> <?php echo SITE_NAME; ?> &lt;<?php echo SITE_EMAIL; ?>&gt;</p>
            <div class="mt-4">
                <p><strong>Message Preview:</strong></p>
                <div class="bg-gray-50 p-3 rounded text-xs font-mono">
                    Welcome to <?php echo SITE_NAME; ?>...<br>
                    Please verify your email address...<br>
                    Verification Link: <?php echo SITE_URL; ?>/verify-email.php?token=[TOKEN]
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
// Auto-refresh for token checking (if user clicks link in same tab)
function checkVerificationStatus() {
    fetch(window.location.href, {
        method: 'HEAD',
        headers: {
            'Cache-Control': 'no-cache'
        }
    }).then(response => {
        // If redirected (status 302), page has changed
        if (response.redirected) {
            window.location.reload();
        }
    }).catch(() => {
        // Ignore errors
    });
}

// Check every 2 seconds for 30 seconds
let checkCount = 0;
const maxChecks = 15;

const checkInterval = setInterval(() => {
    checkCount++;
    if (checkCount >= maxChecks) {
        clearInterval(checkInterval);
    } else {
        checkVerificationStatus();
    }
}, 2000);

// Show success message if redirected back
if (window.location.search.includes('verified=1')) {
    showNotification('Email verified successfully!', 'success');
    // Clean URL
    window.history.replaceState({}, document.title, window.location.pathname);
}
</script>

<?php require_once '../includes/footer.php'; ?>
