<?php
// api/auth/verify-email.php

require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';

$token = isset($_GET['token']) ? $_GET['token'] : null;

if (!$token) {
    sendError('Verification token required', 400);
}

try {
    // Find verification record
    $stmt = $pdo->prepare("
        SELECT user_id, expires_at 
        FROM email_verifications 
        WHERE token = :token
    ");
    $stmt->execute([':token' => $token]);
    $verification = $stmt->fetch();
    
    if (!$verification) {
        sendError('Invalid verification token', 400);
    }
    
    // Check if expired
    $expires_at = strtotime($verification['expires_at']);
    if (time() > $expires_at) {
        // Delete expired token
        $stmt = $pdo->prepare("DELETE FROM email_verifications WHERE token = :token");
        $stmt->execute([':token' => $token]);
        sendError('Verification token has expired', 400);
    }
    
    // Update user status to active
    $stmt = $pdo->prepare("
        UPDATE users 
        SET status = 'active' 
        WHERE id = :user_id AND status = 'pending'
    ");
    $stmt->execute([':user_id' => $verification['user_id']]);
    
    // Delete verification token
    $stmt = $pdo->prepare("DELETE FROM email_verifications WHERE token = :token");
    $stmt->execute([':token' => $token]);
    
    // Return success page (HTML for browser)
    echo "<!DOCTYPE html>
    <html>
    <head>
        <title>Email Verified</title>
        <style>
            body { font-family: Arial; text-align: center; padding: 50px; }
            .success { color: green; }
            .container { max-width: 500px; margin: 0 auto; }
        </style>
    </head>
    <body>
        <div class='container'>
            <h1 class='success'>✓ Email Verified!</h1>
            <p>Your email has been successfully verified.</p>
            <p>You can now <a href='http://localhost/mypodcast/admin/login.html'>login to your account</a>.</p>
        </div>
    </body>
    </html>";
    
} catch (PDOException $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>