<?php
/***
 * API REF USAGE : GET EXISTING SCANNED LISTING DATA
 * /api/get?user=USERNAME&api_token=YOUR_TOKEN&listname=CSV_FILE_NAME&email_status=SCAN_STATUS
 ***/

include '../pagename.php';
include '../../config.php';
require_once __DIR__ . '/../class.runtime.signal.php';
$gate = RuntimeSignal::instance();
if (!$gate->enforce('api:get')) {
	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['listname']) && !empty($_REQUEST['listname'])) {

			$or_std = false;
			$all_std = false;
			$and_std = false;

			if (!empty($cc_data)) {
				function xtrad1($cc_data)
				{
					$data = [];
					foreach ($cc_data as $val) {
						$data[] = ucwords(str_replace('_', ' ', $val));
					}
					return $data;
				}
				function xtrad2($cc_data)
				{
					$data = '';
					foreach ($cc_data as $val) {
						$data .= "$val, ";
					}
					return $data;
				}
				$dataC = xtrad1($cc_data);
				$dataL = xtrad2($cc_data);
			}

			$sql = "SELECT $dataL email_name, email_status, safe_to_send, verification_response, score, bounce_type, email_type, email_acc, email_dom, mail_box, mx_server, mx_response FROM evp_email_list WHERE ";

			function test_input($data)
			{
				$db = new database();
				$data = trim($data);
				$data = stripslashes($data);
				$data = htmlspecialchars($data);
				$data = strtolower($data);
				$data = mysqli_real_escape_string($db->link, $data);
				return $data;
			}

			if (isset($_REQUEST['email_status'])) {
				$email_status = $_REQUEST['email_status'];
			}
			$listname = $_REQUEST['listname'];

			if (!empty($email_status)) {
				$and_std = true;
				$sql .= ' email_status = "' . $email_status . '" AND ';
			} else {
				$all_std = true;
			}
			$sql .= "user_id = '$user_id' AND csv_file_name = '$listname' ";

			if ($all_std || $or_std || $and_std) {
				$read = $db->select($sql);
				$count = mysqli_num_rows($read);
				if ($count > 0) {
					if ($read) {
						$i = 0;
						$json = [];
						foreach ($read as $status) { //write data;
							$i++;
							$code = '200'; // Response Return Succeed
							if (!empty($status['email_type'])) {
								$status['email_type'] = '';
							}
							$json[] = array(
								'index' => $i,
								'email' => $status['email_name'],
								'response' => [
									'safetosend' => $status['safe_to_send'],
									'status' => $status['email_status'],
									'type' => $status['email_type'],
									'v_response' => $status['verification_response'],
									'mx_server' => $status['mx_server'],
									'mx_response' => $status['mx_response']
								],
								'code' => "$code"
							);
						}
						echo json_encode($json);
					}
				} else {
					$code = '103'; // Data not found
					echo json_encode(array('code' => "$code"));
				}
			} else {
				$code = '404'; // 404 Not Found
				echo json_encode(array('code' => "$code"));
			}

		} else {
			$code = '101'; // No Task Given
			echo json_encode(array('code' => "$code"));
		}
	} else {
		$code = '100'; // Invalid Authorization
		echo json_encode(array('code' => "$code"));
	}
} else {
	$code = '404'; // 404 Not Found
	echo json_encode(array('code' => "$code"));
	header("Location: $a_url/" . $error_404_page);
}
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();