<?php


namespace Mnv\Modules;

/**
 * Class Products
 * @package Mnv\Modules
 */
class Products
{

    public array $response = [];

    private $category_id;
    private $page;
    private $limit;

    public array $products = [];
    public array $category_ids = [];

    public function __construct($category_id, $page, $limit = 10)
    {
        global $SECTIONS;

        $this->category_id = $category_id;
        if (!empty($this->category_id) && !empty($SECTIONS[$this->category_id])) {
            $this->category_ids = array($this->category_id);
            if (!empty($SECTIONS[$this->category_id]['allChildren'])) {
                $this->category_ids = array_merge($this->category_ids, $SECTIONS[$this->category_id]['allChildren']);
            }

        }

        $this->page = $page;
        $this->limit = $limit;

    }

    public function all(): void
    {
        if (!empty($this->category_ids)) {
            connect()->in('sectionId', $this->category_ids);
        } else {
            connect()->where('sectionId', $this->category_id);
        }

        $this->products = connect('products')->select('productId, sectionId, title, url, summary')->where('status', 'V')
            ->orderBy('publishedOn DESC')->pagination($this->limit, $this->page)->getAll('array');
//        print_r(connect()->getQuery());
//        print_r($this->products);
        $this->products = prepareProducts($this->products, true, false, true, 'general');
        $this->products = collect($this->products)->map(function ($product) {
            $product['summary'] = $this->internoetics_string_strrpos(strip_tags($product['summary']));
            return $product;
        })->all();

    }

    /**
     * @param $string
     * @param int $length
     * @param string $trimmarker
     * @return string
     */
    private function internoetics_string_strrpos($string, $length = 137, $trimmarker = '...'): string
    {
        $len = strlen(trim($string));
        return ($len > $length) ? rtrim(substr($string, 0, strrpos(substr($string, 0, $length), ' '))) . $trimmarker : $string;
    }
}