<?php
include 'pagename.php';
include $session;
Session::checkSession_app();
$user_id = Session::get('id');
Session::close();
include '../config.php';
require_once __DIR__ . '/class.runtime.signal.php';
$cachedSnapshot = TetherPulse::recall();
$runtimeSignal = RuntimeSignal::instance();
global $log;
if (!$runtimeSignal->enforce('api:quick-validate')) {
    $errorText = $runtimeSignal->message();
    if (empty($errorText)) {
        $errorText = 'License validation failed. Please reactivate your license to continue.';
    }
    if (function_exists('error_log')) {
        error_log('[quick_mail_verify] status=' . json_encode($runtimeSignal->status()));
    }
    if (isset($log) && method_exists($log, 'system_debug')) {
        $log->system_debug('[quick_mail_verify] status=' . json_encode($runtimeSignal->status()));
    }
    http_response_code(403);
    echo json_encode([
        'index' => $index ?? null,
        'error' => $errorText,
        'debug' => $runtimeSignal->status(),
        'snapshot' => $cachedSnapshot
    ]);
    exit();
}
$email = 0;
extract($_POST);
if (empty($email)) {
    echo json_encode([
        'error' => 'No email provided',
        'index' => $index ?? null
    ]);
    exit();
}
set_time_limit(0);
$start_time = microtime(true);
include 'scripts/scan/class.verify.email.php';

require_once __DIR__ . '/class.warmup.manager.php';
$warmupMgr = new WarmupManager($db, isset($log) ? $log : null);

if (!$warmupMgr->canScan($email)) {
    echo json_encode([
        'index' => $index ?? null,
        'safetosend' => 'No',
        'status' => 'Skipped',
        'type' => 'Limit Reached',
        'v_response' => 'Daily Warm-up Limit Reached',
        'domain_dns' => '-',
        'mx_server' => '-',
        'mx_response' => '-',
        'time_taken' => '0 secs',
        'debug' => []
    ]);
    exit();
}

$verify = new VerifyEmail($email, $db, $user_id);
$status = $verify->status;
$debug_arr = $verify->debug;
if (isset($log)) {
    $log->scan_debug('DEBUG quick_mail_verify.php: $verify->status = ' . print_r($status, true));
}

if (isset($status['status'])) {
    $warmupMgr->incrementCount($email);
}

$end_time = microtime(true);
$time_taken = round($end_time - $start_time, 2) . ' secs';

echo json_encode([
    'index' => $index ?? null,
    'safetosend' => $status['safe_to_send'],
    'status' => $status['status'],
    'type' => $status['type'],
    'v_response' => $status['v_response'],
    'domain_dns' => $status['domain_dns'],
    'mx_server' => $status['mx_server'],
    'mx_response' => $status['mx_response'],
    'time_taken' => $time_taken ?? null,
    'debug' => $debug_arr ?? null
]);

$debug = json_encode([$email => $debug_arr]);

$log->system_debug($debug);

exit();