<?php

namespace App\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

use CodeIgniter\RESTful\ResourceController;

class BaseController extends ResourceController
{

	/**
	 * An array of helpers to be loaded automatically upon
	 * class instantiation. These helpers will be available
	 * to all other controllers that extend BaseController.
	 *
	 * @var array
	 */
	protected $helpers = [];

	/**
	 * Constructor.
	 */
	public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
	{
		// Do Not Edit This Line
		parent::initController($request, $response, $logger);

		//--------------------------------------------------------------------
		// Preload any models, libraries, etc, here.
		//--------------------------------------------------------------------
		// E.g.:
		// $this->session = \Config\Services::session();
	}

	/**
	 * Returns array with a key name changed
	 *
	 * @param array $row_list
	 * @param string $oldKey
	 * @param string $newKey
	 */
	protected function renameKey($row_list, $oldKey, $newKey)
	{
		$json = str_replace('"' . $oldKey . '":', '"' . $newKey . '":', json_encode($row_list));
		return json_decode($json, true);
	}


	/**
	 * Returns array list of all rows in model table,
	 * $rename is an array of $oldKey=>$newKey. Param $where to use an optional where condition.
	 * @param array $rename
	 * @param array|null $where
	 */
	public function getAllRows($rename, $where = null, $where_or = null)
	{

		$rows_list = $this->model->getAllRows($where, $where_or);

		if (empty($rows_list)) {
			$rows_list = [];
		} else {
			if ($rename != []) {
				foreach ($rename as $oldkey => $newKey) {
					//do something with your $key and $value;
					$rows_list = $this->renameKey($rows_list, $oldkey, $newKey);
				}
			}
		}

		return $rows_list;
	}

	/**
	 * Returns array list of all rows in model table given a join condition with another table,
	 * $rename is an array of $oldKey=>$newKey. Param $where to use an optional where condition.
	 * @param array $rename
	 * @param array|string|null $where
	 * @param array|string|null $where_or
	 * @param array|string|null $join_condition
	 * @param string|null $join_table
	 * @param string $join_type
	 *
	 */
	public function getJoinRows(
		$rename,
		$where = null,
		$where_or = null,
		$join_table = null,
		$join_condition = null,
		$join_type = 'inner'
	) {

		$rows_list = $this->model->getJoinRows(
			$where,
			$where_or,
			$join_table,
			$join_condition,
			$join_type
		);

		if (empty($rows_list)) {
			$rows_list = [];
		} else {
			if ($rename != []) {
				foreach ($rename as $oldkey => $newKey) {
					//do something with your $key and $value;
					$rows_list = $this->renameKey($rows_list, $oldkey, $newKey);
				}
			}
		}

		return $rows_list;
	}

	/**
	 * Returns array list of updated rows in model table, based on date last_sync
	 * $rename is an array of $oldKey=>$newKey. Param $where to use an optional where condition.
	 * @param array|null $rename
	 * @param array|null $where
	 */
	public function getUpdatedRows($rename, $where = null, $where_or = null, $timeStampColumn = 'last_update')
	{

		// $mysqltime = date ('Y-m-d H:i:s', $this->request->getVar('last_sync'));
		$rows_list = $this->model->getUpdatedRows($this->request->getVar('last_sync'), $where, $where_or, $timeStampColumn);
		// echo $rows->last_query();

		if (empty($rows_list)) {
			$rows_list = [];
		} else {
			if ($rename != []) {
				foreach ($rename as $oldkey => $newKey) {
					$rows_list = $this->renameKey($rows_list, $oldkey, $newKey);
				}
			}
		}

		return $rows_list;
	}

	/**
	 * Returns array list of all rows in model table based on $where
	 * conditions
	 * @param array $rename
	 * @param string $where
	 *
	 * @return array|null
	 */
	public function getAllSelectedRows($rename, $where)
	{

		// $mysqltime = date ('Y-m-d H:i:s', $this->request->getVar('last_sync'));
		$rows_list = $this->model->getSelectedRows($where);
		// echo $rows->last_query();

		if (empty($rows_list)) {
			$rows_list = [];
		} else {
			if ($rename != []) {
				foreach ($rename as $oldkey => $newKey) {
					$rows_list = $this->renameKey($rows_list, $oldkey, $newKey);
				}
			}
		}

		return $rows_list;
	}

	/**
	 * Returns datetime of db server
	 *
	 */
	protected function getServerDateTime()
	{

		$datetime = $this->model->query('SELECT now()')->getResultArray();
		return array_values($datetime)[0]['now()'];
	}

	/**
	 * Send array $data to an endpoint $url with POST, with the same content-type as a html form
	 * @param string $url
	 * @param array $data
	 */
	public function httpPostXform($url, $data)
	{
		$curl = curl_init($url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLINFO_HEADER_OUT, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
		// echo http_build_query($data);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}
	/**
	 * Send array $data to an endpoint $url with GET, with the same content-type as a html form
	 * @param string $url
	 * @param array $data
	 */
	public function httpGETXform($url, $data)
	{
		$curl = curl_init($url . '?' . http_build_query($data));
		// echo($url.'?'.http_build_query($data));
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
		// echo $curl;
		$response = curl_exec($curl);
		curl_close($curl);
		return $response;
	}

	public function dbGroupFromRequest()
	{
		$authHeader = $this->request->getServer('HTTP_AUTHORIZATION');
		helper('jwt');
		$token = getJWTFromRequest($authHeader);
		$dbGroup = dbGroupFromJWT($token);
		return $dbGroup;
	}
}
