<?php
require_once __DIR__ . '/config.php';
require_auth();

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    respond(['error' => 'Method not allowed'], 405);
}

$db = get_db();
$importId = (int)($_GET['id'] ?? 0);
if (!$importId) respond(['error' => 'id is required'], 422);

$stmt = $db->prepare('
    SELECT i.*, sup.name AS supplier_name, pg.code AS product_group_code, pg.name AS product_group_name
    FROM imports i
    LEFT JOIN suppliers sup ON sup.id = i.supplier_id
    LEFT JOIN product_groups pg ON pg.id = i.product_group_id
    WHERE i.id = ?
');
$stmt->execute([$importId]);
$import = $stmt->fetch();

if (!$import) respond(['error' => 'Import not found'], 404);

$stmt = $db->prepare('SELECT * FROM import_rows WHERE import_id = ? ORDER BY style_code');
$stmt->execute([$importId]);
$rows = $stmt->fetchAll();

$grouped = [
    'sample' => [],
    'existing' => [],
    'non_continuable' => [],
    'inactive' => [],
    'new' => [],
];
foreach ($rows as $row) {
    $grouped[$row['classification']][] = $row;
}

$summary = [];
foreach ($grouped as $key => $items) {
    $summary[$key] = [
        'total' => count($items),
        'pending' => count(array_filter($items, fn($r) => $r['row_status'] === 'pending')),
        'onboarded' => count(array_filter($items, fn($r) => $r['row_status'] === 'onboarded')),
        'discarded' => count(array_filter($items, fn($r) => $r['row_status'] === 'discarded')),
    ];
}

respond([
    'import' => $import,
    'rows_by_classification' => $grouped,
    'summary' => $summary,
    'total_rows' => count($rows),
]);
