<?php
$_POST['import_items'] = true;
$_FILES['excel_file'] = [
    'name' => 'test_import.csv',
    'type' => 'text/csv',
    'tmp_name' => __DIR__ . '/test_import.csv',
    'error' => 0,
    'size' => filesize(__DIR__ . '/test_import.csv')
];

// Define db() helper if not defined (it should be in db/config.php)
require_once __DIR__ . '/db/config.php';

// Include the logic from index.php
// I'll copy the logic here to avoid including the whole index.php which might have side effects
$tmpPath = $_FILES['excel_file']['tmp_name'];
$handle = fopen($tmpPath, "r");
$firstRow = fgetcsv($handle, 0, ","); // Skip header
$count = 0; $errors = 0;
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
    if (count($data) < 2) continue;
    try {
        $sku = substr(trim($data[0] ?? ''), 0, 100);
        $name_en = $data[1] ?? '';
        $name_ar = $data[2] ?? '';
        $sale_price = str_replace(',', '', $data[3] ?? 0);
        $purchase_price = str_replace(',', '', $data[4] ?? 0);

        if (empty($sku) && empty($name_en)) continue;

        $stmt = db()->prepare("INSERT INTO stock_items (sku, name_en, name_ar, sale_price, purchase_price) 
                      VALUES (?, ?, ?, ?, ?) 
                      ON DUPLICATE KEY UPDATE name_en=VALUES(name_en), name_ar=VALUES(name_ar), 
                      sale_price=VALUES(sale_price), purchase_price=VALUES(purchase_price)");
        $stmt->execute([$sku, $name_en, $name_ar, (float)$sale_price, (float)$purchase_price]);
        echo "Imported: $sku\n";
        $count++;
    } catch (Throwable $e) {
        echo "Error: " . $e->getMessage() . "\n";
        $errors++;
    }
}
fclose($handle);
echo "Finished. Success: $count, Errors: $errors\n";
