<?php

class PaymentController extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
	}


	public function storePaymentAggregator(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$id = $_POST['id'] ?? null ;

				$exist = $this->db->get_where('payment_aggregators', ['id !=' => $id , 'name' => $_POST['name']]);
				if ($exist->num_rows() == 0) {
					foreach ($_POST as $key => $value){
						if(empty($value)){
							$_POST[$key] = null;
						}
					}
					$_POST['created_at'] = (new DateTime())->format('Y-m-d H:i:s');
					$_POST['updated_at'] = (new DateTime())->format('Y-m-d H:i:s');
					if(!empty($id)){
						$rates = $_POST['rates'] ?? [] ;
						unset($_POST['rates']);
						$this->db->where('id',$id);
						$this->db->update('payment_aggregators',$_POST);
						$this->db->delete('payment_aggregator_rates',['aggregator_id' => $id]);
						if(sizeof($rates) > 0){
							$data = array_map(function ($rate) use($id){
								$row = [];
								$row['country'] = $rate[0];
								$row['type'] = $rate[1];
								$row['method'] = $rate[2];
								$row['channel'] = $rate[3];
								$row['rate'] = $rate[4];
								$row['fixed_fees'] = $rate[5];
								$row['fixed_fees_currency'] = $rate[6];
								$row['aggregator_id'] = $id;
								$row['created_at'] = (new DateTime())->format('Y-m-d H:i:s');
								$row['updated_at'] = (new DateTime())->format('Y-m-d H:i:s');
								return $row;
							},$rates);
							$this->db->insert_batch('payment_aggregator_rates',$data);
						}
					}else{
						$this->db->insert('payment_aggregators',$_POST);
					}
					echo json_encode(['code' => 200]);

				}else{
					echo json_encode(['code'=> 419 , 'message' => $this->lang->line("name_already_used")]);
				}
			}
		}
	}

	public function deletePaymentAggregator(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$this->db->delete('payment_aggregators', ['id' => $_POST['id']]);
				$this->db->delete('payment_aggregator_rates', ['aggregator_id' => $_POST['id']]);
				echo json_encode(['code' => 200]);
			}
		}
	}

	public function enableAggregator()
	{
		if($this->isLogged()) {
			if (isset($_POST)) {
				$date = (new DateTime())->format('Y-m-d H:i:s');
				$this->db->update('payment_aggregators',['status' => 0 , 'updated_at' => $date]);
				$this->db->where('id',$_POST['id']);
				$this->db->update('payment_aggregators',['status' => 1 , 'updated_at' => $date]);
				echo json_encode(['code' => 200]);
			}
		}
	}




	public function isLogged()
	{
		if (!$this->session->userdata('email')) {
			$this->session->set_flashdata('error', 'log in first');

			$data['alert'] = "ok";
			$data['message'] = "Login first!";
			$this->load->view('login', $data);
			return false;
		}
		return true;
	}

}
