<?php

/**
 * Vvveb
 *
 * Copyright (C) 2020  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Vvveb\Controller\Product;

use Vvveb\Controller\Base as Base;
use Vvveb\System\Images as Images;
use Vvveb\System\View as View;

class Products extends Base {
	function index() {
		$view     = View :: getInstance();
		$products = new \Vvveb\Sql\ProductsSQL();

		$page    = $_GET['page'] ?? 1;
		$perpage = 10;

		$results = $products->getProducts(
			['start'       => ($page - 1) * $perpage,
				'limit'       => $perpage,
				'language_id' => 1,
				'store_id'    => 0,
				//'include_manufacturer' => true,
				'include_discount'     => true,
				'include_special'      => true,
				'include_reward'       => true,
				'include_manufacturer' => true,
				//'include_stock_status' => true,
			]
		);

		foreach ($results['products'] as $id => &$product) {
			if (isset($product['images'])) {
				$product['images'] = json_decode($product['images'], 1);

				foreach ($product['images'] as &$image) {
					$image = Images::image('product', $image);
				}
				//	var_dump($product['images']);
			} else {
				if (isset($product['image'])) {
					$product['image'] = Images::image('product', $product['image']);
				}
			}
		}

		$view->products = $results['products'];
		$view->count    = $results['count'];
		$view->perpage  = $perpage;

		//$results['count'] = $products->count();
		//$view->count = 10;
		//$view->perpage = $products->perpage;
	}
}
