<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../includes/auth.php';
requireLogin();
requirePermission('view_inventory');

require_once __DIR__ . '/../../config/database.php';

$company_id = $_SESSION['company_id'] ?? 0;

if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){

    $file = fopen($_FILES['csv_file']['tmp_name'], 'r');
    $header = fgetcsv($file);

    while(($row = fgetcsv($file)) !== FALSE){

        $category_name     = trim($row[0] ?? '');
        $item_type         = strtoupper(trim($row[1] ?? 'PRODUCT'));
        $product_name      = trim($row[2] ?? '');
        $brand             = trim($row[3] ?? '');
        $model             = trim($row[4] ?? '');
        $sku               = trim($row[5] ?? '');
        $cost              = (float)($row[6] ?? 0);
        $sell              = (float)($row[7] ?? 0);
        $desc              = trim($row[8] ?? '');
        $track_inventory   = (int)($row[9] ?? 0);
        $stock_qty         = (int)($row[10] ?? 0);

        if($product_name === ''){
            continue;
        }

        $stmt = $pdo->prepare("
        SELECT id
        FROM inventory_categories
        WHERE company_id = ?
        AND category_name = ?
        ");
        $stmt->execute([$company_id,$category_name]);
        $cat = $stmt->fetch(PDO::FETCH_ASSOC);

        if(!$cat){
            continue;
        }

        $category_id = $cat['id'];

        $stmt = $pdo->prepare("
        INSERT INTO inventory_products
        (
            company_id,
            category_id,
            item_type,
            product_name,
            brand,
            model,
            sku,
            description,
            cost_price,
            selling_price,
            track_inventory,
            stock_qty,
            status
        )
        VALUES
        (?,?,?,?,?,?,?,?,?,?,?,?, 'active')
        ");

        $stmt->execute([
            $company_id,
            $category_id,
            $item_type,
            $product_name,
            $brand,
            $model,
            $sku,
            $desc,
            $cost,
            $sell,
            $track_inventory,
            $stock_qty
        ]);
    }

    fclose($file);
}

header("Location: index.php");
exit;