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

$db = get_db();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $rows = $db->query('
        SELECT i.*, sup.name AS supplier_name, pg.code AS product_group_code, pg.name AS product_group_name,
            (SELECT COUNT(*) FROM import_rows r WHERE r.import_id = i.id) AS total_rows,
            (SELECT COUNT(*) FROM import_rows r WHERE r.import_id = i.id AND r.row_status = "discarded") AS discarded_rows,
            (SELECT COUNT(*) FROM import_rows r WHERE r.import_id = i.id AND r.row_status = "onboarded") AS onboarded_rows,
            (SELECT COUNT(*) FROM import_rows r WHERE r.import_id = i.id AND r.row_status = "pending") AS pending_rows
        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
        ORDER BY i.imported_at DESC
    ')->fetchAll();
    respond($rows);
}

if ($method === 'POST') {
    $input = json_input();
    $required = ['import_number', 'supplier_id', 'product_group_id', 'effective_from', 'effective_to'];
    foreach ($required as $field) {
        if (empty($input[$field])) respond(['error' => "$field is required"], 422);
    }

    $user = require_auth();
    $stmt = $db->prepare('
        INSERT INTO imports (import_number, supplier_id, product_group_id, season, effective_from, effective_to, delivery_from, delivery_to, status, imported_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, "Onboarding", ?)
    ');
    $stmt->execute([
        $input['import_number'],
        $input['supplier_id'],
        $input['product_group_id'],
        $input['season'] ?? null,
        $input['effective_from'],
        $input['effective_to'],
        $input['delivery_from'] ?? $input['effective_from'],
        $input['delivery_to'] ?? $input['effective_to'],
        $user['name'],
    ]);

    respond(['id' => $db->lastInsertId()], 201);
}

respond(['error' => 'Method not allowed'], 405);
