<?php
/**
 * API Endpoint to check values against filter lists using database.Class.php.
 * 
 * Expects POST request with:
 * - api_key: Security token (must exist in evp_multi_server with status 'active').
 * - value1: Domain/Name to check against evp_domain_filter_list.name.
 * - value2: MX server to check against evp_mx_skiplist.mx_server.
 * - value3: Email address to check against evp_email_filter_list.email_address.
 *
 * Outputs JSON response indicating if each value exists in its respective list.
 */

// --- Include DB Class ---
require_once('../config.php');
header('Content-Type: application/json');

// $log->system_debug("filters_handler.php: Starting filters handler script.");

// --- Database Connection Check ---
if (!isset($db) || !$db->link || $db->link->connect_errno) {
    $errorMessage = 'Database connection failed.';
    if (isset($db) && isset($db->error)) {
        $errorMessage = $db->error;
    } elseif (isset($db) && isset($db->link) && $db->link->connect_error) {
        $errorMessage = $db->link->connect_error;
    }
    echo json_encode(['error' => 'Database connection error.']);
    $log->system_debug("Database Connection Error in filters_handler: " . $errorMessage);
    exit;
}

// --- Request Handling ---
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405); // Method Not Allowed
    echo json_encode(['error' => 'Invalid request method. Only POST is accepted.']);
    exit;
}

// --- Input Retrieval ---
$api_key = $_POST['api_key'] ?? null;
$value1 = $_POST['value1'] ?? null; // Domain/Name for evp_domain_filter_list
$value2 = $_POST['value2'] ?? null; // MX Server for evp_mx_skiplist
$value3 = $_POST['value3'] ?? null; // Email for evp_email_filter_list
$worker_id = $_POST['worker_id'] ?? null;

// if ($worker_id) {
//     $log->system_debug("Worker ID received: $worker_id");
// }

// Check for required parameters
if ($api_key === null && ($value1 === null || $value2 === null || $value3 === null)) {
    http_response_code(400); // Bad Request
    echo json_encode(['error' => 'Missing required parameters (api_key, value1, value2, value3).']);
    exit;
}

// --- API Key Validation ---
$validApiKey = false;
try {
    $escaped_api_key = $db->escape_string($api_key);
    $apiKeySql = "SELECT * FROM `evp_multi_server` WHERE `api_key` = '$escaped_api_key' AND `status` = 'active' LIMIT 1";
    $apiKeyResult = $db->select($apiKeySql);

    if ($apiKeyResult && $apiKeyResult->num_rows > 0) {
        $validApiKey = true;
        $apiKeyResult->free();
        // $log->system_debug("API Key is valid: $escaped_api_key");
    } elseif ($apiKeyResult === false) {
        $log->system_debug("API Key check query failed: " . $db->error);
    }
} catch (Exception $e) {
    $log->system_debug("Error checking API key: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Internal server error during API key validation.']);
    exit;
}

if (!$validApiKey) {
    http_response_code(403); // Forbidden
    echo json_encode(['error' => 'Invalid or inactive API Key.']);
    exit;
}

// --- Handle MX skiplist insert if requested ---
if (
    isset($_POST['insert_mx_skip']) && $_POST['insert_mx_skip'] == 1 &&
    isset($_POST['mx_server']) && !empty($_POST['mx_server']) &&
    isset($_POST['reason'])
) {
    $mx_server = trim($_POST['mx_server']);
    $reason = trim($_POST['reason']);

    $mx_escaped = $db->escape_string($mx_server);
    $sql_check = "SELECT 1 FROM evp_mx_skiplist WHERE mx_server = '$mx_escaped' LIMIT 1";
    $result = $db->select($sql_check);

    if ($result && $result->num_rows > 0) {
        $result->free();
        echo json_encode(['inserted' => false, 'reason' => 'Already exists']);
        exit;
    } else {
        $reason_escaped = $db->escape_string($reason);
        $sql_insert = "INSERT INTO evp_mx_skiplist (mx_server, reason) VALUES ('$mx_escaped', '$reason_escaped')";
        $insert_result = $db->select($sql_insert);
        if ($insert_result !== false) {
            echo json_encode(['inserted' => true]);
        } else {
            echo json_encode(['inserted' => false, 'error' => $db->error]);
        }
        exit;
    }
}

// --- Logic ---
$results = [
    'domain_exists' => false,
    'domain_status' => 'ok',
    'mx_exists' => false,
    'mx_reason' => '',
    'email_exists' => false,
    'email_reason' => '',
    'catch_all_enabled' => false,
];

function getOption(database $db, string $option_name) {
    $option_escaped = $db->escape_string($option_name);
    $sql = "SELECT option_value FROM evp_options WHERE option_name = '$option_escaped' LIMIT 1";
    $result = $db->select($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $result->free();
        return $row['option_value'];
    }
    return null;
}

$filter_skipMX = getOption($db, 'filter_skip_mx') === 'true';
$filter_skipEmail = getOption($db, 'filter_skip_email') === 'true';

function checkIfExists(database $db, string $table, string $column, string $value): bool
{
    $trimmedValue = trim($value);
    if (empty($trimmedValue)) {
        return false;
    }

    if (!preg_match('/^[a-zA-Z0-9_]+$/', $table) || !preg_match('/^[a-zA-Z0-9_]+$/', $column)) {
         $log->system_debug("Invalid table or column name provided to checkIfExists: Table='$table', Column='$column'");
         return false;
    }

    try {
        $value_escaped = $db->escape_string($trimmedValue);
        $sql = "SELECT 1 FROM `$table` WHERE `$column` = '$value_escaped' LIMIT 1";
        $result = $db->select($sql);

        if ($result === false) {
            $log = isset($GLOBALS['log']) ? $GLOBALS['log'] : null;
            if ($log && method_exists($log, 'system_debug')) {
                $log->system_debug("MySQLi query error checking $table.$column: " . $db->error);
            }
            return false;
        }

        $exists = $result->num_rows > 0;
        $log = isset($GLOBALS['log']) ? $GLOBALS['log'] : null;
        if ($log && method_exists($log, 'system_debug')) {
            $log->system_debug("Check for $table.$column with value '$trimmedValue': " . ($exists ? 'Exists' : 'Does not exist'));
        }
        $result->free();
        return $exists;

    } catch (\Exception $e) {
        $log = isset($GLOBALS['log']) ? $GLOBALS['log'] : null;
        if ($log && method_exists($log, 'system_debug')) {
            $log->system_debug("General error in checkIfExists for $table.$column with value '$trimmedValue': " . $e->getMessage());
        }
        return false;
    }
}

function getDomainStatus(database $db, string $domain) {
    $trimmedDomain = trim($domain);
    if (empty($trimmedDomain)) return ['exists' => false, 'status' => 'ok'];
    $domain_escaped = $db->escape_string($trimmedDomain);
    $sql = "SELECT e_type FROM evp_domain_filter_list WHERE name = '$domain_escaped' LIMIT 1";
    $result = $db->select($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $result->free();
        if ($row['e_type'] === 'Disposable Account') {
            return ['exists' => true, 'status' => 'Disposable Account'];
        }
        if ($row['e_type'] === 'Unsupported Domain') {
            return ['exists' => true, 'status' => 'Unsupported Domain'];
        }
        return ['exists' => true, 'status' => 'ok'];
    }
    return ['exists' => false, 'status' => 'ok'];
}

function getMxStatus(database $db, string $mx_server) {
    $trimmedMx = trim($mx_server);
    if (empty($trimmedMx)) return ['exists' => false, 'reason' => ''];
    $mx_escaped = $db->escape_string($trimmedMx);
    $sql = "SELECT reason FROM evp_mx_skiplist WHERE mx_server = '$mx_escaped' LIMIT 1";
    $result = $db->select($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $reason = $row['reason'];
        $result->free();
        return ['exists' => true, 'reason' => $reason];
    }
    return ['exists' => false, 'reason' => ''];
}

function getEmailStatus(database $db, string $email) {
    $trimmedEmail = trim($email);
    if (empty($trimmedEmail)) return ['exists' => false, 'reason' => ''];
    $email_escaped = $db->escape_string($trimmedEmail);
    $sql = "SELECT reason FROM evp_email_filter_list WHERE email_address = '$email_escaped' LIMIT 1";
    $result = $db->select($sql);
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $reason = $row['reason'];
        $result->free();
        return ['exists' => true, 'reason' => $reason];
    }
    return ['exists' => false, 'reason' => ''];
}

function getCatchAllStatus(database $db, string $domain) {
    $trimmedDomain = trim($domain);
    if (empty($trimmedDomain)) return false;
    $domain_escaped = $db->escape_string($trimmedDomain);
    $sql = "SELECT catch_all_check FROM evp_domain_filter_list WHERE name = '$domain_escaped' AND catch_all_check = '1' LIMIT 1";
    $result = $db->select($sql);
    if ($result && $result->num_rows > 0) {
        $result->free();
        return true;
    }
    return false;
}

$domainStatus = getDomainStatus($db, $value1);
$results['domain_exists'] = $domainStatus['exists'];
$results['domain_status'] = $domainStatus['status'];

if ($filter_skipMX) {
    $log->scan_debug("MX check enabled, checking MX server: $value2");
    $mxStatus = getMxStatus($db, $value2);
    $results['mx_exists'] = $mxStatus['exists'];
    $results['mx_reason'] = $mxStatus['reason'];
} else {
    $results['mx_exists'] = false;
    $results['mx_reason'] = '';
}

if ($filter_skipEmail) {
    $emailStatus = getEmailStatus($db, $value3);
    $results['email_exists'] = $emailStatus['exists'];
    $results['email_reason'] = $emailStatus['reason'];
} else {
    $results['email_exists'] = false;
    $results['email_reason'] = '';
}

$results['catch_all_enabled'] = getCatchAllStatus($db, $value1);

$log->scan_debug("Results: " . json_encode($results));
http_response_code(200); // OK
echo json_encode($results);

exit;
?>