<?php

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

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

$page_meta['title'] = 'Brand Selector';

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

if (empty($append)) {
    $append = '';
}

$query = Brand::query();

$totalnumrows = $query->count();

if ($_GET['page']=='') {
    $_GET['page'] = 1;
}
$rowsPerPage = 25;
$pageNum = $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$pagestoshow = 10;

$brands = $query->orderBy('order')
    ->skip($offset)
    ->limit($rowsPerPage)
    ->get();

$append .= '&field='.$_REQUEST['field'];
if ($brands->count() > 0) {
    ?>
    <h2>Brand Selection</h2>
    <table class="manage-items tabular">
        <tr>
            <th>ID</th>
            <th>Brand</th>
            <th>Use</th>
        </tr>
        <?php
        $row = false;
        foreach ($brands as $brand) {
            $data = $brand->toArray();
            $row = !$row;
            ?>
            <tr class="row<?= $row;?>" onclick="javascript:opener.document.getElementById('<?= $_REQUEST['field'];?>').value='<?=$data["id"];?>';opener.document.getElementById('<?= $_REQUEST['field'];?>_name').value='<?=addslashes($data["name"]);?>';window.close();" style="cursor:pointer;">
                <td><?= $data['id'];?></td>
                <td><?= $data['name'];?></td>
                <td><i class="fa fa-plus-circle"></i></td>
            </tr>
            <?php
        }
        ?>
    </table>
    <?php
} else {
    ?>
    <p>There were no brands found matching your search criteria</p>
    <?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;
}
