<?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'=>'phone'
		);
		$is_phone=$this->model->is_phone($q);
		if($is_phone) {
			$sql="phone=? AND date_delete=0";
			$q=$this->model->validate_phone($q);
			$partners=$this->model->select_partner(array($sql, $q), $option);
			//var_dump($partners);
		}

		if(empty($partners)) {
			$sql="card=? AND date_delete=0";
			$option['order']='card';
			$partners=$this->model->select_partner(array($sql, $q), $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'));
		}
	}
}
