<?php
/**
 * TraderAlign — Resend Verification Email Page
 * Allows logged-in users to request a new verification email
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/ScopedDb.php';
require_once __DIR__ . '/../src/Auth.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_name(SESSION_NAME);
    session_start();
}

// Must be logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ' . APP_URL . '/sign-in');
    exit;
}

$userId = $_SESSION['user_id'];
$message = '';
$messageType = '';

// Database connection
try {
    $dsn = "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4";
    $pdo = new PDO($dsn, DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);
} catch (PDOException $e) {
    error_log("Database connection failed in resend-verification: " . $e->getMessage());
    $message = 'System error. Please try again later.';
    $messageType = 'error';
}

// Handle resend request
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($pdo)) {
    // CSRF Protection
    if (!isset($_POST['csrf_token']) || !isset($_SESSION['csrf_token']) || 
        !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        $message = 'Invalid security token. Please try again.';
        $messageType = 'error';
    } else {
        // Regenerate CSRF token
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        
        try {
            // Check rate limit (3 per hour)
            $rateLimitDir = sys_get_temp_dir() . '/traderalign_rate_limits';
            if (!is_dir($rateLimitDir)) {
                mkdir($rateLimitDir, 0755, true);
            }
            
            $rateLimitKey = 'resend_verify_' . $userId;
            $rateLimitFile = $rateLimitDir . '/' . md5($rateLimitKey) . '.json';
            $rateLimitData = [];
            
            if (file_exists($rateLimitFile)) {
                $rateLimitData = json_decode(file_get_contents($rateLimitFile), true) ?: [];
            }
            
            // Clean old entries (1 hour window)
            $oneHourAgo = time() - 3600;
            $rateLimitData = array_filter($rateLimitData, function($timestamp) use ($oneHourAgo) {
                return $timestamp > $oneHourAgo;
            });
            
            if (count($rateLimitData) >= 3) {
                $oldestAttempt = min($rateLimitData);
                $waitMinutes = ceil(($oldestAttempt + 3600 - time()) / 60);
                $message = "Please wait {$waitMinutes} minutes before requesting another verification email.";
                $messageType = 'warning';
            } else {
                // Get user data
                $stmt = $pdo->prepare('SELECT id, email, email_verified_at FROM users WHERE id = :uid AND deleted_at IS NULL');
                $stmt->execute([':uid' => $userId]);
                $user = $stmt->fetch();
                
                if (!$user) {
                    $message = 'User not found.';
                    $messageType = 'error';
                } elseif ($user['email_verified_at'] !== null) {
                    $message = 'Your email is already verified!';
                    $messageType = 'success';
                } else {
                    // Generate new verification token
                    $data = random_bytes(16);
                    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
                    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
                    $newToken = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
                    
                    // Update user's verification token
                    $stmt = $pdo->prepare('UPDATE users SET verification_token = :token WHERE id = :uid');
                    $stmt->execute([':token' => $newToken, ':uid' => $userId]);

                    $verificationUrl = APP_URL . '/verify?token=' . urlencode($newToken);

                    // Plaintext, unexpired login-capable tokens must never sit
                    // in a web-servable log file in production (logs/ is also
                    // blocked at the web-server level via logs/.htaccess, but
                    // this keeps a real token out of that file entirely
                    // outside of local development).
                    if (APP_ENV === 'development') {
                        $logDir = __DIR__ . '/../logs';
                        if (!is_dir($logDir)) {
                            mkdir($logDir, 0755, true);
                        }
                        $logEntry = sprintf(
                            "[%s] RESENT - User ID: %s | Email: %s | Token: %s | URL: %s\n",
                            date('Y-m-d H:i:s'),
                            $userId,
                            $user['email'],
                            $newToken,
                            $verificationUrl
                        );
                        file_put_contents($logDir . '/verification.log', $logEntry, FILE_APPEND | LOCK_EX);
                    }

                    // Add to rate limit
                    $rateLimitData[] = time();
                    file_put_contents($rateLimitFile, json_encode($rateLimitData));
                    
                    // Try to send email
                    if (defined('RESEND_API_KEY') && RESEND_API_KEY) {
                        // Same sendVerificationEmail function from sign-up.php
                        $emailSent = sendVerificationEmail($user['email'], $verificationUrl, $userId);
                        if ($emailSent) {
                            $message = 'Verification email sent! Check your inbox.';
                            $messageType = 'success';
                        } else {
                            $message = 'Verification link generated. Email delivery failed, but you can use the link from the logs.';
                            $messageType = 'warning';
                        }
                    } else {
                        $message = 'Verification link generated (check logs). Configure RESEND_API_KEY for email delivery.';
                        $messageType = 'info';
                    }
                }
            }
        } catch (PDOException $e) {
            error_log("Resend verification failed: " . $e->getMessage());
            $message = 'System error. Please try again later.';
            $messageType = 'error';
        }
    }
}

// Generate CSRF token if not exists
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Get user email for display
try {
    $stmt = $pdo->prepare('SELECT email, email_verified_at FROM users WHERE id = :uid');
    $stmt->execute([':uid' => $userId]);
    $userData = $stmt->fetch();
} catch (PDOException $e) {
    $userData = null;
}

/**
 * Send email verification email using Resend API
 */
function sendVerificationEmail(string $email, string $verifyUrl, string $userId): bool
{
    $apiKey = RESEND_API_KEY;
    $fromEmail = 'TraderAlign <noreply@yourdomain.com>';
    
    $html = <<<HTML
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Verify Your Email</title>
    </head>
    <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px; background-color: #f9fafb;">
        <div style="background: linear-gradient(135deg, #2563eb, #1d4ed8); padding: 30px; border-radius: 8px 8px 0 0; text-align: center;">
            <h1 style="color: #ffffff; font-size: 28px; margin: 0;">TraderAlign</h1>
            <p style="color: #bfdbfe; margin: 10px 0 0;">Trading Journal & Analytics</p>
        </div>
        
        <div style="background: #ffffff; padding: 30px; border-radius: 0 0 8px 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
            <h2 style="color: #1a1a1a; font-size: 22px; margin-top: 0;">Verify Your Email Address</h2>
            
            <p style="font-size: 16px;">Please verify your email address by clicking the button below:</p>
            
            <div style="text-align: center; margin: 35px 0;">
                <a href="{$verifyUrl}" style="display: inline-block; background: linear-gradient(135deg, #2563eb, #1d4ed8); color: #ffffff; text-decoration: none; padding: 14px 40px; border-radius: 8px; font-weight: 600; font-size: 16px; box-shadow: 0 2px 4px rgba(37, 99, 235, 0.3);">Verify Email</a>
            </div>
            
            <p style="font-size: 14px; color: #6b7280;">Or copy and paste this link in your browser:</p>
            <p style="background: #f3f4f6; padding: 12px; border-radius: 6px; word-break: break-all; font-size: 13px; color: #4b5563;">{$verifyUrl}</p>
            
            <hr style="border: none; border-top: 1px solid #e5e7eb; margin: 30px 0;">
            
            <p style="font-size: 13px; color: #9ca3af;">If you didn't request this, you can safely ignore this email.</p>
        </div>
    </body>
    </html>
    HTML;

    $data = [
        'from' => $fromEmail,
        'to' => $email,
        'subject' => 'Verify Your Email - TraderAlign',
        'html' => $html,
        'headers' => [
            'X-Entity-Ref-ID' => 'verify-' . $userId . '-' . time(),
        ],
    ];

    $ch = curl_init('https://api.resend.com/emails');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 5,
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        error_log("Resend API curl error: {$curlError}");
        return false;
    }

    if ($httpCode !== 200) {
        error_log("Resend API error (HTTP {$httpCode}): {$response}");
        return false;
    }

    return true;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Resend Verification - TraderAlign</title>
    <link rel="icon" type="image/png" sizes="32x32" href="/traderalign/assets/favicon/favicon-32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/traderalign/assets/favicon/favicon-16.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/traderalign/assets/favicon/apple-touch-icon.png">
    <link rel="shortcut icon" href="/traderalign/assets/favicon/favicon.ico">
    <link rel="stylesheet" href="/traderalign/assets/css/brand.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        surface: {
                            50: '#f8fafc',
                            100: '#f1f5f9',
                            200: '#e2e8f0',
                            300: '#cbd5e1',
                            600: '#475569',
                            700: '#334155',
                            800: '#1e293b',
                            900: '#0f172a',
                            950: '#020617'
                        },
                        brand: {
                            50: '#eff6ff',
                            100: '#dbeafe',
                            500: '#3b82f6',
                            600: '#2563eb',
                            700: '#1d4ed8'
                        }
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-surface-950 text-surface-100 min-h-screen">
    <div class="max-w-2xl mx-auto px-4 py-16">
        <!-- Header -->
        <div class="text-center mb-8">
            <a href="/traderalign/" class="inline-block mb-4">
                <img src="/traderalign/images/logo.png" alt="TraderAlign" class="ta-logo ta-logo--xl" style="margin:0 auto;">
            </a>
            <h1 class="text-3xl font-bold text-white mb-2">Resend Verification Email</h1>
            <p class="text-surface-300">We'll send a new verification link to your email</p>
        </div>

        <!-- Message Display -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-lg <?php 
            echo match($messageType) {
                'success' => 'bg-green-500/10 border border-green-500/20 text-green-400',
                'error' => 'bg-red-500/10 border border-red-500/20 text-red-400',
                'warning' => 'bg-yellow-500/10 border border-yellow-500/20 text-yellow-400',
                'info' => 'bg-blue-500/10 border border-blue-500/20 text-blue-400',
                default => 'bg-surface-800 border border-surface-700 text-surface-300'
            };
        ?>">
            <p class="text-sm"><?php echo htmlspecialchars($message); ?></p>
        </div>
        <?php endif; ?>

        <!-- Already Verified State -->
        <?php if (isset($userData) && $userData['email_verified_at'] !== null): ?>
        <div class="bg-surface-800/50 border border-surface-700 rounded-xl p-8 text-center">
            <div class="text-green-400 mb-4">
                <svg class="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
            </div>
            <h2 class="text-xl font-semibold text-white mb-2">Email Already Verified</h2>
            <p class="text-surface-300 mb-6">Your email has been verified. You have full access to all features.</p>
            <a href="<?php echo APP_URL; ?>/dashboard" class="inline-block px-6 py-3 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors">
                Go to Dashboard
            </a>
        </div>

        <!-- Resend Form -->
        <?php else: ?>
        <div class="bg-surface-800/50 border border-surface-700 rounded-xl p-6">
            <?php if (isset($userData)): ?>
            <div class="mb-6 p-4 bg-surface-900/50 rounded-lg border border-surface-700">
                <p class="text-sm text-surface-300">Verification will be sent to:</p>
                <p class="text-white font-medium"><?php echo htmlspecialchars($userData['email']); ?></p>
            </div>
            <?php endif; ?>

            <form method="POST" action="" class="space-y-6">
                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                
                <div class="bg-surface-900/50 rounded-lg p-4 border border-surface-700">
                    <div class="flex items-start gap-3">
                        <svg class="w-5 h-5 text-surface-400 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        <div class="text-sm text-surface-300">
                            <p class="font-medium text-surface-200 mb-1">Important:</p>
                            <ul class="list-disc list-inside space-y-1">
                                <li>You can request up to 3 verification emails per hour</li>
                                <li>Check your spam folder if you don't see the email</li>
                                <li>The verification link expires after 24 hours</li>
                            </ul>
                        </div>
                    </div>
                </div>

                <button type="submit" class="w-full px-6 py-3 bg-brand-600 text-white rounded-lg hover:bg-brand-700 transition-colors font-medium focus:outline-none focus:ring-2 focus:ring-brand-500 focus:ring-offset-2 focus:ring-offset-surface-800">
                    Send Verification Email
                </button>
            </form>

            <div class="mt-6 text-center">
                <a href="<?php echo APP_URL; ?>/dashboard" class="text-sm text-surface-400 hover:text-surface-200 transition-colors">
                    ← Back to Dashboard
                </a>
            </div>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>