<?php

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$res = [];


if(!empty($_FILES['csv'])) {
    $csv = $_FILES['csv']['tmp_name'];
    $headers = [];
    $warehouses = \App\Models\Inventory\Warehouse::all();

    $res = array_map(function($row) use(&$headers, $warehouses) {
        $arr = str_getcsv($row);

        if(empty($headers)) {
            $headers = $arr;

            return $headers;
        }

        $data = array_combine($headers, $arr);
        $quantities = $warehouses->reduce(function($r, $c) use($data) {
            if(isset($data[$c->code])) {
                $r[$c->code] = $data[$c->code];
            }

            return $r;
        }, []);
        $quantities['total'] = \App\Models\Inventory\Inventory::updateStock($data['EPOS CODE'], $quantities);

        return $quantities;
    }, file($csv));
}

echo json_encode($res);
die;
