<?php
/**
 * Email Verification Endpoint
 * Verifies user email addresses via token sent during registration
 */

error_reporting(E_ALL);
ini_set('display_errors', 1);

// CORS headers (reflect origin when using 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: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');

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

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/utils/EmailVerification.php';

/**
 * Send JSON response
 */
function sendResponse($success, $message, $data = null, $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json');
    
    $response = [
        'success' => $success,
        'message' => $message
    ];
    
    if ($data !== null) {
        $response['data'] = $data;
    }
    
    echo json_encode($response);
    exit;
}

/**
 * Log verification attempts
 */
function logVerification($message, $data = null) {
    $logDir = __DIR__ . '/../logs';
    if (!file_exists($logDir)) {
        mkdir($logDir, 0755, true);
    }
    
    $logMessage = '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
    if ($data !== null) {
        $logMessage .= 'Data: ' . print_r($data, true) . "\n";
    }
    
    $logFile = $logDir . '/email_verification.log';
    error_log($logMessage, 3, $logFile);
}

try {
    global $pdo;
    
    if (!isset($pdo)) {
        sendResponse(false, 'Database connection not available', null, 500);
    }
    
    // Get token from URL parameter
    $token = $_GET['token'] ?? '';
    
    if (empty($token)) {
        logVerification("Verification attempt with no token");
        sendResponse(false, 'Verification token is required', null, 400);
    }
    
    logVerification("Verification attempt with token", ['token_preview' => substr($token, 0, 20) . '...']);
    
    // Get the valid token from database
    $tokenData = EmailVerification::getValidToken($pdo, $token);
    
    if (!$tokenData) {
        logVerification("Invalid or expired token", ['token_preview' => substr($token, 0, 20) . '...']);
        sendResponse(false, 'Invalid or expired verification token. Please request a new verification email.', null, 400);
    }
    
    logVerification("Valid token found for user", ['user_id' => $tokenData['user_id'], 'email' => $tokenData['email']]);
    
    // Check if token was already used
    if (!empty($tokenData['used_at'])) {
        logVerification("Token already used", ['user_id' => $tokenData['user_id']]);
        sendResponse(true, 'Email address has already been verified. You can now log in.', [
            'email' => $tokenData['email'],
            'already_verified' => true
        ]);
    }
    
    // Begin transaction
    $pdo->beginTransaction();
    
    try {
        // Mark token as used
        $tokenUsed = EmailVerification::markTokenUsed($pdo, $tokenData['id']);
        
        if (!$tokenUsed) {
            throw new Exception('Failed to mark token as used');
        }
        
        // Update user's email_verified status (tolerant if column missing)
        $hasEmailVerified = false;
        try {
            $col = $pdo->query("SHOW COLUMNS FROM users LIKE 'email_verified'");
            $hasEmailVerified = $col && $col->rowCount() > 0;
        } catch (Exception $ie) {
            $hasEmailVerified = false;
        }

        $userUpdated = true; // default true if column doesn't exist
        if ($hasEmailVerified) {
            $stmt = $pdo->prepare("UPDATE users SET email_verified = 1 WHERE id = ?");
            $userUpdated = $stmt->execute([$tokenData['user_id']]);
        }
        
        if (!$userUpdated) {
            throw new Exception('Failed to update user verification status');
        }
        
        // Commit transaction
        $pdo->commit();
        
        logVerification("Email successfully verified", [
            'user_id' => $tokenData['user_id'],
            'email' => $tokenData['email']
        ]);
        
        // Return success with redirect URL
        sendResponse(true, 'Email address verified successfully! You can now log in.', [
            'email' => $tokenData['email'],
            'username' => $tokenData['username'],
            'redirect_url' => '/login'
        ], 200);
        
    } catch (Exception $e) {
        // Rollback transaction
        $pdo->rollBack();
        
        logVerification("Verification failed in transaction", [
            'error' => $e->getMessage(),
            'user_id' => $tokenData['user_id'] ?? null
        ]);
        
        sendResponse(false, 'Verification failed. Please try again or request a new verification email.', null, 500);
    }
    
} catch (Exception $e) {
    logVerification("Verification endpoint error", [
        'error' => $e->getMessage(),
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ]);
    
    sendResponse(false, 'An error occurred during verification. Please try again later.', null, 500);
}
