<?php
namespace Models;

// Модель Программ лояльности
class Loyalty extends \DB\SQL\Mapper {
	public $db, $f3;

	public function __construct($db, $f3) {
		parent::__construct($db, 'loyalty' ); // подключаемся к таблице
		$this->db=$db;
		$this->f3=$f3;
	}

	// Выбор из базы
	function select_loyalty($query=null, $options=null) {
		$this->reset();
		$this->load($query, $options);
		$loyalty=array();
		if(!$this->dry()) {
			do {
				$loyalty[]=$this->cast();
			}
			while ($this->skip());
		}
		return $loyalty;
	}

	// Подбор программмы лояльности для добавленного товара
	function get_loyalty($client, $product, $certificates=array()) {
		$now=time(); // Время сейчас
		$w=date('w'); // Номер дня недели
		$h=sprintf("%'.02d", date('H')); // Час
		if($w==0)$w=7;
		$sql="SELECT * FROM `loyalty` WHERE `date_start`<=? AND `date_end`>=?";
		$val=array(
			$now,
			$now-3600*24
		);
		$loyalty=$this->db->exec($sql, $val);
		$result=array();
		$product_certificate=array_column($certificates, 'product_id');
		if($loyalty) {
			$group_id=(string)$client['group_id']??'0';
			
			foreach ($loyalty as $n => $l) {
				$ok=false;
				$groups=json_decode($l['partnergroup'], true);
				$l_certificates=json_decode($l['certificates'], true);
				$hours=json_decode($l['d'.$w], true);
				$data=json_decode($l['data'], true);
				$client_groups=array('0', $group_id);
				if(!empty($product_certificate) && $l_certificates && array_intersect($l_certificates, $product_certificate)) {
					$client_groups[]='certificates';
				}

				// Лояльность подходит если
				if((!$groups || array_intersect($client_groups, $groups)) && (int)$hours[$h]==1) {
					if($l['action_type']>0) {
						if(isset($data['product'][$product['id']]) || isset($data['category'][$product['category_id']])) {
							$ok=true;
						}
					}
					elseif($l['action_type']<0) {
						if(!isset($data['product'][$product['id']]) && !isset($data['category'][$product['category_id']])) {
							$ok=true;
						}
					}

					if($ok===true) {
						$l['items']=$data;
						$result[$l['id']]=$l;
					}
				}
			}
		}
		return $result;
	}

	// Список скидок
	function select_discounts($discount=false) {
		$where='';
		$val=array();
		if($discount!==false) {
			$where='WHERE value=?';
			$val[]=$discount;
		}
		return $this->db->exec("SELECT * FROM discounts ".$where." ORDER BY value", $val);
	}

	function get_auto_add_loyalty($receipt) {
		$loyalty=array();
		$now=time();
		$w=date('w'); // Номер дня недели
		$h=sprintf("%'.02d", date('H')); // Час
		if($w==0)$w=7;
		$this->load(array("data like '%\"quantity_type\":\"add\"%' AND date_start<=? AND date_end>=?", array($now, $now-3600*24)));
		if($this->dry()) return $loyalty;
		$product_certificate=array_column($receipt['certificates'], 'product_id');
		$group_id=0;
		if($receipt['partner_id']>0) {
			$partner=$this->db->exec("SELECT group_id FROM partners WHERE partner_id=? LIMIT 1", $receipt['partner_id']);
			if($partner) {
				$group_id=$partner[0]['group_id'];
			}
		}
		do {
			$l=$this->cast();
			$groups=json_decode($l['partnergroup'], true);
			$l_certificates=json_decode($l['certificates'], true);
			$hours=json_decode($l['d'.$w], true);
			$data=json_decode($l['data'], true);
			$client_groups=array($group_id);
			if(!empty($product_certificate) && array_intersect($l_certificates, $product_certificate)) {
				$client_groups[]='certificates';
			}
			if((!$groups || array_intersect($client_groups, $groups)) && (int)$hours[$h]==1) {
				$loyalty[$l['id']]=$l;
			}
		}
		while($this->skip());
		return $loyalty;
	}

	function get_receipt_sum_loyalty($receipt) {
		$loyalty=array();
		$now=time();
		$w=date('w'); // Номер дня недели
		$h=sprintf("%'.02d", date('H')); // Час
		if($w==0)$w=7;
		$this->load(array("data like '%\"quantity_type\":\"receiptsumm\"%' AND date_start<=? AND date_end>=?", array($now, $now-3600*24)));
		if($this->dry()) return $loyalty;
		$product_certificate=array_column($receipt['certificates'], 'product_id');

		$partner_data=json_decode($receipt['other_data'], true);
		if(is_array($partner_data) && isset($partner_data['partner'])) {
			$group_id=$partner_data['partner']['group_id'];
		}
		else {
			$group_id=1; // Розничный покупатель
		}

		do {
			$l=$this->cast();
			$groups=json_decode($l['partnergroup'], true);
			$l_certificates=json_decode($l['certificates'], true);
			$hours=json_decode($l['d'.$w], true);
			$data=json_decode($l['data'], true);
			$client_groups=array($group_id);
			if(!empty($product_certificate) && array_intersect($l_certificates, $product_certificate)) {
				$client_groups[]='certificates';
			}
			if((!$groups || array_intersect($client_groups, $groups)) && (int)$hours[$h]==1 && $receipt['sum']>$l['quantity']) {
				$loyalty[$l['id']]=$l;
			}
		}
		while($this->skip());
		return $loyalty;
	}
}
