<?php

namespace App\Controllers;

use App\Models\ProductsModel;
use App\Models\ProductsLogModel;
use CodeIgniter\Controller;

class Products extends BaseController {
	
	protected array $data;

	function __construct() {
		$this->data['productowners'] = array('S'=>'Summit', 'C'=> 'Customer', 'O' => 'Other');
		$this->data['productactives'] = array('1'=> 'Yes', '2'=>'No');
	}

	// Get Data Dari CLQMS untuk MEAN Jumlah Test Selama 6 Bulan
	private function getPatresCount($pr_number_link) {

		if ($pr_number_link != "") {
			$curl = curl_init(); 

			curl_setopt_array($curl, array(
				CURLOPT_URL => 'https://clqms.services-summit.my.id/api_service/count_patres'.$pr_number_link,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => 'GET',
			));

			$response = curl_exec($curl);
			curl_close($curl);
			$data = json_decode($response, true);

			return $data;
		}

    }
	
	public function index() {
		$db = \Config\Database::connect();
		
		$sql = "select * from productalias";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['productalias'] = $results;
		
		$sql = "select * from areas";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['areas'] = $results;

		$sql = "select * from producttype";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['producttype'] = $results;

		if ($this->request->getMethod() === 'POST') {
			
			$productaliasid = $this->request->getVar('productaliasid');
			$areaid = $this->request->getVar('areaid');
			$producttypeid = $this->request->getVar('producttypeid');
			$sitename = $this->request->getVar('sitename');

			$data['productaliasid'] = $productaliasid;
			$data['areaid'] = $areaid;
			$data['producttypeid'] = $producttypeid;
			$data['sitename'] = $sitename;

			$areaquery = '';
			if($areaid != '') { $areaquery = " s.siteid in (select siteid from v_siteaccount where areaid='$areaid') "; }

			$producttypequery = '';
			if($producttypeid != '') { $producttypequery = " pt.producttypeid='$producttypeid' "; }
			
			$sitenamequery = '';
			if($sitename!= '') { 
				$sitename = strtolower($sitename);
				$sitenamequery= " lower(s.sitename) like '%$sitename%' "; 
			}

			$where = 0;
			
			$sql = "SELECT p.productid, p.installationdate, p.active, pc.productname, pc.productaliasid, p.productnumber, s.sitename, pt.producttypeid, pt.texts, 
					z.zonename as city, z2.zonename as prov, a1.accountname
					FROM products p
					left join accounts a1 on a1.accountid=p.accountid_productowner
					left join productcatalog pc on pc.catalogid=p.catalogid
					left join producttype pt on pt.producttypeid=pc.producttypeid
					left join sites s on s.siteid=p.siteid
					left join accounts a on a.accountid=s.accountid
					left join zones z on z.zoneid=a.zoneid
					left join zones z2 on z2.zoneid=z.parentzoneid
					";
			
			if($productaliasid != 0) {
				if($where == 0) { $sql .=" where "; $where++; } 
				else { $sql .=" and "; }	
				$sql.= "pc.productaliasid='$productaliasid'";
			}

			if($areaquery != '') {
				if($where == 0) { $sql .=" where "; $where++; } 
				else { $sql .=" and "; }	
				$sql.= "$areaquery";
			}

			if($producttypequery != '') {
				if($where == 0) { $sql .=" where "; $where++; } 
				else { $sql .=" and "; }	
				$sql.= "$producttypequery";
			}
			
			if($sitenamequery != '') {
				if($where == 0) { $sql .=" where "; $where++; } 
				else { $sql .=" and "; }	
				$sql.= "$sitenamequery";
			}

			$sql.=" ORDER BY p.installationdate DESC ";

			$data['sql']=$sql;
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['products'] = $results;

			// // Untuk CLQMS Patres Count Rata-Rata Bulanan
			// $pr_number_link = "";			
			// foreach ($data['products'] as $value) {
			// 	// 20 adalah kode TMS-30i
			// 	if ($value['productaliasid'] == '20') {
			// 		$pr_number_link .= "/" . $value['productnumber'];
			// 	}
			// }
			// if ($pr_number_link != "") {
			// 	$data['testCountCLQMS'] = $this->getPatresCount($pr_number_link);
			// }
		
		}
		return view('products_index', $data);
	}
	
	public function view($productid=null) {
		$db = \Config\Database::connect();

		$sql = "SELECT p.*, pc.productname, ps.productservicetext, s.sitename, pc.catalognumber
			FROM products p
			left join productcatalog pc on pc.catalogid=p.catalogid
			left join sites s on s.siteid=p.siteid
			left join productservice ps on p.productserviceid=ps.productserviceid
			where p.productid='$productid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products'] = $results;

		$sql = "SELECT pl.*, pc.productname, ps.productservicetext, pc.catalognumber, s.sitename
			FROM products_log pl
			LEFT JOIN productcatalog pc ON pc.catalogid=pl.catalogid
			left join sites s on s.siteid=pl.siteid
			left join productservice ps on ps.productserviceid=pl.productserviceid
			where pl.productid='$productid' order by pl.logdate desc";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products_log'] = $results;

		return view('products_view', $data);
	}
	
	public function edit($productid=null) {
		$db = \Config\Database::connect();
		
		if($productid != 0) {
			$sql = "select * from products where productid='$productid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['products'] = $results;
		}
		
		$sql = "select * from productcatalog where productaliasid <> ''";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['productcatalog'] = $results;
		
		$sql = "select * from sites where enddate is null";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		
		$sql = "select * from productservice";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['productservice'] = $results;

		$sql = "select * from accounts";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['accounts'] = $results;
		
		$data['productowners'] = $this->data['productowners'];
		$data['productactives'] = $this->data['productactives'];

		if ($this->request->getMethod() === 'POST') {

			$rules = [
				'productid' => 'required',
				'productnumber' => 'required|is_unique[products.productnumber,productid,'.$productid.']',
				'catalogid' => 'required',
				'siteid' => 'required',
				'productowner' => 'required'
			];
			$data['new_value'] = [
				'productid' => $this->request->getVar('productid'),
				'siteid'  => $this->request->getVar('siteid'),
				'productnumber' => $this->request->getVar('productnumber'),
				'catalogid'  => $this->request->getVar('catalogid'),
				'locationstartdate'  => ($this->request->getVar('locationstartdate') == '') ? NULL : $this->request->getVar('locationstartdate'),
				'installationdate'  => ($this->request->getVar('installationdate') == '') ? NULL : $this->request->getVar('installationdate'),
				'warrantystartdate'  => ($this->request->getVar('warrantystartdate') == '') ? NULL : $this->request->getVar('warrantystartdate'),
				'warrantyenddate'  => ($this->request->getVar('warrantyenddate') == '') ? NULL : $this->request->getVar('warrantyenddate'),
				'accountid_productowner'  => $this->request->getVar('accountid_productowner'),
				'productowner'  => $this->request->getVar('productowner'),
				'active' => ($this->request->getVar('productactive') == '') ? NULL : $this->request->getVar('productactive'),
				'productserviceid'  => $this->request->getVar('productserviceid'),
				'statuspart'  => $this->request->getVar('statuspart'),
				'remotetool'  => $this->request->getVar('remotetool'),
				'remoteid'  => $this->request->getVar('remoteid'),
				'remotepwd'  => $this->request->getVar('remotepwd'),
			];
			
			foreach($data['new_value'] as $qkey => $qvalue) {
				if(empty( $qvalue ) ) { $data['new_value'][$qkey] = null; }
				else { $data['new_value'][$qkey] = $db->escapeString($qvalue); }
			}

			if($productid != 0) {
				if($this->validate($rules)){
					$productsModel = new ProductsModel();
					$productsModel->update($productid, $data['new_value']);
					return view('form_success',$data);
				} else {
					$data['validation'] = $this->validator;
					return view('products_edit',$data);
				}
			} else {
				if($this->validate($rules)){
					$productsModel = new ProductsModel();
					$productsModel->set('createdate', 'NOW()', FALSE);
					$productsModel->insert($data['new_value']);
					return view('form_success');
				} else {
					$data['validation'] = $this->validator;
					return view('products_edit',$data);
				}
			}
		}
		return view('products_edit', $data);
	}
	
	public function movesite($productid=null) {
		$db = \Config\Database::connect();
		
		$sql = "select p.*, pc.productname from products p 
			left join productcatalog pc on pc.catalogid=p.catalogid
			where p.productid='$productid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products'] = $results;
		
		$sql = "select * from sites";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		
		
		$sql = "select * from accounts";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['accounts'] = $results;

		$data['productowners'] = $this->data['productowners'];
		
		if ($this->request->getMethod() === 'POST') {
			
			$rules = [
				'productid' => 'required',
				'siteid' => 'required',
				'oldlocationenddate' => 'required',
				'newlocationstartdate' => 'required',
				'productowner' => 'required',
			];
			$data['new_value'] = [
				'productnumb' => $this->request->getVar('productnumb'),
				'productnam' => $this->request->getVar('productnam'),
				'productid' => $this->request->getVar('productid'),
				'siteid'  => $this->request->getVar('siteid'),
				'oldlocationenddate' => $this->request->getVar('oldlocationenddate'),
				'newlocationstartdate' => $this->request->getVar('newlocationstartdate'),
				'productowner' => $this->request->getVar('productowner'),
				'accountid_productowner' => $this->request->getVar('accountid_productowner'),
			];

			if($this->validate($rules)){

				$productid = $data['new_value']['productid'];
				$siteid = $data['new_value']['siteid'];
				$oldlocationenddate = $data['new_value']['oldlocationenddate'];
				$newlocationstartdate = $data['new_value']['newlocationstartdate'];
				$productowner = $data['new_value']['productowner'];
				$accountid_productowner = $data['new_value']['accountid_productowner'];
				// products_log
				$sql = "INSERT INTO products_log 
					(productid, siteid, catalogid, locationstartdate, locationenddate, installationdate, warrantystartdate, warrantyenddate, productowner, productserviceid, statuspart, accountid_productowner, logdate )
					SELECT productid, siteid,catalogid, locationstartdate, '$oldlocationenddate', installationdate, warrantystartdate, warrantyenddate, productowner, productserviceid, statuspart, accountid_productowner, NOW() 
					FROM products WHERE productid='$productid'";
				$query = $db->query($sql);

				// products
				$sql = "update products set siteid='$siteid', locationstartdate='$newlocationstartdate', productowner='$productowner', accountid_productowner='$accountid_productowner' where productid='$productid'";
				$query = $db->query($sql);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('products_movesite', $data);
			}
		} 
		return view('products_movesite', $data);
	}
	
	public function changeowner($productid=null) {
		$db = \Config\Database::connect();
		
		$sql = "select p.*, pc.productname from products p 
			left join productcatalog pc on pc.catalogid=p.catalogid
			where p.productid='$productid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products'] = $results;
		
		$data['productowners'] = $this->data['productowners'];
		
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'productid' => 'required',
				'productowner' => 'required',
			];
			$data['new_value'] = [
				'productid' => $this->request->getVar('productid'),
				'productowner' => $this->request->getVar('productowner')
			];
			if($this->validate($rules)){
				$productid = $data['new_value']['productid'];
				$productowner = $data['new_value']['productowner'];
				// products_log
				$sql = "INSERT INTO products_log 
					(productid, siteid, catalogid, locationstartdate, locationenddate, installationdate, warrantystartdate, warrantyenddate, productowner, productserviceid, statuspart, logdate )
					SELECT productid, siteid,catalogid, locationstartdate, null, installationdate, warrantystartdate, warrantyenddate, productowner, productserviceid, statuspart, NOW() 
					FROM products WHERE productid='$productid'";
				$query = $db->query($sql);
				// products
				$sql = "update products set productowner='$productowner' where productid='$productid'";
				$query = $db->query($sql);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('products_changeowner', $data);
			}
		} 
		return view('products_changeowner', $data);
	}
	
	public function upgrade($productid=null) {
		$db = \Config\Database::connect();
		
		$sql = "select p.*, pc.productname from products p 
			left join productcatalog pc on pc.catalogid=p.catalogid
			where p.productid='$productid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products'] = $results;
		
		$sql = "select * from productcatalog where productaliasid <> ''";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['productcatalog'] = $results;
		
		//$data['productowners'] = $this->data['productowners'];
		
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'productid' => 'required',
				'catalogid' => 'required',
			];
			$data['new_value'] = [
				'productid' => $this->request->getVar('productid'),
				'catalogid' => $this->request->getVar('catalogid')
			];
			if($this->validate($rules)){
				$productid = $data['new_value']['productid'];
				$catalogid = $data['new_value']['catalogid'];
				// products_log
				$sql = "INSERT INTO products_log 
					(productid, siteid, catalogid, locationstartdate, locationenddate, installationdate, warrantystartdate, warrantyenddate, productowner, productserviceid, statuspart, logdate )
					SELECT productid, siteid,catalogid, locationstartdate, null, installationdate, warrantystartdate, warrantyenddate, productowner, productserviceid, statuspart, NOW() 
					FROM products WHERE productid='$productid'";
				$query = $db->query($sql);
				// products
				$sql = "update products set catalogid='$catalogid' where productid='$productid'";
				$query = $db->query($sql);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('products_upgrade', $data);
			}
		} 
		return view('products_upgrade', $data);
	}
	
	public function productslog_edit($productlogid=null) {
		$db = \Config\Database::connect();
		
		$sql = "select * from productcatalog where productaliasid <> ''";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['productcatalog'] = $results;
		
		$sql = "select * from products_log where productlogid='$productlogid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products_log'] = $results;

		$sql = "select * from sites";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		
		if ($this->request->getMethod() === 'POST') {
			$data['new_value'] = [
				'catalogid' => $this->request->getVar('catalogid'),
				'siteid'  => $this->request->getVar('siteid'),
				
				'locationstartdate'  => ($this->request->getVar('locationstartdate') == '') ? NULL : $this->request->getVar('locationstartdate'),
				'locationenddate'  => ($this->request->getVar('locationenddate') == '') ? NULL : $this->request->getVar('locationenddate'),
				'installationdate'  => ($this->request->getVar('installationdate') == '') ? NULL : $this->request->getVar('installationdate'),
				'warrantystartdate'  => ($this->request->getVar('warrantystartdate') == '') ? NULL : $this->request->getVar('warrantystartdate'),
				'warrantyenddate'  => ($this->request->getVar('warrantyenddate') == '') ? NULL : $this->request->getVar('warrantyenddate'),
				
				'productowner'  => $this->request->getVar('productowner'),
				'productserviceid'  => $this->request->getVar('productserviceid'),
				'statuspart'  => $this->request->getVar('statuspart')
			];

			$productsLogModel = new ProductsLogModel();
			$productsLogModel->update($productlogid, $data['new_value']);
			return view('form_success');
		}
		return view('productslog_edit', $data);
	}
	
	public function productslog_delete() {
		$db = \Config\Database::connect();
		$productlogid = $this->request->getVar('logid');
		$sql = "delete from products_log where productlogid='$productlogid'";
		$query = $db->query($sql);
	}

	public function exportdata() {
		
		$db = \Config\Database::connect();

		$productaliasid = $this->request->getGet('productaliasid');
		$areaid = $this->request->getGet('areaid');
		$producttypeid = $this->request->getGet('producttypeid');
		$sitename = $this->request->getGet('sitename');


		$areaquery = '';
		if($areaid != '') { $areaquery = " s.siteid in (select siteid from v_siteaccount where areaid='$areaid') "; }

		$producttypequery = '';
		if($producttypeid != '') { $producttypequery = " pt.producttypeid='$producttypeid' "; }
		
		$sitenamequery = '';
		if($sitename!= '') { 
			$sitename = strtolower($sitename);
			$sitenamequery= " lower(s.sitename) like '%$sitename%' "; 
		}

		$where = 0;
		
		$sql = "SELECT a2.accountname as owneraccount, p.statuspart, ps.productservicetext,  p.productid, pc.productname, p.productnumber, p.active, pc.catalognumber, pt.texts as type_name, pc.manufacturer, s.sitename, 
				z.zonename as city, z2.zonename as prov, p.installationdate, p.locationstartdate, p.locationenddate, p.warrantystartdate, p.warrantyenddate, p.productowner
				FROM products p
				left join productcatalog pc on pc.catalogid=p.catalogid
				-- left join accoun pc2 on pc2.catalogid=p.accountid_productowner
				left join producttype pt on pt.producttypeid=pc.producttypeid
				left join productservice ps on ps.productserviceid=p.productserviceid
				left join sites s on s.siteid=p.siteid
				left join accounts a on a.accountid=s.accountid
				left join accounts a2 on a2.accountid=p.accountid_productowner
				left join zones z on z.zoneid=a.zoneid
				left join zones z2 on z2.zoneid=z.parentzoneid
				";
		
		if($productaliasid != 0) {
			if($where == 0) { $sql .=" where "; $where++; } 
			else { $sql .=" and "; }	
			$sql.= "pc.productaliasid='$productaliasid'";
		}

		if($areaquery != '') {
			if($where == 0) { $sql .=" where "; $where++; } 
			else { $sql .=" and "; }	
			$sql.= "$areaquery";
		}

		if($producttypequery != '') {
			if($where == 0) { $sql .=" where "; $where++; } 
			else { $sql .=" and "; }	
			$sql.= "$producttypequery";
		}
		
		if($sitenamequery != '') {
			if($where == 0) { $sql .=" where "; $where++; } 
			else { $sql .=" and "; }	
			$sql.= "$sitenamequery";
		}

		$sql.=" ORDER BY p.installationdate DESC";

		$data['sql']=$sql;
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products'] = $results;

		return view('products_export_excel', $data);

	}
}