<?php

namespace MGModule\DNSManager2\mgLibs\custom;

class RepoTableHelper {
    /**
     * @var repository 
     */
    private $repository;
    private $items_per_page = 10;
    private $page = 1;
    private $count_all;
    private $count_filtered;
    private $pages_count;
    private $filters = array();
    
    /**
     * Klasa ta pomaga generować output dla DataTable używając repozytorium
     * @param \MGModule\DNSManager2\mgLibs\models\repository $repository
     * @param array $input
     * @param array $search_columns kolumny, na których wykonywany będzie search
     */
    public function __construct(\MGModule\DNSManager2\mgLibs\models\repository $repository, $input, $search_columns = false) {
        $count_all = $repository->count();
        $items_per_page = $input['limit']?:$this->items_per_page;
        $page = floor($input['offset']/$items_per_page);
        
        if($input['search'])
        {
            $repository->search($input['search'], $search_columns);
            $this->search = $input['search'];
        }

        foreach($input['filter'] as $column => $value)
        {   
            if(!empty($value))
            {
                $repository->setFilter($column, $value);
                $this->filters[$column] = $value;
            }
        }

        // foreach ($input['table_sorts'] as $column => $vector) {
        if(isset($input['order']['column'])) {
            $repository->sortBy($input['order']['column'], $input['order']['dir']);
        }
       // }

        $repoClone = clone $repository;
        $count_filtered = $repoClone->count();

        $pages_count = floor($count_filtered/$items_per_page) + 1;
        if($page > $pages_count) 
        {
            $page = $pages_count;
        }
        
        $repository->offset($input['offset']);//($page - 1) * $items_per_page);
        $repository->limit($items_per_page);
        
        $this->repository = $repository;

        $this->page = $page;
        $this->count_all = $count_all;
        $this->count_filtered = $count_filtered;
        $this->items_per_page = $items_per_page;
        $this->pages_count = $pages_count;
    }
    
    public function get() {
        return $this->repository->get();
    }
    
    public function getDataTableArray() {
        $out = array();
        $out['recordsTotal'] = $this->count_all;
        $out['recordsFiltered'] = $this->count_filtered;
        $out['data'] = array();
        return $out;
    }
    
}