<?php
// import_per_count.php
require_once('../config.php');
header('Content-Type: application/json');

$csv_file_name = isset($_POST['csv_file_name']) ? trim($_POST['csv_file_name']) : '';
$user_id = isset($_POST['user_id']) ? trim($_POST['user_id']) : '';

if (!$csv_file_name || !$user_id) {
    echo json_encode(['success' => false, 'error' => 'Missing parameters.']);
    exit;
}

// Get import task meta
$sql = "SELECT meta, status FROM evp_task WHERE csv_name = '" . mysqli_real_escape_string($db->link, $csv_file_name) . "' AND user_id = '" . mysqli_real_escape_string($db->link, $user_id) . "' AND status = 'importing' LIMIT 1";
$res = $db->select($sql);
if ($res && $row = $res->fetch_assoc()) {
    $meta = json_decode($row['meta'], true);
    $imported = isset($meta['imported_total']) ? (int)$meta['imported_total'] : 0;
    $skipped = isset($meta['skipped_total']) ? (int)$meta['skipped_total'] : 0;
    $total = isset($meta['total_lines']) ? (int)$meta['total_lines'] : 0;
    $display_total = $total - $skipped;
    if ($display_total < 0) $display_total = 0;
    $complete = ($imported >= $display_total && $display_total > 0);
    echo json_encode([
        'success' => true,
        'imported' => $imported,
        'total' => $display_total,
        'skipped' => $skipped,
        'complete' => $complete
    ]);
    exit;
} else {
    // If not found, check if import is complete
    $meta_sql = "SELECT total FROM evp_email_list_metadata WHERE csv_file_name = '" . mysqli_real_escape_string($db->link, $csv_file_name) . "' AND user_id = '" . mysqli_real_escape_string($db->link, $user_id) . "' LIMIT 1";
    $meta_res = $db->select($meta_sql);
    if ($meta_res && $meta_row = $meta_res->fetch_assoc()) {
        $imported = (int)$meta_row['total'];
        echo json_encode([
            'success' => true,
            'imported' => $imported,
            'total' => $imported,
            'complete' => true
        ]);
        exit;
    }
    echo json_encode(['success' => false, 'error' => 'Task not found.']);
    exit;
}
