<?php
/***
 * API REF USAGE : VERIFY SINGLE OR MULTIPLE EMAIL
 * EMAIL_TO_VERIFY multiple email accepted using comma seperate.
 * /api/v?user=USERNAME&api_token=YOUR_TOKEN&verify=EMAIL_TO_VERIFY
 ***/
include '../pagename.php';
include '../../config.php';
require_once __DIR__ . '/../class.runtime.signal.php';
$gate = RuntimeSignal::instance();
if (!$gate->enforce('api:v')) {
	http_response_code(403);
	echo json_encode(array('code' => '403', 'error' => ($gate->message() !== '' ? $gate->message() : 'Access denied')));
	header('Content-type: application/json');
	exit();
}

if (isset($_REQUEST['api_token']) && !empty($_REQUEST['api_token']) && isset($_REQUEST['user']) && !empty($_REQUEST['user'])) {
	$api_token = $_REQUEST['api_token'];
	$user = $_REQUEST['user'];

	// Fetch stored credentials from evp_options
	$options_query = "SELECT option_name, option_value FROM evp_options WHERE option_name IN ('api_token', 'username', 'user_id')";
	$options_result = $db->select($options_query);
	$stored_options = [];
	if ($options_result) {
		while ($row = $options_result->fetch_assoc()) {
			$stored_options[$row['option_name']] = $row['option_value'];
		}
	}

	$stored_token = isset($stored_options['api_token']) ? $stored_options['api_token'] : '';
	$stored_user = isset($stored_options['username']) ? $stored_options['username'] : '';
	$stored_uid = isset($stored_options['user_id']) ? $stored_options['user_id'] : '';

	if ($stored_token === $api_token && $stored_user === $user && !empty($stored_uid)) {
		$user_id = $stored_uid;
		if (isset($_REQUEST['verify']) && !empty($_REQUEST['verify'])) {
			$emailVerify = $_REQUEST['verify'];
			$emailVerify = explode(',', $emailVerify);
			set_time_limit(0);
			include '../scripts/scan/class.verify.email.php';
			$i = 0;
			$json = [];
			foreach ($emailVerify as $email) {
				$i++;
				$verify = new VerifyEmail($email, $db, $user_id);
				$status = $verify->status;
				$code = '200'; // Response Return Succeed
				$json[] = array(
					'index' => $i,
					'verify' => "$email",
					'response' => [
						'safetosend' => $status['safe_to_send'],
						'status' => $status['status'],
						'type' => $status['type'],
						'v_response' => $status['v_response'],
						'mx_server' => $status['mx_server'],
						'mx_response' => $status['mx_response']
					],
					'code' => "$code"
				);
			}
			echo json_encode($json);
		} else {
			$code = '101'; // No Task Given  	101
			echo json_encode(array('code' => "$code"));
		}
	} else {
		$code = '100'; // Invalid Authorization
		echo json_encode(array('code' => "$code"));
	}
} else {
	header("Location: $a_url/" . $error_404_page);
	$code = '404'; // 404 Not Found
	echo json_encode(array('code' => "$code"));
}
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// headers to tell that result is JSON
header('Content-type: application/json');
exit();