<?php

$main_class = 'posStore';

class PosStore extends Window
{
    use DatabaseCommunication;

    protected $template = 'window/pos.store.tpl';
    private $err_str;

    public function get_vars()
    {
        $vars = parent::get_vars();

        $id_product = getVal('id_product');

        $ean = intval(getVal('ean'));
        if (empty($id_product) && !empty($ean)) {
            $fields = 'p.title as label, p.id as id_product, pv.id as id_variation, p.id as id_product';
            $from = getTableName('products').' p LEFT JOIN '.getTableName('products_variations').' pv ON pv.id_product=p.id ';
            $where = " p.figure='Y' AND
                     (
                     p.code LIKE '%{$ean}%'
                     OR p.ean LIKE '{$ean}' OR pv.ean LIKE '{$ean}'
                     )";

            if (!empty($cfg['Modules']['products_variations']['variationCode'])) {
                $where .= " OR pv.code LIKE '%{$ean}%' ";
            }
            $SQL = sqlQuery("SELECT {$fields}
						FROM {$from}
						WHERE {$where} LIMIT 1");

            if (sqlNumRows($SQL) == 0) {
                $this->err_str = 'Tento EAN není přiřazen k žádnému produktu';
            } elseif (sqlNumRows($SQL) > 1) {
                $this->err_str = 'Existuje více produktů s tímto EAN, vložte ručně';
            } else {
                $row = sqlFetchArray($SQL);
                $id_product = $row['id_product'];
            }
        }

        if (!empty($id_product)) {
            if (findModule('products_variations')) {
                $select = '';

                if (findModule(Modules::PRODUCTS, Modules::SUB_NOTE)) {
                    $select .= ', COALESCE(pv.note, p.note)';
                }

                $SQL = sqlQuery("SELECT pv.*, COALESCE(pv.price, p.price) as price_real {$select}, p.id as id_product
						FROM products_variations AS pv
		            LEFT JOIN products p ON pv.id_product=p.id
						WHERE id_product={$id_product}
						GROUP BY pv.id");
                $vars['products'] = [];
                foreach ($SQL as $row) {
                    $row['piecesOrdered'] = returnSQLResult('SELECT SUM(oi.pieces)
                  FROM '.getTableName('order_items').' oi
                  LEFT JOIN '.getTableName('orders')." o ON oi.id_order=o.id
		         WHERE oi.id_product={$id_product} AND oi.id_variation={$row['id']} AND
		         o.status_storno=0 AND o.status IN
		         (".join(',', getStatuses('notpacked')).')');

                    $row['class'] = 'row-green';

                    if ($row['in_store'] < 0) {
                        if ($row['id_product']) {
                            // Suppliers products
                            if (findModule('products_suppliers')) {
                                $query = 'SELECT SUM(in_store)
										FROM '.getTableName('products_of_suppliers')." pos
										WHERE pos.id_product={$row['id_product']} AND pos.id_variation={$row['id']}";

                                $row['piecesInSuppliers'] = returnSQLResult($query);
                            }
                        }

                        if ($row['in_store'] + $row['piecesOrdered'] < 0) {
                            $row['class'] = 'row-red';
                            if (findModule('products_suppliers')) {
                                if ($row['in_store'] + $row['piecesOrdered'] + $row['piecesInSuppliers'] > 0) {
                                    $row['class'] = 'row-orange';
                                }
                            }
                        }
                    }
                    $row['id_variation'] = $row['id'];
                    $vars['products'][] = $row;
                }
            }
            if (!findModule('products_variations') || empty($vars['products'])) {
                $SQL = $this->selectSQL('products', ['id' => $id_product]);
                $vars['products'] = [];
                foreach ($SQL as $row) {
                    $row['id_variation'] = '';
                    $row['id_product'] = $row['id'];

                    $row['piecesOrdered'] = returnSQLResult('SELECT SUM(oi.pieces)
                  FROM '.getTableName('order_items').' oi
                  LEFT JOIN '.getTableName('orders')." o ON oi.id_order=o.id
		         WHERE oi.id_product={$id_product} AND oi.id_variation={$row['id']} AND
		         o.status_storno=0 AND o.status IN
		         (".join(',', getStatuses('notpacked')).')');

                    $row['class'] = 'row-green';

                    if ($row['in_store'] < 0) {
                        if ($row['id_product']) {
                            // Suppliers products
                            if (findModule('products_suppliers')) {
                                $query = 'SELECT SUM(in_store)
										FROM '.getTableName('products_of_suppliers')." pos
										WHERE pos.id_product={$row['id_product']} AND pos.id_variation={$row['id']}";

                                $row['piecesInSuppliers'] = returnSQLResult($query);
                            }
                        }

                        if ($row['in_store'] + $row['piecesOrdered'] < 0) {
                            $row['class'] = 'row-red';
                            if (findModule('products_suppliers')) {
                                if ($row['in_store'] + $row['piecesOrdered'] + $row['piecesInSuppliers'] > 0) {
                                    $row['class'] = 'row-orange';
                                }
                            }
                        }
                    }

                    $vars['products'][] = $row;
                }
            }
        }
        if (empty($this->err_str)) {
            if (empty($vars['products'])) {
                $this->err_str = 'Produkt neexistuje';
            } else {
                $this->err_str = 'Načteno';
            }
        }
        $vars['err_str'] = $this->err_str;

        return $vars;
    }
}
