<?php
// send_verification_email.php: Handles sending verification emails

define('TONSUI_LOADED', true);

// Include required files
require_once __DIR__ . '/session_init.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/utils/EmailVerification.php';
// Safe mailer include; if missing, we will gracefully skip sending to avoid fatals
$mailerPath = __DIR__ . '/send_mail.php';
if (file_exists($mailerPath)) {
    require_once $mailerPath;
}

// Set response headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
// Reflect exact origin for credentialed requests (avoid wildcard with credentials)
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (!empty($origin)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    $scheme = $_SERVER['REQUEST_SCHEME'] ?? 'https';
    $host = $_SERVER['HTTP_HOST'] ?? '';
    if (!empty($host)) {
        header('Access-Control-Allow-Origin: ' . $scheme . '://' . $host);
    }
}
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('X-XSS-Protection: 1; mode=block');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Function to send JSON response
function sendResponse($success, $message, $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    $response = ['success' => $success, 'message' => $message];
    if ($data !== null) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit;
}

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sendResponse(false, 'Method not allowed', null, 405);
}

try {
    // Get request data
    $data = json_decode(file_get_contents('php://input'), true);
    
    // Validate input
    if (empty($data['email'])) {
        sendResponse(false, 'Email is required', null, 400);
    }
    
    $email = filter_var($data['email'], FILTER_VALIDATE_EMAIL);
    if (!$email) {
        sendResponse(false, 'Invalid email format', null, 400);
    }
    
    // Get database connection
    if (!isset($pdo)) {
        // db.php includes a Database singleton that sets $pdo
        if (!isset($GLOBALS['pdo'])) {
            throw new Exception('Database connection not available');
        }
        $pdo = $GLOBALS['pdo'];
    }
    
    // Check if user exists and is not already verified
    $stmt = $pdo->prepare("SELECT id, username, email_verified FROM users WHERE email = ? LIMIT 1");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$user) {
        // Don't reveal if email exists for security
        sendResponse(true, 'If an account exists with this email, a verification link has been sent.');
    }
    
    if ($user['email_verified']) {
        sendResponse(true, 'Email is already verified');
    }
    
    // Generate verification token
    $tokenData = EmailVerification::generateToken();
    
    // Start transaction
    $pdo->beginTransaction();
    
    try {
        // Store the token
        if (!EmailVerification::storeToken(
            $pdo, 
            $user['id'], 
            $tokenData['hashed_token'], 
            $tokenData['expires_at']
        )) {
            throw new Exception('Failed to store verification token');
        }
        
        // Update user's verification token
        $stmt = $pdo->prepare(
            "UPDATE users SET email_verification_token = ?, updated_at = NOW() WHERE id = ?"
        );
        if (!$stmt->execute([$tokenData['hashed_token'], $user['id']])) {
            throw new Exception('Failed to update user verification token');
        }
        
        // Send verification email (frontend route)
        $verificationUrl = getBaseUrl() . "/verify-email?token=" . $tokenData['token'];

        $emailSent = true;
        if (function_exists('send_mail')) {
            $subject = 'Verify Your Email Address - Viz Venture Group';
            $html = "<h2>Verify Your Email</h2><p>Hello {$user['username']},</p><p>Please verify your email by clicking the link below:</p><p><a href='{$verificationUrl}'>Verify Email</a></p><p>Or copy and paste this URL:<br>{$verificationUrl}</p>";
            $alt = "Verify your email: {$verificationUrl}";
            $emailSent = send_mail($user['email'], $subject, $html, $alt) === true;
        } else {
            error_log('[send_verification_email] send_mail.php not found; skipping email send');
        }
        // Do not throw on email failure to avoid blocking; respond success with generic message
        
        // Commit transaction
        $pdo->commit();
        
        sendResponse(true, 'Verification email sent successfully');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
    
} catch (Exception $e) {
    error_log('Error in send_verification_email.php: ' . $e->getMessage());
    sendResponse(false, 'Failed to send verification email', null, 500);
}

/**
 * Get base URL for the application
 */
function getBaseUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    return $protocol . $_SERVER['HTTP_HOST'];
}

/**
 * Send verification email
 */
function sendVerificationEmail($to, $username, $verificationUrl) {
    // In a real application, you would use a proper email sending library
    // This is a simplified example
    $subject = 'Verify Your Email Address';
    $message = "
    <html>
    <head>
        <title>Verify Your Email Address</title>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .button {
                display: inline-block; 
                padding: 10px 20px; 
                background-color: #4CAF50; 
                color: white; 
                text-decoration: none; 
                border-radius: 4px;
                margin: 20px 0;
            }
        </style>
    </head>
    <body>
        <div class='container'>
            <h2>Welcome to TON SUI Mining!</h2>
            <p>Hello {$username},</p>
            <p>Thank you for registering. Please verify your email address by clicking the button below:</p>
            <p>
                <a href='{$verificationUrl}' class='button'>Verify Email Address</a>
            </p>
            <p>Or copy and paste this link into your browser:</p>
            <p><code>{$verificationUrl}</code></p>
            <p>This link will expire in 24 hours.</p>
            <p>If you did not create an account, please ignore this email.</p>
            <p>Best regards,<br>TON SUI Mining Team</p>
        </div>
    </body>
    </html>
    ";
    
    $headers = [
        'MIME-Version: 1.0',
        'Content-type: text/html; charset=utf-8',
        'From: no-reply@tonsuimining.com',
        'X-Mailer: PHP/' . phpversion()
    ];
    
    // In a real application, use a proper email sending library like PHPMailer
    return mail($to, $subject, $message, implode("\r\n", $headers));
}
