<?php

use App\Models\Inventory\Inventory;
use App\Models\Inventory\Warehouse;
use Illuminate\Support\Facades\DB;
use Mtc\Shop\Category;
use Mtc\Shop\Item\Size;

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

init_request_values([
    'lowstock' => null,
    'catid' => null,
    'page' => null,
    'name' => null,
    'id' => null,
]);

$page_meta['title'] = 'Manage Stock';

if ($_REQUEST['action'] === 'update_stock') {
    if (!empty($_REQUEST['stock'])) {
        if (config('ecom.stock.advanced')) {
            foreach ($_REQUEST['stock'] as $sizes) {
                foreach($sizes as $sku => $quantities) {
                    Inventory::updateStock($sku, $quantities);
                }
            }
        } else {
            foreach ($_REQUEST['stock'] as $item_id => $item) {
                foreach ($item as $size_id => $stock) {
                    if (empty($size_id)) {
                        (new \Mtc\Shop\Item())->find($item_id)->update(['stock' => $stock]);
                    } else {
                        (new Size())->find($size_id)->update(['stock' => $stock]);
                    }
                }
            }
        }

    }

    header('location: manage.stock.php?' . http_build_query($_GET));
}

$items = \Mtc\Shop\Item::query()
    ->select([
        'items.id AS item_id',
        'items.name',
        'items.stock AS item_stock',
        'items_sizes.id AS size_id',
        'items_sizes.stock AS size_stock',
        'items_sizes.size',
        'items_sizes.quantity',
        'items_sizes.strength',
    ])
    ->addSelect(DB::raw('IF(`items_sizes`.`id`, `items_sizes`.`PLU`, `items`.`epos_code`) AS sku'))
    ->where('items.deleted', '=', '0')
    ->where('items.id', '>', '0')
    ->whereNotIn('items.product_type', ['prescription', 'private_prescription'])
    ->leftJoin('items_sizes', 'items.id', '=', 'items_sizes.item_id')
    ->orderBy('items.id');

$append = '';

if (!empty($_REQUEST['name'])) {
    $items = $items->selectRaw(
        'MATCH(items.name) AGAINST(? IN BOOLEAN MODE ) AS match_name',
        [
            str_replace('*', '', $_REQUEST['name'])
        ]
    );
    $items = $items->where(function($q): void {     
        $q->whereRaw(
            'MATCH(items.name) AGAINST(? IN BOOLEAN MODE )',
            [
                $_REQUEST['name']
            ]
        );
        $q->orWhere('items.epos_code', $_REQUEST['name']);
        $q->orWhere('items_sizes.PLU', $_REQUEST['name']);
    });
    $append.='&name=' . $_REQUEST['name'];
}


if ($_REQUEST['lowstock'] != '') {
    $items = $items->where(function($where): void {
        $where->where(function($where): void {
            $where->whereNotNull('items_sizes.id')
                ->where('items_sizes.stock', '<', '2');
        })->orWhere(function($where): void {
            $where->whereNull('items_sizes.id')
                ->where('items.stock', '<', '2');
        });
    });
    $append .= '&lowstock=' . $_REQUEST['lowstock'];
}


if (!empty($_REQUEST['catid'])) {
    $items->whereExists(function($query): void {
        $query->select('*')
            ->from('items_categories')
            ->where('cat_id', '=', $_REQUEST['catid'])
            ->whereRaw('items.id = items_categories.item_id');
    });
    $append.='&catid=' . $_REQUEST['catid'];
}

if (!empty($_REQUEST['product_type'])) {
    $items = $items->where('items.product_type', $_REQUEST['product_type']);
    $append.='&product_type=' . $_REQUEST['product_type'];
}

$totalnumrows = $items->count();

if ($_REQUEST['page'] == '') {
    $_REQUEST['page'] = 1;
}

$rowsPerPage = 100;
$pageNum = $_REQUEST['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$pagestoshow = 10;

$items = $items->take($rowsPerPage)->skip($offset)->get();


if (config('ecom.stock.advanced')) {
    $warehouses = Warehouse::query()
        ->orderBy('priority', 'ASC')
        ->get();
    $stock = Inventory::query()
        ->whereIn('sku', $items->pluck('sku'))
        ->get()
        ->mapWithKeys(function ($v) {
            return ["{$v->sku}-{$v->warehouse_code}" => $v->quantity];
        });
} else {

}

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end"><?= clean_page($page_meta['title']) ?></li>
</ul>

<h1>Manage Stock</h1>

<form action="manage.stock.php" method="get" class="style">
    <fieldset class="show">
        <h1><a class="show el">Search <i class="fa fa-caret-right"></i></a></h1>
        <div class="row">
            <p>Use * to match any character or sequence of characters in a search</p>
        </div>

        <div class="row">
            <label for="name">Name / EPOS Code</label>
            <input type="text" name="name" id="name" value="<?= clean_page($_REQUEST['name']) ?>">
        </div>
        <?php

        if (CATEGORIES_MAX > 0) {
        ?>
            <div class="row">
                <label for="catid">Category</label>
                <select name="catid" id="catid">
                    <option value="">All</option>
                    <?= Category::renderList([
                        'template' => 'option',
                        'show_subs' => true,
                        'selected' => (!empty($_REQUEST['catid']) ? $_REQUEST['catid'] : 0),
                    ]) ;?>
                </select>
            </div>
        <?php
        }
        ?>
        <div class="row">
            <label for="lowstock">Low Stock</label>
            <input type="checkbox" name="lowstock" id="lowstock" <?= (!empty($_REQUEST['lowstock'])) ? "checked" : ''; ?>>
        </div>

        <input type="hidden" name="action" value="search">

        <div class="row">
            <div class="search-button"><input type="submit" value="Search" class="BUTTON"/></div>
        </div>

    </fieldset>

</form>

<?php
if ($totalnumrows > 0) {
    require $path . 'core/admin/templates/pagination.php';
    ?>
    <form method="post">
        <p>
            <input type="submit" value="Update Stock"/>
            <a href="export.stock.php" class="btn btn-secondary">Export CSV</a>
            <button type="button" class="btn btn-secondary" id="btnUploadStockCSV">Upload CSV</button>
        </p>
        <table class="manage-items">
            <tr>
                <th>Product ID</th>
                <th>SKU</th>
                <th>Product Name</th>
                <th>Size</th>
                <th>Quantity</th>
                <th>Strength</th>
                <th>Stock</th>
            </tr>
            <tbody class="tabular">
            <?php
            foreach ($items as $item) {
                ?>
                <tr>
                    <td><?= clean_page($item->item_id);?></td>
                    <td><?= clean_page($item->sku);?></</td>
                    <td><?= clean_page($item->name);?></td>
                    <td><?= clean_page($item->size);?></td>
                    <td><?= clean_page($item->strength);?></td>
                    <td><?= clean_page($item->quantity);?></td>
                    <td>
                        <?php

                    if (config('ecom.stock.advanced')) {
                        ?>
                        <?php foreach($warehouses as $warehouse) { ?>
                        <div>
                            <label>
                                <span><?= $warehouse->code ?></span>
                                <input type="number" name="stock[<?= $item->item_id ?>][<?= $item->sku ?>][<?= $warehouse->code ?>]" value="<?= $stock->get("{$item->sku}-{$warehouse->code}") ?>">
                            </label>
                        </div>
                        <?php } ?>
                    <?php
                    } else {
                    ?>
                        <input type="text"
                               name="stock[<?=$item->item_id; ?>][<?= (int)$item->size_id; ?>]"
                               value="<?= !empty($item->size_id) ? $item->size_stock : $item->item_stock; ?>"
                               style="width:100px;"
                        />
                <?php
                    }
                ?>
                    </td>
                </tr>
                <?php
            }
            ?>
            </tbody>
        </table>
        <p>
            <input type="hidden" name="action" value="update_stock"/>
            <input type="submit" value="Update Stock"/>
        </p>
    </form>
    <?php
        require $path . 'core/admin/templates/pagination.php';
} else {
?>
    <p>There were no products found matching your search criteria</p>
<?php
}

require_once $path . 'core/admin/templates/adminfooter.html.php';
