<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/pricing.php';

$user = sparrow_require_backyard_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    sparrow_redirect('/backyard/import.php');
}

try {
    if (empty($_FILES['pricing_csv']['tmp_name'])) {
        throw new RuntimeException('Please choose a pricing CSV file.');
    }

    $file = $_FILES['pricing_csv'];

    if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        throw new RuntimeException('The pricing CSV could not be uploaded.');
    }

    $matrix_text = file_get_contents($file['tmp_name']);

    if ($matrix_text === false || trim($matrix_text) === '') {
        throw new RuntimeException('The pricing CSV file is empty or could not be read.');
    }

    $count = sparrow_import_pricing_matrix_from_text(
    $matrix_text,
    'Gildan Light Cotton Shirt',
    15.00,
    18.00,
    'Imported from pricing spreadsheet',
    !empty($_POST['matrix_replace_existing'])
);

    sparrow_redirect('/backyard/import.php?pricing_imported=' . (int) $count);
} catch (Throwable $e) {
    sparrow_redirect('/backyard/import.php?pricing_error=' . urlencode($e->getMessage()));
}