<?php
namespace Controllers;
// Контроллер для клиетов
class Partners extends Controller {

	public function __construct() {
		parent::__construct();
		$this->model=new \Models\Partners($this->db, $this->f3);
	}

	// Страница поиска клиента
	function search() {
		$this->f3->set('page_data', $this->model->page_data('search'));
	}

	// Результат поиска
	function search_result() {
		$partners=array();
		$q=$this->f3->get('GET.q');
		if($q!='') {
			$page=$this->f3->get('GET.page');
			if(!$page) $page=1;
			$limit=$this->f3->get('lines_of_page');
			$option=array(
				'offset'=>($page-1)*$limit,
				'limit'=>$limit,
				'order'=>'lowername'
			);

			$phone_sql='OR phone LIKE ?';
			$inn_sql='OR inn LIKE ?';
			$lowername_sql='OR lowername LIKE ?';

			if($this->sets['clients_search']==1) {
				$val=array(
					'card'=>$q,
					'phone'=>$this->model->is_phone($q)?$this->model->validate_phone($q):$q,
					'inn'=>$q,
					'lowername'=>'%'.mb_strtolower($q).'%',
				);
			}
			else {
				$val=array(
					'card'=>'%'.$q.'%',
					'phone'=>$this->model->is_phone($q)?$this->model->validate_phone($q):'%'.$q.'%',
					'inn'=>'%'.$q.'%',
					'lowername'=>'%'.mb_strtolower($q).'%',
				);
			}

			$lenght=mb_strlen($q);
			if($lenght<4) {
				$phone_sql='';
				$inn_sql='';
				unset($val['phone'], $val['inn']);
				if($lenght<3) {
					$lowername_sql='';
					unset($val['lowername']);
				}
			}
			elseif(!is_numeric($q)) {
				$inn_sql='';
				unset($val['inn']);
			}

			$sql="(card LIKE ? ".$phone_sql.$inn_sql.$lowername_sql.") AND date_delete=0";

			$partners=$this->model->select_partner(array($sql, array_values($val)), $option);
		}

		if(empty($partners)) {
			$this->f3->set('value', $q);
			$this->f3->set('is_phone', $this->model->is_phone($q));
			$this->f3->set('page_data', $this->model->page_data('not_found'));
		}
		elseif(count($partners)==1) {
			$this->f3->reroute('/receipts/add_partner?partner_id='.$partners[0]['partner_id']);
		}
		else {
			$this->model->reset();
			$count=$this->model->count(array($sql, $q));
			$this->f3->set('pagination', $this->pagination($count, $page));
			$this->f3->set('partners', $partners);
			$this->f3->set('page_data', $this->model->page_data('search_result'));
		}
	}
}
