<?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'
			);
			$sql="(phone LIKE ? OR card LIKE ? OR inn LIKE ? OR lowername LIKE ?) AND date_delete=0";
			$val=array(
				$this->model->is_phone($q)?$this->model->validate_phone($q):'%'.$q.'%',
				'%'.$q.'%',
				'%'.$q.'%',
				'%'.mb_strtolower($q).'%',
			);
			$partners=$this->model->select_partner(array($sql, $val), $option);
		}

		if(empty($partners)) {
			$this->f3->set('value', $q);
			$this->f3->set('is_phone', $is_phone);
			$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'));
		}
	}
}
