<?php
$pageTitle = 'Import Preview';
require_once __DIR__ . '/../../app/includes/header.php'; require_admin();
require_once __DIR__ . '/../../app/includes/product_helpers.php';
require_role_access('*');

$file = $_SESSION['product_import_file'] ?? '';
if (!$file || !is_file($file)) {
    flash('error', 'No import file found.');
    redirect('/products/import.php');
}

$rows = [];
$errors = [];
$handle = fopen($file, 'r');
$header = $handle ? fgetcsv($handle) : false;
if (is_array($header) && isset($header[0])) {
    $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string)$header[0]);
}
if ($header !== PRODUCT_CSV_HEADER) {
    $errors[] = 'CSV header is invalid. Required header: ' . implode(',', PRODUCT_CSV_HEADER);
} else {
    $line = 1;
    while (($csv = fgetcsv($handle)) !== false) {
        $line++;
        if (count(array_filter($csv, fn($v) => trim((string)$v) !== '')) === 0) { continue; }
        $raw = array_combine(PRODUCT_CSV_HEADER, array_pad($csv, count(PRODUCT_CSV_HEADER), ''));
        [$data, $rowErrors] = validate_product_input($raw);
        $match = null;
        if (!$rowErrors) {
            $stmt = db()->prepare('SELECT id FROM products WHERE product_name=? AND brand=? AND model=? LIMIT 1');
            $stmt->execute([$data['product_name'], $data['brand'], $data['model']]);
            $match = $stmt->fetchColumn();
        }
        $rows[] = ['line' => $line, 'data' => $data ?? $raw, 'action' => $rowErrors ? 'Error' : ($match ? 'Update' : 'New'), 'errors' => $rowErrors];
    }
}
if ($handle) { fclose($handle); }
$_SESSION['product_import_preview'] = $rows;
?>
<div class="page-head"><div><h1>Import Preview</h1><p>Review rows before importing.</p></div></div>
<?php if ($errors): ?><div class="alert alert-danger"><?= e(implode(' ', $errors)) ?></div><?php endif; ?>
<div class="card app-card"><div class="table-responsive"><table class="table align-middle mb-0">
<thead><tr><th>Row</th><th>Product Category</th><th>Product Name</th><th>Brand</th><th>Model</th><th>Unit</th><th>Unit Price</th><th>Status</th><th>Import Action</th><th>Error</th></tr></thead><tbody>
<?php foreach ($rows as $row): $d = $row['data']; ?><tr><td><?= (int)$row['line'] ?></td><td><?= e($d['product_category'] ?? '') ?></td><td><?= e($d['product_name'] ?? '') ?></td><td><?= e($d['brand'] ?? '') ?></td><td><?= e($d['model'] ?? '') ?></td><td><?= e($d['unit'] ?? '') ?></td><td><?= e((string)($d['unit_price'] ?? '')) ?></td><td><?= e($d['status'] ?? '') ?></td><td><?= e($row['action']) ?></td><td><?= e(implode(' ', $row['errors'])) ?></td></tr><?php endforeach; ?>
<?php if (!$rows): ?><tr><td colspan="10" class="text-center text-muted py-4">No rows to import.</td></tr><?php endif; ?>
</tbody></table></div></div>
<form class="mt-4" method="post" action="<?= APP_BASE ?>/products/import-store.php">
    <?= csrf_field() ?>
    <button class="btn btn-primary" type="submit" <?= $errors || !$rows ? 'disabled' : '' ?>>Confirm Import</button>
    <a class="btn btn-outline-secondary" href="<?= APP_BASE ?>/products/import.php">Cancel</a>
</form>
<?php require_once __DIR__ . '/../../app/includes/footer.php'; ?>
