<?php
// Start measuring execution time
$start_time = microtime(true);

// Include required files
include 'pagename.php';
include '../config.php';

// Set content type to JSON and disable any output buffering
header('Content-Type: application/json');
ob_clean(); // Clean any previous output

// Initialize response array
$response = array(
    'success' => false,
    'percent' => 0,
    'total_verify' => 0,
    'status' => 'unknown',
    'details' => array()
);

try {
    // Validate input parameters
    // Defensive: Require both filename and uid for all polling
    if ((isset($_POST['filenames']) && is_array($_POST['filenames']) && isset($_POST['uid'])) || (isset($_POST['filename']) && isset($_POST['uid']))) {
        $user_id = mysqli_real_escape_string($db->link, $_POST['uid']);
        $results = array();
        $filenames = array();
        if (isset($_POST['filenames']) && is_array($_POST['filenames'])) {
            $filenames = $_POST['filenames'];
        } elseif (isset($_POST['filename'])) {
            $filenames[] = $_POST['filename'];
        }
        foreach ($filenames as $csv_file_name) {
            $csv_file_name = mysqli_real_escape_string($db->link, $csv_file_name);
            $email_meta_info = "SELECT * FROM evp_email_list_metadata WHERE csv_file_name = '$csv_file_name' AND user_id = '$user_id'";
            $meta_info = $db->select($email_meta_info);
            if (!$meta_info || mysqli_num_rows($meta_info) == 0) {
                $results[$csv_file_name] = array('success' => false, 'error' => 'No data found for this CSV file');
                continue;
            }
            $csv_result = $meta_info->fetch_assoc();
            $scan_status = $csv_result['scan_status'];
            $count_valid = intval($csv_result['valid']);
            $count_invalid = intval($csv_result['invalid']);
            $count_catchall = intval($csv_result['catch_all']);
            $count_unknown = intval($csv_result['unknown']);
            $count_skipped = intval($csv_result['skipped']);
            $count_free = intval($csv_result['free_account']);
            $count_role = intval($csv_result['role_account']);
            $count_disposable = intval($csv_result['disposable']);
            $count_syntax = intval($csv_result['syntax_error']);
            $total_email = intval($csv_result['total']);
            $total_verify = $count_valid + $count_invalid + $count_catchall + $count_unknown + $count_skipped;
            $verify_per_status = ($total_email > 0) ? ceil(($total_verify / $total_email) * 100) : 0;
            $csv_name_ex = preg_replace('/\.[^.\s]{3,4}$/', '', $csv_file_name);
            $results[$csv_file_name] = array(
                'success' => true,
                'percent' => $verify_per_status,
                'total_verify' => $total_verify,
                'status' => $scan_status,
                'total' => $total_email,
                'details' => array(
                    array("valid_" . $csv_name_ex => $count_valid),
                    array("invalid_" . $csv_name_ex => $count_invalid),
                    array("catchall_" . $csv_name_ex => $count_catchall),
                    array("unknown_" . $csv_name_ex => $count_unknown),
                    array("skipped_" . $csv_name_ex => $count_skipped),
                    array("free_account_" . $csv_name_ex => $count_free),
                    array("role_account_" . $csv_name_ex => $count_role),
                    array("disposable_" . $csv_name_ex => $count_disposable),
                    array("syntax_" . $csv_name_ex => $count_syntax)
                )
            );
        }
        // Always return as an object keyed by filename
        echo json_encode($results, JSON_NUMERIC_CHECK);
        exit;
    } else {
        $response['error'] = "Missing required parameters: filename and uid are required.";
        echo json_encode($response, JSON_NUMERIC_CHECK);
        exit;
    }
} catch (Exception $e) {
    $response['error'] = $e->getMessage();
    echo json_encode($response, JSON_NUMERIC_CHECK);
    exit;
}

// End execution to prevent any additional output
?>