<?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() {
		$q=$this->f3->get('GET.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'=>'card'
		);

		$sql="card=?";
		$partners=$this->model->select_partner(array($sql, $q), $option);
		if(empty($partners)) {
			$sql="phone=?";
			$q=$this->model->validate_phone($q);
			$option['order']='phone';
			$partners=$this->model->select_partner(array($sql, $q), $option);
		}

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