<?php

class Inventory extends Window
{
    public function get_vars()
    {
        $vars = parent::get_vars();
        $pageVars = getVal('body', $vars);

        if (findModule('products', 'note') && $this->getAction() != 'add') {
            $SQL = sqlQuery('SELECT p.id id_product, p.title product_title, pv.id id_variation, pv.title variation_title,
			COALESCE(pv.in_store, p.in_store)+(
				SELECT COALESCE(SUM(pieces), 0)
				FROM '.getTableName('order_items').' oi
				LEFT JOIN '.getTableName('orders').' o ON oi.id_order = o.id
				WHERE o.status=1 AND ((oi.id_variation = pv.id) OR (pv.id IS NULL AND oi.id_product = p.id))
			) AS in_store, COALESCE(pv.note, p.note) AS note
			 FROM '.getTableName('products').' p
	       LEFT JOIN '.getTableName('products_variations')." pv ON pv.id_product=p.id
	       WHERE pv.note RLIKE '{$pageVars['data']['name']}($|,| )' OR p.note RLIKE '{$pageVars['data']['name']}($|,| )'
	       ORDER BY in_store DESC");

            $pageVars['items'] = [];
            foreach ($SQL as $key => $row) {
                $pageVars['items'][$key] = $row;
                $pageVars['items'][$key] = leadImage($row['id_product'], 4);
            }
        }

        $pageVars['paid'] = ['0' => 'NE', '1' => 'ANO'];
        $vars['body'] = $pageVars;

        return $vars;
    }

    public function hasRights($name = null)
    {
        switch ($name) {
            case Window::RIGHT_DELETE:
            case Window::RIGHT_DUPLICATE:
                return false;
            case Window::RIGHT_SAVE:
                if (!findRight('ALL_RIGHTS') && getVal('body', parent::get_vars())['data']['finished'] == '1') {
                    return false;
                }
                // no break
            default:
                return parent::hasRights($name);
        }
    }
}

$inventory = new Inventory();
$inventory->run();
