<?php
// api/km_check.php
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../auth_stub.php';

session_start();

function json_error($message, $code = 400) {
    http_response_code($code);
    echo json_encode(['status' => 'error', 'message' => $message], JSON_UNESCAPED_UNICODE);
    exit;
}

function json_ok($data = []) {
    echo json_encode(array_merge(['status' => 'ok'], $data), JSON_UNESCAPED_UNICODE);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
    if ($action !== 'check') {
        json_error('Noto‘g‘ri action', 400);
    }

    if ($method !== 'POST') {
        json_error('POST bo‘lishi kerak', 405);
    }

    $mode = $_POST['mode'] ?? '';
    if (!in_array($mode, ['consumer', 'group'], true)) {
        json_error('Mode noto‘g‘ri (consumer/group)', 400);
    }

    if (empty($_FILES['file']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
        json_error('Fayl yuklanmadi', 400);
    }

    $origName = $_FILES['file']['name'] ?? '';
    $tmpPath  = $_FILES['file']['tmp_name'];

    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    // Hozircha faqat tekst fayllar (TXT/CSV). XLS/XLSX uchun keyin PhpSpreadsheet qo‘shish mumkin.
    if (!in_array($ext, ['txt', 'csv', 'dat', 'log'])) {
        json_error('Hozircha faqat TXT/CSV kabi tekst fayllar qo‘llab-quvvatlanadi.', 400);
    }

    $content = file_get_contents($tmpPath);
    if ($content === false) {
        json_error('Faylni o‘qib bo‘lmadi', 500);
    }

    $lines = preg_split('/\r\n|\r|\n/', $content);
    $rawCount = count($lines);

    $codes = [];
    foreach ($lines as $line) {
        $code = trim($line);
        if ($code === '') continue;
        // GS1 dataMatrix matni bo‘lsa, shu bo‘yicha tekshiramiz
        $codes[] = $code;
    }

    $codes = array_values(array_unique($codes));
    $uniqueCount = count($codes);

    if ($uniqueCount === 0) {
        json_ok([
            'mode'          => $mode,
            'total_uploaded'=> $rawCount,
            'total_unique'  => 0,
            'found_count'   => 0,
            'missing_count' => 0,
            'missing_codes' => []
        ]);
    }

    // Qaysi jadval/ustundan qidiramiz
    if ($mode === 'consumer') {
        $table  = 'codes';
        $column = 'gs1_text';
    } else { // group
        $table  = 'blocks';
        $column = 'gtin2_number';
    }

    // Bazadan borlarini topish (chunk bilan)
    $found = [];
    $chunkSize = 800;

    for ($i = 0; $i < $uniqueCount; $i += $chunkSize) {
        $chunk = array_slice($codes, $i, $chunkSize);
        $placeholders = implode(',', array_fill(0, count($chunk), '?'));
        $sql = "SELECT DISTINCT $column AS val FROM $table WHERE $column IN ($placeholders)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($chunk);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            if (!empty($row['val'])) {
                $found[$row['val']] = true;
            }
        }
    }

    $missing = [];
    foreach ($codes as $c) {
        if (!isset($found[$c])) {
            $missing[] = $c;
        }
    }

    $missingCount = count($missing);
    $foundCount   = $uniqueCount - $missingCount;

    json_ok([
        'mode'           => $mode,
        'file_name'      => $origName,
        'total_uploaded' => $rawCount,
        'total_unique'   => $uniqueCount,
        'found_count'    => $foundCount,
        'missing_count'  => $missingCount,
        'missing_codes'  => $missing,
    ]);

} catch (Throwable $e) {
    json_error('Server xatosi', 500);
}
