<?php
// Validate a product upload CSV before it reaches the shop. Usage: php validate.php products_upload.csv
// Writes valid_products.csv (clean rows) and upload_errors.csv (row, field, value, problem). Exit 1 if any errors.
declare(strict_types=1);
const CATEGORIES = ['Cleaning', 'Hardware', 'Garden', 'Office', 'Kitchen'];
function check(array $r, array &$seen): array {
    $e = [];
    if (!preg_match('/^SKU-\d{4}$/', $r['sku'])) $e[] = ['sku', 'Format must be SKU-0000'];
    elseif (isset($seen[$r['sku']])) $e[] = ['sku', 'Duplicate of row ' . $seen[$r['sku']]];
    if (trim($r['name']) === '') $e[] = ['name', 'Name is required'];
    if (!in_array($r['category'], CATEGORIES, true)) $e[] = ['category', 'Not an allowed category'];
    if (!preg_match('/^\d+\.\d{2}$/', $r['price'])) $e[] = ['price', 'Use digits with 2 decimals, e.g. 12.50'];
    elseif ((float)$r['price'] <= 0) $e[] = ['price', 'Price must be above 0'];
    if (!ctype_digit($r['stock'])) $e[] = ['stock', 'Stock must be a whole number, 0 or more'];
    if (!preg_match('/^\d{12}$/', $r['barcode'])) $e[] = ['barcode', 'Barcode must be 12 digits'];
    return $e;
}
$in = fopen($argv[1] ?? 'products_upload.csv', 'r'); $hdr = fgetcsv($in, null, ',', '"', '');
$ok = fopen('valid_products.csv', 'w'); $bad = fopen('upload_errors.csv', 'w');
fputcsv($ok, $hdr, ',', '"', ''); fputcsv($bad, ['row', 'sku', 'field', 'value', 'problem'], ',', '"', '');
$seen = []; $n = 0; $valid = 0; $errs = 0; $rowNo = 1;
while (($line = fgetcsv($in, null, ',', '"', '')) !== false) {
    $rowNo++; $n++; $r = array_combine($hdr, $line); $e = check($r, $seen);
    if (!isset($seen[$r['sku']])) $seen[$r['sku']] = $rowNo;
    if (!$e) { fputcsv($ok, $line, ',', '"', ''); $valid++; continue; }
    foreach ($e as [$f, $msg]) { fputcsv($bad, [$rowNo, $r['sku'], $f, $r[$f], $msg], ',', '"', ''); $errs++; }
}
printf("Rows read: %d\nValid rows: %d\nRows with errors: %d\nErrors listed: %d\n", $n, $valid, $n - $valid, $errs);
exit($valid === $n ? 0 : 1);
