<?php

use Mtc\Shop\Brand;
use Mtc\Shop\Item\Image;


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

$page_meta["title"] = "Product Selection";

require_once $path . 'core/admin/templates/adminheader.full.php';

init_request_values([
    'catid' => null,
    'brandid' => null,
    'name' => null,
    'sku' => null,
    'page' => null,
]);

?>

<script>
    $(window).bind('beforeunload', function() {
        var inputEl = window.opener.document.getElementById('<?= clean_page($_REQUEST['field']) ?>');
        inputEl.onchange();
    });
</script>

<form action="manage.products.mini.php" method="POST" class="style el miniselector">

<fieldset<?php if ($_REQUEST['action']=='search') {?> class="show"<?php } ?>>
    <h1><a href="#" class="show el">Filter Results</a></h1>

    <div class="row">
        <label for="catid">Category</label>
        <select name="catid">
        <option value="">All</option>
        <?php
        echo get_the_categories($_REQUEST['catid']);
        ?>
        </select>
    </div>

    <?php
    if (BRANDS_ENABLED) { ?>
        <div class="row">
            <label for="">Brand</label>
                            <select name="brandid">
                        <option value="">All</option>
                        <?php
                        $brands = Brand::query()
                            ->orderBy('name')
                            ->get();
                        foreach ($brands as $brand) {
                            $data = $brand->toArray();
                            if ($_REQUEST['brandid']==$data["id"]) {
                                ?>
                                <option value="<?php echo $data['id'];?>" selected><?php echo clean_page($data['name']);?></option>
                                <?php

                            } else {
                                ?>
                                <option value="<?php echo $data['id'];?>"><?php echo clean_page($data['name']);?></option>
                                <?php
                            }
                        }
                        ?>
                    </select>

        </div>
        <?php
    } ?>

    <div class="row">
        <label for="name">Name</label>
        <input type="text" name="name" value="<?= $_REQUEST['name'];?>"/>
   </div>

    <?php
    if (ITEMS_CODE) { ?>
        <div class="row">
            <label for="SKU">EPOS Code</label>
            <input type="text" name="sku" value="<?= $_REQUEST['sku'];?>"/>
       </div>
       <?php
    } ?>

    <div class="row">
        <input type="hidden" name="action" value="search">
        <input type="hidden" name="field" value="<?php echo $_REQUEST['field'];?>">
        <label for="">&nbsp;</label><input type="submit" value="Search" class="BUTTON">
    </div>

</fieldset>

</form>

<?php

$append = http_build_query($_REQUEST);

$query = \Mtc\Shop\Item::query()
    ->distinct()
    ->select('items.id', 'items.name', 'items.epos_code as sku')
    ->leftJoin('items_brands', 'items.id', '=', 'items_brands.item_id')
    ->leftJoin('items_categories', 'items.id', '=', 'items_categories.item_id')
    ->where('items.deleted', 0)
    ->whereNotIn('items.product_type', [
        \Mtc\Shop\Item::TYPE_PRIVATE_PRESCRIPTION,
        \Mtc\Shop\Item::TYPE_PRESCRIPTION,
        \Mtc\Shop\Item::TYPE_CONSULTATION,
    ])
    ->when(!empty($_REQUEST['brandid']), function ($query) {
        $query->where('items_brands.brand_id', '=', $_REQUEST['brandid']);
    })
    ->when(!empty($_REQUEST['catid']), function ($query) {
        $query->where('items_categories.cat_id', '=', $_REQUEST['catid']);
    })
    ->when(!empty($_REQUEST['sku']), function ($query) {
        $query->where('items.epos_code', 'like', '%'.$_REQUEST['sku'].'%');
    })
    ->when(!empty($_REQUEST['name']), function ($query) {
        $query->where('items.name', 'like', '%'.$_REQUEST['name'].'%');
    });


$totalnumrows = $query->count();

if ($_REQUEST['page']=='') {
    $_REQUEST['page'] = 1;
}
$rowsPerPage = 25;
$pageNum = $_REQUEST['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$pagestoshow = 5;
$items = $query->orderBy('items.name')
    ->skip($offset)
    ->limit($rowsPerPage)
    ->get();

if ($items->count() > 0) {
    ?>

    <h3 class="headlinemini el">Results</h3>

    <table class="manage-items tabular">
        <tr class="row_heading">
            <?php
            if (ITEMS_CODE) { ?>
                 <th>Epos Code</th>
                 <?php
            } ?>
            <th>Image</th>
            <th>Name</th>
            <th class="center">Use</th>
        </tr>
        <?php
        $row = false;
        foreach ($items as $item) {
            $data = $item->toArray();
            $row = !$row;
            ?>
            <tr class="row<?= $row ?>"
                onclick="opener.document.getElementById('<?= clean_page($_REQUEST['field']) ?>').value='<?= $data["id"] ?>';
                    if (opener.document.getElementById('<?= clean_page($_REQUEST['field']) ?>_name') != null) {
                        opener.document.getElementById('<?= clean_page($_REQUEST['field']) ?>_name').value='<?= clean_page(addslashes(item_name($data["id"]))) ?>';
                    }
                    opener.document
                        .getElementById('<?= clean_page($_REQUEST['field']) ?>')
                        .dispatchEvent(new Event('change'));
                    window.close();"
                style="cursor:pointer;">

                <?php
                if (ITEMS_CODE) { ?>
                    <td><?= $data['sku'] ?></td>
                    <?php
                } ?>
                <td align="center">
                    <?php
                    if (get_default_image($data['id']) != '') {
                        ?>
                        <img src="/<?= $image_folders['product_folders']['mini']['path'] ?>/<?= get_default_image($data['id']) ?>"/>
                        <?php
                    } elseif (!empty($data['epos_image'])) {
                        ?>
                        <img src="<?= $data['epos_image'] ?>" style="width:35px;"/>
                        <?php
                    }
                    ?>
                </td>
                <td><?= clean_page($data['name']) ?></td>
                <td class="center"><i class="fa fa-plus-circle"></i></td>
            </tr>
            <?php
        }
        ?>
    </table>
    <?php
} else {
    ?>
    <div class="el">
        <h3>No products found</h3>
        <p>There were no products found matching your search criteria</p>
    </div>
    <?php
}

include $path . 'core/admin/templates/pagination.php';
require_once $path . 'core/admin/templates/adminfooter.full.php';

function get_default_image($item_id)
{
    $image = Image::query()
        ->where('item_id', '=', $item_id)
        ->where('default', '=', 1)
        ->first();

    if (empty($image)) {
        return null;
    }
    return $image->name;
}
