<?php
require_once __DIR__ . '/../../app/includes/auth.php';
require_once __DIR__ . '/../../app/includes/product_helpers.php';
require_auth(); require_role_access('*'); verify_csrf();

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

$new = 0; $updated = 0; $failed = 0; $errorRows = [];
$pdo = db();
$pdo->beginTransaction();
try {
    foreach ($rows as $row) {
        if (!empty($row['errors'])) {
            $failed++;
            $errorRows[] = $row;
            continue;
        }
        $d = $row['data'];
        $stmt = $pdo->prepare('SELECT id FROM products WHERE product_name=? AND brand=? AND model=? LIMIT 1');
        $stmt->execute([$d['product_name'], $d['brand'], $d['model']]);
        $id = $stmt->fetchColumn();
        if ($id) {
            $stmt = $pdo->prepare('UPDATE products SET product_category=?, description=?, unit=?, unit_price=?, status=?, updated_at=? WHERE id=?');
            $stmt->execute([$d['product_category'], $d['description'], $d['unit'], $d['unit_price'], $d['status'], now(), $id]);
            $updated++;
        } else {
            $stmt = $pdo->prepare('INSERT INTO products (product_category, product_name, description, brand, model, unit, unit_price, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
            $stmt->execute([$d['product_category'], $d['product_name'], $d['description'], $d['brand'], $d['model'], $d['unit'], $d['unit_price'], $d['status'], now(), now()]);
            $new++;
        }
    }
    $pdo->commit();
    log_activity('product_imported', 'Imported ' . count($rows) . ' products: ' . $new . ' new, ' . $updated . ' updated, ' . $failed . ' failed.');
    $_SESSION['product_import_errors'] = $errorRows;
    flash('success', 'Import completed. Total rows processed: ' . count($rows) . '. New products inserted: ' . $new . '. Existing products updated: ' . $updated . '. Failed rows: ' . $failed . '.');
} catch (Throwable $e) {
    $pdo->rollBack();
    flash('error', 'Import failed: ' . $e->getMessage());
}
if ($file && is_file($file)) { unlink($file); }
unset($_SESSION['product_import_file'], $_SESSION['product_import_preview']);
redirect('/products/index.php');
