<?php set_time_limit(0);
ini_set('display_errors', 1);

include 'pagename.php';

include $session;

Session::checkSession_app();

include '../config.php';

require_once __DIR__ . '/class.runtime.signal.php';
$licenseGate = RuntimeSignal::instance();
if (!$licenseGate->enforce('api:bulk-upload')) {
    $errorMsg = $licenseGate->message();
    if (empty($errorMsg)) {
        $errorMsg = 'License validation failed. Please reactivate your license to continue.';
    }
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => $errorMsg]);
    exit;
}

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$file_data = $_SESSION['file_data'];
$tmp_name = $_SESSION['file_name'];
$file_size = $_SESSION['file_size'];
$file_size = round($file_size, 2);
unset($_SESSION['file_data']);
unset($_SESSION['file_name']);
unset($_SESSION['file_size']);


if (($file_size_limit != null) && ($file_size > $file_size_limit)) {
    echo json_encode(['success' => false, 'message' => 'File size exceeds the limit. Please reduce the file size and try again.']);
    exit();
}

function sanitize_text($data)
{
    global $db;
    return mysqli_real_escape_string($db->link, htmlspecialchars(stripslashes(trim($data))));
}

function clear_quotes($strClear)
{
    return preg_replace('/^(\'(.*)\'|"(.*)")$/', '$2$3', $strClear);
}

$filename = sanitize_text($tmp_name);
$filename = preg_replace('/\.csv$/', '', $filename);

$user_id = sanitize_text($_POST['uid']);
$csv_new_name = isset($_POST['csv_new_name']) ? sanitize_text($_POST['csv_new_name']) : null;
$log->system_debug("csv_new_name: " . ($csv_new_name ? $csv_new_name : "NULL"));

$check_mailbox = sanitize_text($_POST['check_mailbox']);
$cc_data = $_POST['cc_data'];
$log->system_debug("cc_data: " . $cc_data);
$cc_data = json_decode($cc_data, true);
$log->system_debug("cc_data (after json_decode): " . json_encode($cc_data));
$cc_data_serialized = serialize($cc_data);

$log->system_debug("cc_data (serialized): " . $cc_data_serialized);

$total = 0;
$start_date = date("Y-m-d h:i:s");

if ($check_mailbox == 'true') {
    $mail_box = 'pending';
} elseif ($check_mailbox == 'false') {
    $check_mailbox = NULL;
}

$curl_called = false;

if (isset($file_size)) {

    $meta = json_encode([
        "import_offset" => 0,
        "total_lines" => 0,
        "processed_rows" => 0,
        "detected_encoding" => null,
        "progress_percentage" => 0,
        "last_processed_time" => time(),
        "batch_processing_time" => 0,
        "memory_usage_mb" => 0,
        "import_pid" => null,
        "import_locked" => false,
        "import_locked_until" => null,
        "last_error" => null,
        "cumulative_imported" => 0,
        "cumulative_duplicates" => 0,
        "cumulative_skipped" => 0,
        "cumulative_total" => 0,
        "imported_total" => 0,
        "duplicate_total" => 0,
        "skipped_total" => 0,
        "parsed_total" => 0
    ]);

    $file_meta = json_decode($meta, true);
    $file_size_bytes = $file_size * 1024 * 1024; // Convert MB to bytes
    $file_meta['file_size_bytes'] = $file_size_bytes;
    $file_meta['file_name_original'] = $tmp_name;
    $file_meta['created_date'] = $start_date;

    $estimated_line_count = (int) ($file_size_bytes / 100);
    $file_meta['estimated_line_count'] = $estimated_line_count;

    $file_meta['file_length_bytes'] = $file_size_bytes;

    $meta = json_encode($file_meta);

    $insert_task_sql = "INSERT INTO evp_task (csv_name, user_id, status, meta) VALUES ('$filename', '$user_id', 'importing', '" . mysqli_real_escape_string($db->link, $meta) . "')";

    $log->system_debug("SQL Query: $insert_task_sql");

    if ($db->insert($insert_task_sql)) {
        $listing_metadata_sql = "INSERT INTO evp_email_list_metadata ( csv_file_name, csv_new_name, total, creation_date, scan_status, check_mailbox, user_id, cc_data ) 
                             VALUES ('$filename', " . ($csv_new_name ? "'$csv_new_name'" : "NULL") . ", '$total', '$start_date', 'pending', '$check_mailbox', '$user_id', '$cc_data_serialized')";
        $log->system_debug("Metadata SQL Query: $listing_metadata_sql");
        $listing_metadata_read = $db->insert($listing_metadata_sql);
        $log->system_debug("Task metadata structure: " . $meta);
        if (!$curl_called) {
            $curl_url = $s_url . '/functions/tasks/scheduler.import.php?cron=' . $apiKey_opt;
            $log->system_debug("cURL URL: " . $curl_url);
            $log->system_debug("API Key: " . $apiKey_opt);
            $curl = curl_init();
            curl_setopt_array($curl, [
                CURLOPT_URL => $curl_url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 5,
                CURLOPT_FRESH_CONNECT => true,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
            ]);

            $response = curl_exec($curl);
            $err = curl_error($curl);


            if ($err) {
                $log->system_debug("cURL Error: " . $err . " - Import will be processed by scheduled task");
            } else {
                $log->system_debug("Import process started successfully: " . substr($response, 0, 100));
            }

            $log->system_debug("Import process initiated for CSV file: $filename");

            $curl_called = true;
        }
        if ($curl_called) {
            echo json_encode(['success' => true, 'task' => 'import', 'message' => 'CSV file will import in background.']);
        }

    } else {
        $log->system_debug("SQL Error: " . mysqli_error($db->link));
        echo json_encode(['success' => false, 'message' => 'Failed to assign Import Task for this CSV file.']);
    }

}

exit();
