<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
session_start();
require 'config/conn.php';
require 'vendor/autoload.php';

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

// Handle old token-based URLs
if (isset($_GET['token'])) {
    $verification_code = mysqli_real_escape_string($conn, $_GET['token']);
    $query = "SELECT email FROM students WHERE verification_code = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("s", $verification_code);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        header("Location: verify.php?code=" . urlencode($verification_code) . "&email=" . urlencode($user['email']));
        exit();
    } else {
        $_SESSION['verification_error'] = "Invalid verification token.";
        header("Location: login.php");
        exit();
    }
}

function sendNewVerificationCode($conn, $email) {
    $new_verification_code = bin2hex(random_bytes(32));
    $expiry_time = date('Y-m-d H:i:s', strtotime('+30 minutes'));
    
    $update = "UPDATE students SET verification_code = ?, verification_code_expiry = ?, is_verified = 0 WHERE email = ?";
    $stmt = $conn->prepare($update);
    $stmt->bind_param("sss", $new_verification_code, $expiry_time, $email);
    
    if ($stmt->execute()) {
        $query = "SELECT full_name FROM students WHERE email = ?";
        $stmt2 = $conn->prepare($query);
        $stmt2->bind_param("s", $email);
        $stmt2->execute();
        $result = $stmt2->get_result();
        $user = $result->fetch_assoc();
        $full_name = $user['full_name'];
        
        $mail = new PHPMailer(true);
        try {
            $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;
            
            $mail->setFrom('noreply@.com', 'Athenian');
            $mail->addAddress($email, $full_name);
            
            $mail->isHTML(true);
            $mail->Subject = 'New Verification Code - Athenian';
            
           $verification_link = "https://localhost/school-project/verify.php?code=$verification_code&email=" . urlencode($email);
            
            $mail->Body = "
                <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #e0e0e0; border-radius: 8px; overflow: hidden;'>
                    <div style='background-color: #4CAF50; padding: 25px; text-align: center;'>
                        <h1 style='color: white; margin: 0; font-size: 24px;'>Athenian</h1>
                        <p style='color: rgba(255,255,255,0.8); margin: 5px 0 0; font-size: 16px;'>
                            Audio News & Updates
                        </p>
                    </div>
                    
                    <div style='padding: 25px;'>
                        <h2 style='color: #4CAF50; margin-top: 0;'>New Verification Code</h2>
                        <p>Hello $full_name,</p>
                        <p>We've generated a new verification link for your Athenian account.</p>
                        
                        <div style='background-color: #E8F5E9; border-left: 4px solid #4CAF50; padding: 15px; margin: 20px 0; border-radius: 8px;'>
                            <p>Please click the button below to verify your email address:</p>
                            <div style='text-align: center; margin: 20px 0;'>
                                <a href='$verification_link' style='background-color: #4CAF50; color: white; padding: 12px 24px; text-decoration: none; border-radius: 8px; font-weight: bold; display: inline-block;'>
                                    Verify Email Address
                                </a>
                            </div>
                            <p>If the button doesn't work, copy and paste this link into your browser:</p>
                            <div style='background-color: #f5f5f5; padding: 10px; border-radius: 4px; word-break: break-all; font-family: monospace;'>
                                $verification_link
                            </div>
                            <p style='font-size: 13px; color: #757575; margin-top: 5px;'>⏳ Link expires in 30 minutes</p>
                        </div>
                        
                        <div style='background-color: #fff3e0; border-left: 4px solid #FFC107; padding: 15px; margin: 20px 0; border-radius: 8px;'>
                            <h4 style='margin-top: 0; color: #4CAF50;'>Security Notice</h4>
                            <p>For your protection, we'll never ask for your password or verification codes via email.</p>
                            <p>If you didn't request this, please ignore this email.</p>
                        </div>
                        
                        <p style='font-size: 14px; color: #757575;'>Best regards,<br>The Athenian Team</p>
                    </div>
                    
                    <div style='background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #757575;'>
                        <p>© " . date('Y') . " Athenian. All rights reserved.</p>
                    </div>
                </div>
            ";
            
            $mail->AltBody = "Hello $full_name,\n\nWe've generated a new verification link for your Athenian account.\n\nPlease visit this link to verify your email:\n$verification_link\n\nThis link will expire in 30 minutes.\n\nIf you didn't request this, please ignore this email.\n\nBest regards,\nThe Athenian Team";
            
            $mail->send();
            return true;
        } catch (Exception $e) {
            error_log("Mailer Error: " . $mail->ErrorInfo);
            return false;
        }
    }
    return false;
}

if (isset($_GET['code']) && isset($_GET['email'])) {
    $verification_code = mysqli_real_escape_string($conn, $_GET['code']);
    $email = mysqli_real_escape_string($conn, $_GET['email']);
    
    $query = "SELECT id, verification_code_expiry FROM students 
              WHERE email = ? AND verification_code = ? AND is_verified = 0";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("ss", $email, $verification_code);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        $expiry_time = $user['verification_code_expiry'];
        
        if (strtotime($expiry_time) < time()) {
            if (sendNewVerificationCode($conn, $email)) {
                $_SESSION['verification_error'] = "The verification link has expired. We've sent a new one to your email address.";
            } else {
                $_SESSION['verification_error'] = "The verification link has expired and we couldn't send a new one. Please contact support.";
            }
        } else {
            $update = "UPDATE students SET is_verified = 1, verification_code = NULL, verification_code_expiry = NULL WHERE email = ?";
            $stmt = $conn->prepare($update);
            $stmt->bind_param("s", $email);
            
            if ($stmt->execute()) {
                $_SESSION['verification_success'] = "Email verification successful! You can now login to your account.";
            } else {
                $_SESSION['verification_error'] = "Verification failed: " . $conn->error;
            }
        }
    } else {
        $check_verified = $conn->prepare("SELECT id FROM students WHERE email = ? AND is_verified = 1");
        $check_verified->bind_param("s", $email);
        $check_verified->execute();
        
        if ($check_verified->get_result()->num_rows > 0) {
            $_SESSION['verification_error'] = "This email address has already been verified. Please login.";
        } else {
            $_SESSION['verification_error'] = "Invalid verification link. Would you like us to send a new one?";
            $_SESSION['pending_verification_email'] = $email;
        }
    }
} else {
    $_SESSION['verification_error'] = "Invalid verification link.";
}

header("Location: login.php");
exit();
?>