<?php
namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class API_DictMappings extends ResourceController {
	protected $format = 'json';

	public function index()	{
		$db = \Config\Database::connect();
		$sql = "select m.*, t.TUBECODE, t.TUBENAME from cmod.dbo.CM_DICT_MAPPINGS m
			left join cmod.dbo.CM_DICT_TUBES t on m.TUBEID=t.TUBEID";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['dictMappings'] = $results;
		
		return $this->respond($data, 200);
	}
	
	public function search(){
		$db = \Config\Database::connect();
		$liscode = $this->request->getPost('liscode');
		$hiscode = $this->request->getPost('hiscode');
		$descs = $this->request->getPost('maptext');
		$sql = "select m.*, t.TUBECODE, t.TUBENAME from cmod.dbo.CM_DICT_MAPPINGS m
			left join cmod.dbo.CM_DICT_TUBES t on m.TUBEID=t.TUBEID";
		$where = "";
		if (!empty($liscode) || !empty($hiscode) || !empty($maptext) ) {
			$where = ' WHERE ';
			$x = 0;
			if (!empty($liscode)) { $where .= "m.LISCODE like '%$liscode%'"; $x = 1; }
			if (!empty($hiscode)) {
				if ($x == 1) { $where .= ' OR '; }
				$where .= "m.HISCODE LIKE '%$hiscode%'"; $x = 1;
			}
			if (!empty($maptext)) {
				if ($x == 1) { $where .= ' OR '; }
				$where .= "LOWER(m.DESCS) LIKE '%$maptext%'";
			}
		}
		$sql .= $where;
		
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['dictMappings'] = $results;
		
		return $this->respond($data, 200);
	}
	
	public function detail($mapid)	{
		$data = array();
		$db = \Config\Database::connect();
		$sql = "select * from cmod.dbo.CM_DICT_MAPPINGS where MAPID='$mapid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if(isset($results[0])) { 
			$data = $results[0]; 
			if($data['MAPTYPE']=='P') {
				$sql = "select * from cmod.dbo.CM_DICT_MAPPING_PROFILES where MAPID='$mapid'";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				$data['mliscodes'] = $results;
			}
		}
		return $this->respond($data, 200);
	}
	
	public function saveSingle() {
		$update = $this->request->getPost('update');
		$liscode = $this->request->getPost('liscode');
		$hiscode = $this->request->getPost('hiscode');
		$descs = $this->request->getPost('descs');
		$tubeid = $this->request->getPost('tubeid');
		
		// check if hiscode is exists
		$db = \Config\Database::connect();
		$sql = "select 1 from cmod.dbo.CM_DICT_MAPPINGS where HISCODE='$hiscode' and MAPTYPE in ('S','P') and MAPID<>'$update'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if(isset($results[0])) { 
			$response = [
				'errors' => 'HISCODE already exists',
				'message' => 'HISCODE already exists'
			];
			return $this->fail($response , 409);
		}
		
		
		if($update == '0') { $sql = "INSERT INTO cmod.dbo.CM_DICT_MAPPINGS (MAPTYPE, HISCODE, LISCODE, DESCS, TUBEID ) VALUES ('S', '$hiscode', '$liscode', '$descs', '$tubeid')"; }
		else { $sql = "UPDATE cmod.dbo.CM_DICT_MAPPINGS set HISCODE='$hiscode', LISCODE='$liscode', DESCS='$descs', TUBEID='$tubeid' where MAPID='$update'";  }
		
		if( $db->query($sql) )  {
			return $this->respond(['message' => 'Save Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalid Inputs'
			];
	       return $this->fail($response , 409);
        }
	}
	
	public function saveProfile() {
		$db = \Config\Database::connect();
		$update = $this->request->getPost('update');
		$hiscode = $this->request->getPost('hiscode');
		$tubeid = $this->request->getPost('tubeid');
		$descs = $this->request->getPost('descs');
		$mliscode = [];
		for ($i = 1; $i <= 44; $i++) {
			$key = "mliscode{$i}";
			if (isset($_POST[$key])) {
				$mliscode[$key] = $this->request->getPost($key);
			}
		}
		
		// check if hiscode is exists
		$sql = "select 1 from cmod.dbo.CM_DICT_MAPPINGS where HISCODE='$hiscode' and MAPTYPE in ('P','S') and MAPID<>'$update'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if(isset($results[0])) { 
			$response = [
				'errors' => $db->errors(),
				'message' => 'HISCODE already exists'
			];
			return $this->fail($response , 409);
		}
		
		// dict_mappings
		if($update == '0') { $sql = "INSERT INTO cmod.dbo.CM_DICT_MAPPINGS (MAPTYPE, HISCODE, LISCODE, DESCS, TUBEID) VALUES ('P', '$hiscode', null, '$descs', '$tubeid')"; }
		else { $sql = "UPDATE cmod.dbo.CM_DICT_MAPPINGS set HISCODE='$hiscode', LISCODE=null, DESCS='$descs', TUBEID='$tubeid' where MAPID='$update'";  }
		if( !$db->query($sql) )  {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalid Inputs'
			];
	       return $this->fail($response , 409);
        }
		// getting mapid after
		if($update == 0) { $update = $db->insertID(); }
		
		// dict_mapping_profiles
		$datasource = '';
		foreach($mliscode as $liscode) { $datasource .= "('$update','$liscode'),"; }
		$datasource = rtrim($datasource,',');
		$sql = "MERGE INTO cmod.dbo.CM_DICT_MAPPING_PROFILES AS t
			USING ( VALUES 
				$datasource
			) AS s (MAPID, LISCODE) on s.MAPID=t.MAPID and s.LISCODE=t.LISCODE
			WHEN NOT MATCHED BY TARGET THEN
				INSERT (MAPID, LISCODE)
				VALUES (s.MAPID, s.LISCODE)
			WHEN NOT MATCHED BY SOURCE and t.MAPID='$update' THEN
				DELETE;";
		
		if( $db->query($sql) )  {
			return $this->respond(['message' => 'Save Success'],201);
		} else {
			$response = [
				'errors' => $db->errors(),
				'message' => 'Invalid Inputs'
			];
	       return $this->fail($response , 409);
        }
	}
}