<?php
session_start();
require '../config/conn.php';
require '../config/session.php';
require '../vendor/autoload.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['resend_verification'])) {
    $email = trim($_POST['email']);

    // Check if user exists and is not verified
    $stmt = $conn->prepare("SELECT id, full_name, is_verified FROM admins WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        $_SESSION['verification_error'] = "Email not found in our system.";
        header("Location: admin-login.php");
        exit();
    }

    $user = $result->fetch_assoc();

    if ($user['is_verified']) {
        $_SESSION['verification_error'] = "This account is already verified. Please login.";
        header("Location: admin-login.php");
        exit();
    }

    // Generate new verification code
    $new_verification_code = bin2hex(random_bytes(32));
    $expiry_time = date('Y-m-d H:i:s', strtotime('+30 seconds'));

    // Update database
    $update = $conn->prepare("UPDATE admins SET verification_code = ?, verification_code_expiry = ? WHERE email = ?");
    $update->bind_param("sss", $new_verification_code, $expiry_time, $email);

    if ($update->execute()) {
        // Send verification email
        $mail = new PHPMailer(true);
        try {
            // Server settings
            $mail->isSMTP();
            $mail->Host       = 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'holuwaseunisrael@gmail.com';
            $mail->Password   = 'ceae tepn tfyx oxjn';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465;
            
            // Recipients
            $mail->setFrom('noreply@Athenian.com', 'Athenian University');
            $mail->addAddress($email, $user['full_name']);
            
            // Content
            $mail->isHTML(true);
            $mail->Subject = 'New Verification Code - Athenian University';
            
            $verification_link = "https://localhost/school-project/admin/verify.php?code=$new_verification_code&email=" . urlencode($email);
            
            $mail->Body = "
                <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
                    <h2 style='color:  #fbbb01;'>New Verification Code</h2>
                    <p>Hello {$user['full_name']},</p>
                    <p>We've generated a new verification link for your Athenian University account.</p>
                    <p>Please click the button below to verify your email address:</p>
                    <p style='text-align: center; margin: 30px 0;'>
                        <a href='$verification_link' style='background-color:  #fbbb01; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-weight: bold;'>
                            Verify Email Address
                        </a>
                    </p>
                    <p>If the button doesn't work, copy and paste this link into your browser:</p>
                    <p style='word-break: break-all;'>$verification_link</p>
                    <p>This link will expire in 30 seconds.</p>
                    <p>If you didn't request this, please ignore this email.</p>
                    <p>Best regards,<br>Athenian University Team</p>
                </div>
            ";
            
            $mail->AltBody = "Hello {$user['full_name']},\n\nWe've generated a new verification link for your Athenian University account.\n\nPlease visit this link to verify your email:\n$verification_link\n\nThis link will expire in 30 seconds.\n\nIf you didn't request this, please ignore this email.\n\nBest regards,\nAthenian University Team";
            
            $mail->send();
            
            $_SESSION['verification_success'] = "A new verification link has been sent to your email address. Please check your inbox (and spam folder).";
        } catch (Exception $e) {
            $_SESSION['verification_error'] = "Failed to send verification email. Please try again later.";
        }
    } else {
        $_SESSION['verification_error'] = "Failed to generate new verification code. Please try again.";
    }

    header("Location: admin-login.php");
    exit();
}

// If accessed directly
header("Location: admin-login.php");
exit();
?>