<?php

use App\Models\Inventory\Inventory;
use App\Models\Inventory\Warehouse;

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

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="stock.csv";');

$warehouses = Warehouse::query()
    ->orderBy('priority', 'ASC')
    ->get();
$rows = Inventory::query()
    ->where(function($q) {
        return $q->whereHas('item', function($q) {
            return $q->where('hidden', 0)
                ->where('deleted', 0);
        })
            ->orWhereHas('size', function($q) {
                return $q->where('hide', 0);
            });
    })
    ->orderBy('sku', 'DESC')
    ->get()
    ->groupBy('sku');
$fp = fopen('php://output', 'w');

fputcsv($fp, $warehouses->map(function($v) {
    return $v->code;
})->prepend('EPOS CODE')->toArray());

$rows->each(function($v, $sku) use($fp, $warehouses) {
    fputcsv($fp, $warehouses
        ->map(function($w) use($v) {
            return collect($v)->where('warehouse_code', $w->code)->value('quantity');
        })
        ->prepend($sku)
        ->toArray()
    );
});

fclose($fp);
die;
