<?php

namespace App\Controllers;

use App\Models\ActivitiesModel;
use App\Models\ActdetailModel;
use App\Models\InvTransModel;

use CodeIgniter\Controller;

class Activities extends Controller {
	
	protected array $data;

	function __construct() {
		$this->data['medias'] = array('WA'=>'Whatsapp', 'PH'=> 'Phone', 'VB' => 'Verbal', 'LT'=>'Letter', 'CRM'=>'Direct CRM', 'SKP'=>'Skype');
		$this->data['actions'] = array('r'=>'Remote', 'p'=> 'Phone', 'o'=>'On site');
		$this -> data['userpos'] = array(
			'' 		=> 'ALL',
			'TSO' 	=> 'ALL - TSO', 
			'IT' 	=> 'IT', 
			'IVD' 	=> 'IVD', 
			'IVDT' 	=> 'IVD - Barat', 
			'IVDH' 	=> 'IVD - Tengah', 
			'IVDR' 	=> 'IVD - Timur',
			'MT' 	=> 'Marketing',
			'PS' 	=> 'Product Specialist',
		);
		$this->data['stats'] = array('O'=>'Open',  'R'=>'Refer', 'A'=>'Accepted', 'P'=>'Pending', 'C'=>'Close', 
											// 'S'=>'Suspend', 'D'=>'Disable'
									);
		$this->data['actbys'] = array( 'P'=>'Product ( Equipment / System )' , 'V'=> 'Vendor', 'C'=>'Consumables / Reagent', 'O'=>'Other');
		$this->data['exports'] = array('P'=>'PDF', 'E'=> 'Excel');
		$this->data['acttypes'] = array(1=>'Incident Report', 2=> 'Change Request', 3=>'Project', 4=>'Support', 5=>'Maintenance', 6=>'Training', 7=>'Refurbish', 9=>'Training Customer/TSO');

		// invtrans
		$this->data['itx_apprtypes'] = array('W'=>'Warranty', 'U'=> 'User');
		$this->data['itx_conditions'] = array('N'=>'New', 'U'=> 'Used', 'R'=>'Refurbished');
		$this->data['itx_purposes'] = array(
			'TB' => 'Retrieve - broken', 'TR' => 'Retrieve - repair', 'TU' => 'Retrieve - usage', 'TF' => 'Retrieve - FSCA',
			'PR' => 'Replace - Repair', 'PB' => 'Replace - broken',	'PU' => 'Replace - usage', 'PF' => 'Replace - FSCA', 'B' => 'Borrow', 'R' => 'Return'
		);
	}
	
	public function index() {
		$data = array();
		$db = \Config\Database::connect();
		
		$sql = "SELECT * FROM sites WHERE enddate IS NULL";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		
		$sql = "SELECT * FROM users order by firstname";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users'] = $results;
		
		$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;

		$data['actbys'] = $this->data['actbys'];
		$data['stats'] = $this->data['stats'];
		$data['acttypes'] = $this->data['acttypes'];
		$data['actions'] = $this->data['actions'];
		
		if( $this->request->getPost('opendate') == '' ){ $opendate = date("Y-m-01"); } 
		else { $opendate = $this->request->getPost('opendate'); }
		if( $this->request->getPost('closedate') == ''){ $closedate = date("Y-m-d"); } 
		else { $closedate = $this->request->getPost('closedate'); }

		$filterquery = '';
        $siteid = $this->request->getPost('siteid');
        $productid = $this->request->getPost('productid');
        $areaid = $this->request->getPost('areaid');
      	$sub = $this->request->getPost('sub');
		$detail_activity = $this->request->getPost('detail_activity');
        $productaliasid = $this->request->getPost('productaliasid');
		$actbys = $this->request->getPost('actbys');
		$acttypes = $this->request->getPost('acttypes');
		$actions = $this->request->getPost('actions');
		
		if($siteid != '') {
			$sql = "SELECT p.*, pc.`productname`, p.`productnumber`
			FROM products p
			LEFT JOIN productcatalog pc ON pc.`catalogid`=p.`catalogid`
			WHERE p.siteid=$siteid and productaliasid<>0 order by pc.productname";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['products'] = $results;
		}
		
		if( $this->request->getPost('userid') != '' ) { $userid = $this->request->getPost('userid'); }
		else { $userid = $_SESSION['userid']; }
		$status = $this->request->getPost('status');

        if($siteid != ''){ $filterquery .= " and a.siteid = '$siteid' "; }
		if($productid != '') { $filterquery .= " and a.productid = '$productid' "; }
        if($productaliasid != ''){ $filterquery .= " and pa.productaliasid = '$productaliasid' "; }
		if($userid != 0 ){ $filterquery .= " and ( u.userid = '$userid' or a.userid_owner=0) "; }
		if($status != ''){ $filterquery .= " and activitystatus = '$status' "; }
      	if($sub == 'IT'){ $filterquery .= " and up.userposid in (3,5) "; }
		if($sub == 'IVD'){ $filterquery .= " and up.userposid in (2,4) "; }
		if($sub == 'PS'){ $filterquery .= " and up.userposid in (6,14) "; }
		if($detail_activity != '') {
			$column_detail_activity = ", ad.*";
			$join_detail_activity   = " left join actdetail ad on a.actid=ad.actid ";
			$filterquery .= " and ad.textvalue LIKE '%$detail_activity%' "; 
		} else {
			$column_detail_activity = "";
			$join_detail_activity   = "";
		}
		if($actbys != ''){$filterquery .= " and a.actby = '$actbys'";}
		if($acttypes != ''){$filterquery .= " and a.acttypeid  = $acttypes";}
		if($actions != ''){$filterquery .= " and a.action  = '$actions'";}

		$areaquery = ''; 
		if($areaid != ''){ $areaquery .= " and a.siteid in ( select siteid from v_siteaccount where areaid='$areaid' ) "; }
		
		if( isset($_GET['reportdate']) ) { 
			$reportdate = $_GET['reportdate']; 
			if($reportdate < $opendate) { $opendate = $reportdate; }
		} else { $reportdate = $opendate; }
		
		$data['opendate'] = $opendate;
        $data['closedate'] = $closedate;
		$data['siteid'] = $siteid;
		$data['productid'] = $productid;
		$data['productaliasid'] = $productaliasid;
		$data['userid'] = $userid;
		$data['status'] = $status;
      	$data['sub'] = $sub;
      	$data['areaid'] = $areaid;
		$data['detail_activity'] = $detail_activity;
		$data['actby'] = $actbys;
		$data['acttype'] = $acttypes;
		$data['action'] = $actions;
		
		$sql = "SELECT s.sitename, pc.productname, v.vendorname ,u.firstname as username,uc.firstname as creator_name, up.userposid, at.fulltext, a.*
			$column_detail_activity 
			FROM `activities` a 		
			$join_detail_activity
			left join sites s on s.siteid=a.siteid 
			left join products p on a.productid=p.productid
			left join productcatalog pc on pc.catalogid=p.catalogid
			left join vendors v on v.vendorid=a.vendorid
			left join productalias pa on pa.productaliasid=pc.productaliasid
			left join users u on u.userid=a.userid_owner 
			left join (select userid, firstname from users) as uc on uc.userid=a.userid_creator
			left join userposition up on up.userposid = u.userposid
			left join acttype at on at.acttypeid=a.acttypeid
			where 
			( a.closedate between '$opendate 00:00:00' and '$closedate 23:59:59' $filterquery $areaquery )
			-- OR ( a.reportdate between '$reportdate 00:00:00' and '$closedate 23:59:59' $filterquery $areaquery )
			OR ( a.activitystatus='O'  $filterquery $areaquery )
			OR ( a.activitystatus='P' $filterquery )
			-- OR ( a.activitystatus='R' ) Dinonaktifkan Dulu
			GROUP BY a.actid
			-- order by field(a.activitystatus,'O','R','C'), a.closedate desc, a.reportdate desc Dinonaktifkan Dulu
			order by field(a.activitystatus,'O','C'), a.closedate desc, a.reportdate desc"
			;
		// $sql = "SELECT s.sitename, pc.productname, v.vendorname, u.firstname AS username, up.userposid, at.fulltext, a.*
		// 	-- ,ad.*
		// 	FROM 
		// 	  activities a
		// 	--   LEFT JOIN actdetail ad ON a.actid = ad.actid
		// 	  LEFT JOIN sites s ON s.siteid = a.siteid
		// 	  LEFT JOIN products p ON a.productid = p.productid
		// 	  LEFT JOIN productcatalog pc ON pc.catalogid = p.catalogid
		// 	  LEFT JOIN vendors v ON v.vendorid = a.vendorid
		// 	  LEFT JOIN productalias pa ON pa.productaliasid = pc.productaliasid
		// 	  LEFT JOIN users u ON u.userid = a.userid_owner
		// 	  LEFT JOIN userposition up ON up.userposid = u.userposid
		// 	  LEFT JOIN acttype at ON at.acttypeid = a.acttypeid
		// 	WHERE (
		// 		a.closedate BETWEEN '$opendate 00:00:00' AND '$closedate 23:59:59'
		// 		$filterquery $areaquery
		// 		OR ( a.activitystatus in ('O','P') $filterquery $areaquery )
		// 	)
		// 	GROUP BY a.actid
		// 	ORDER BY 
		// 	  FIELD(a.activitystatus, 'O', 'C', 'R'), 
		// 	  a.closedate DESC, 
		// 	  a.reportdate DESC;";
		//echo "$sql";
        $query = $db->query($sql);
        $result = $query->getResultArray();
		$data['sql'] = $sql;
        $data['tampildata'] = $result;

		// dd($sql);

		return view('activities_index', $data);
	}
		
    // public function index_getproduct($siteid=null){
	// 	$db = \Config\Database::connect();
	// 	$sql = "SELECT p.*, pc.`productname`, p.`productnumber`
	// 		FROM products p
	// 		LEFT JOIN productcatalog pc ON pc.`catalogid`=p.`catalogid`
	// 		WHERE p.siteid=$siteid and productaliasid<>0 order by pc.productname";
	// 	$query = $db->query($sql);
	// 	$results = $query->getResultArray();
	// 	$option = "<option value=''>--</option>";
	// 	foreach ($results as $data) {
	// 		$qproductid = $data['productid'];
	// 		$qproductname = $data['productname'];
	// 		$qproductnumber = $data['productnumber'];
	// 		$qproductlocationenddate = $data['locationenddate'];
	// 		if($qproductlocationenddate == NULL){
	// 			$option .= "<option value='$qproductid'>$qproductname ( SN# $qproductnumber )</option>\r\n"; 
	// 			//$option .= "$qproductid $qproductname $qproductnumber<br/>";
	// 		}
	// 	}
	// 	//echo "$option";
	// 	return $option;
	// }

	public function index_getproduct($siteid, $productaliasid){
		$db = \Config\Database::connect();

		// Kondisi untuk tiap form
		if ($siteid == 'none' && $productaliasid != 'none') {
			$query = "WHERE pa.productaliasid=$productaliasid";
		} else if ($siteid != 'none' && $productaliasid == 'none') {
			$query = "WHERE p.siteid=$siteid";
		} else {
			$query = "WHERE pa.productaliasid=$productaliasid and p.siteid=$siteid";
		}

		$sql = "SELECT p.*, pc.productname FROM productalias pa 
		LEFT JOIN productcatalog pc ON pa.productaliasid = pc.productaliasid 
		LEFT JOIN products p ON pc.catalogid = p.catalogid 
		LEFT JOIN sites s ON p.siteid = s.siteid 
		$query ORDER BY pc.productname";

		// Kondisi apabila kedua form kosong
		if ($siteid == 'none' && $productaliasid == 'none') {
			return "<option value=''>--</option>";
		}

		$query = $db->query($sql);
		$results = $query->getResultArray();
		$option = "<option value=''>--</option>";
		foreach ($results as $data) {
			$qproductid = $data['productid'];
			$qproductname = $data['productname'];
			$qproductnumber = $data['productnumber'];
			$qproductlocationenddate = $data['locationenddate'];
			if($qproductlocationenddate == NULL){
				$option .= "<option value='$qproductid'>$qproductname ( SN# $qproductnumber )</option>\r\n"; 
				//$option .= "$qproductid $qproductname $qproductnumber<br/>";
			}
		}
		//echo "$option";
		return $option;
	}
    
	public function edit($actid=null){
		$db = \Config\Database::connect();
		$data['controller'] = $this;
		$data['actid'] = $actid;
		$siteid = '';
		$actby = '';

		$data['actid_ref_status'] = 'disabled'; // Khusus untuk refer create
		$data['reff'] = []; //Reff
		
		if($actid != 0) {
			$sql = "select * from activities where actid=$actid";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['activities'] = $results;
			$siteid = $results[0]['siteid'];
			$actby = $results[0]['actby'];

			// Khusus Untuk Refer Edit
			if ($results[0]['actid_ref'] > 0 ) {
				$act_reff = $results[0]['actid_ref'];
				$data['actid_ref_status'] = '';
				$sql = "SELECT a.actid, a.subject, CONCAT(u.firstname,' ',u.lastname) as fullname, s.sitename
						FROM activities a
						LEFT JOIN sites s ON a.`siteid`=s.`siteid`
						LEFT JOIN users u ON a.`userid_owner`=u.`userid`
						WHERE a.actid=$act_reff";
						// -- AND a.actid = $actid
				$query = $db->query($sql);
				$results = $query->getResultArray();
				$data['reff'] = $results;
			}
				
			$sql = "select actdetailid, acttextid, textvalue from actdetail where actid=$actid order by acttextid, createdate desc";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			foreach( $results as $result ) {
				$qactdetailid = $result['actdetailid'];
				$data['activities'][0]['actdetailid'][] = $result['actdetailid'];
				$data['activities'][0]['acttextid'][] = $result['acttextid'];
				$data['activities'][0]['textvalue'][] = $result['textvalue'];
			}

			$sql = "select * from invtrans where actid='$actid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['invtrans'] = $results;
		}
			
		$sql = "select userid, firstname, lastname from users where enddate is null order by firstname";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users'] = $results;
	
		$sql = "select siteid, enddate, sitename from sites where enddate is null order by siteid";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		
		$sql = "select * from acttype";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttype'] = $results;

		$sql = "select * from acttext";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttext'] = $results;
		
		$data['medias'] = $this->data['medias'];
		$data['actions'] = $this->data['actions'];
		$data['stats'] = $this->data['stats'];
		$data['actbys'] = $this->data['actbys'];
		
		// invtrans
		$data['purposes'] = $this->data['itx_purposes'];
		$data['conditions'] = $this->data['itx_conditions'];
		
		$sql = " SELECT u.*, c.`productname`, c.catalognumber FROM unitgroup u
			LEFT JOIN productcatalog c ON u.`catalogid`=c.`catalogid`
			WHERE c.productaliasid<>0 AND u.`enddate` IS NULL";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['unitgroup'] = $results;
		
		$sql = "SELECT p.productid, s.sitename, pc.productname, p.productnumber FROM products p
				LEFT JOIN productcatalog pc ON p.`catalogid`=pc.`catalogid`
				LEFT JOIN sites s ON s.`siteid`=p.`siteid`";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products'] = $results;
		
		$sql = "SELECT * FROM invcounters";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['invcounters'] = $results;
		
		$sql = "SELECT * FROM vendors";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['vendors'] = $results;
		
		if( $this->request->getVar('siteid') != '' ) { $siteid = $this->request->getVar('siteid');  }
		
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'subject' => 'required',
				'siteid' => 'required',
				'userid_creator' => 'required',
				'reportdate' => 'required',
				'activitystatus' => 'required',
				'actdetailid' => 'required'
			];
			$data['new_value'] = [
				'actid_ref' => (int) $this->request->getVar('actid_ref'),
				'actby' => $this->request->getVar('actby'),
				'siteid' => $this->request->getVar('siteid'),
				'acttypeid' => $this->request->getVar('acttypeid'),
				'userid_owner' => $this->request->getVar('userid_owner'),
				'userid_creator' => $this->request->getVar('userid_creator'),
				'activitystatus' => $this->request->getVar('activitystatus'),
				// 'referid' => $this->request->getVar('referid'),
				'reportfrom' => $this->request->getVar('reportfrom'),
				'reportdate' => $this->request->getVar('reportdate'),
				'opendate' => $this->request->getVar('opendate'),
				'closedate' => $this->request->getVar('closedate'),
				'media' => $this->request->getVar('media'),
				'action' => $this->request->getVar('action'),
				'subject' => $this->request->getVar('subject'),
				'attachment' => $this->request->getVar('attachment'),
				'actdetailid' => $this->request->getVar('actdetailid'),
				'acttextid' => $this->request->getVar('acttextid'),
				'textvalue' => $this->request->getVar('textvalue')
			];

			$actby = $this->request->getVar('actby');
			if($actby == 'P') { 
				$data['new_value']['productid'] = $this->request->getVar('productid'); 
				$data['new_value']['swversion'] = $this->request->getVar('swversion'); 
				$data['new_value']['vendorid'] = null;
			} elseif($actby == 'V') { 
				$data['new_value']['vendorid'] = $this->request->getVar('vendorid');
				$data['new_value']['productid'] = null; 
				$data['new_value']['swversion'] = null;
			} else {
				$data['new_value']['vendorid'] = null;
				$data['new_value']['productid'] = null; 
				$data['new_value']['swversion'] = null; 
			}

			if ($this->validate($rules)) {	
				$db = \Config\Database::connect();
				if($actid == 0) { 

					// Cek apakah ada duplikasi data
					$exists = $db->table('activities')
						->where('subject', $data['new_value']['subject'])
						->where('siteid', $data['new_value']['siteid'])
						->where('reportdate', $data['new_value']['reportdate'])
						->where('opendate', $data['new_value']['opendate'])
						->where('closedate', $data['new_value']['closedate'])
						->where('userid_creator', $data['new_value']['userid_creator'])
						->get()->getRow();
					if ($exists) { // Jika ada maka Redirect
						return redirect()->to('/activities');
					}

					// Create Activities
					$activitiesModel = new ActivitiesModel();
					$activitiesModel->set('createdate', 'NOW()', FALSE);
					$activitiesModel->insert($data['new_value']);

					// Create Activities Status Log
					$actid = $activitiesModel->getInsertID();
					$actstatus = $data['new_value']['activitystatus'];
					$userid = $data['new_value']['userid_creator'];
					$sql = "INSERT INTO actstatus_log (activityid, activitystatus, userid, logdate) 
							VALUES ($actid,'$actstatus', $userid, NOW())";
					$query = $db->query($sql);

					$acttextid = $data['new_value']['acttextid'];
					$textvalue = $data['new_value']['textvalue'];
					foreach($data['new_value']['acttextid'] as $qindex => $qacttextid) {
						$qtextvalue = $db->escapeString($textvalue[$qindex]);
						$sql = "insert into actdetail (actid, acttextid, textvalue, createdate) values ('$actid','$qacttextid', '$qtextvalue', NOW())";
						$query = $db->query($sql);
					}
				} else { 
					// update edit
					$activitiesModel = new ActivitiesModel();
					$activitiesModel->update($actid,$data['new_value']);

					// REFF UPDATE
					if ($data['new_value']['activitystatus'] == 'C' && $data['new_value']['actid_ref'] > 0 ) {
						// Update field 'activitystatus' menjadi 'C' untuk actid yang REF
						$activitiesModel->update($data['new_value']['actid_ref'], ['activitystatus' => 'C']);
					}
					
					// clear other act by
					if($actby == 'P') { // product
						$sql = "update activities set vendorid=null where actid='$actid'";
						$query = $db->query($sql);
						$sql = "delete from actconsumables where actid='$actid'";
						$query = $db->query($sql);	
					} elseif($actby == 'V') { // vendor
						$sql = "update activities set productid=null where actid='$actid'";
						$query = $db->query($sql);
						$sql = "delete from actconsumables where actid='$actid'";
						$query = $db->query($sql);
					} elseif($actby == 'C') { // consumables
						$sql = "update activities set productid=null where actid='$actid'";
						$query = $db->query($sql);
						$sql = "update activities set vendorid=null where actid='$actid'";
						$query = $db->query($sql);
					} else { // other
						$sql = "update activities set productid=null where actid='$actid'";
						$query = $db->query($sql);
						$sql = "update activities set vendorid=null where actid='$actid'";
						$query = $db->query($sql);
						$sql = "delete from actconsumables where actid='$actid'";
						$query = $db->query($sql);
					}
					
					// Apabila Act Status Diubah Maka Kondisi berikut dijalankan
					$tb_actstatus_log = $db->table('actstatus_log');
					$actstatus_old = $tb_actstatus_log->select('activitystatus')->where('activityid', $actid)->orderBy('logdate', 'DESC')->get()->getRowArray();
					$actstatus_new = $data['new_value']['activitystatus'];
					$actstatus_old = !empty($actstatus_old) ? $actstatus_old['activitystatus'] : NULL;
					$userid = $data['new_value']['userid_creator'];
					if( $actstatus_old != $actstatus_new ) {
						// Create Activities Status Log
						$sql = "INSERT INTO actstatus_log (activityid, activitystatus, userid, logdate) 
						VALUES ($actid,'$actstatus_new', $userid, NOW())";
						$query = $db->query($sql);
					}
					
					$acttextid = $data['new_value']['acttextid'];
					$textvalue = $data['new_value']['textvalue'];
					//del actdetailid
					$actdetailid_delete = $this->request->getVar('actdetailid_delete');
					if($actdetailid_delete !='') {
						$actdetailid_del = explode(' ',$actdetailid_delete);
						foreach($actdetailid_del as $actdetailid) {
							$sql = "delete from actdetail where actdetailid='$actdetailid'";
							$query = $db->query($sql);	
						}
					}
					
					foreach($data['new_value']['actdetailid'] as $qkey => $qactdetailid) {
						$qacttextid = $acttextid[$qkey];
						$qtextvalue = $db->escapeString($textvalue[$qkey]);
						if( $qactdetailid == 0 ) {
							$sql = "insert into actdetail (actid, acttextid, textvalue, createdate) values ('$actid','$qacttextid', '$qtextvalue', NOW())";
							$query = $db->query($sql);
						} else {
							$sql = "insert into actdetail (actdetailid, actid, acttextid, textvalue, createdate) values ('$qactdetailid','$actid','$qacttextid', '$qtextvalue', NOW())
								ON DUPLICATE KEY UPDATE acttextid='$qacttextid', textvalue='$qtextvalue'";
							$query = $db->query($sql);	
						}
					}
				}
				
				// act by consumables
				$actconid_delete = $this->request->getVar('actconid_delete');
				if($actconid_delete != '') {
					$actconid_del = explode(' ',$actconid_delete);
					foreach($actconid_del as $actconid) {
						$sql = "delete from actconsumables where actconid='$actconid'";
						$query = $db->query($sql);	
					}
				}
				$catalogid = $this->request->getVar('catalogid');
				if(isset($catalogid)) {
					$lotnumber = $this->request->getVar('lotnumber');
					$sql = "INSERT INTO actconsumables ( actid, catalogid, lotnumber ) VALUES ";
					foreach($catalogid as $qid => $qvalue) {
						$sql .= "( '$actid' , '". $catalogid[$qid]."', '". $lotnumber[$qid]."' ),"; 
					}
					$sql = rtrim($sql, ',');
					$query = $db->query($sql);
				}
				
				// invtrans 
				$itxid_delete = $this->request->getVar('itxid_delete');
				if($itxid_delete!='') {
					$itxid_del =explode(' ',$itxid_delete);
					foreach($itxid_del as $itxid) {
						$sql = "delete from invtrans where itxid='$itxid'";
						$query = $db->query($sql);	
					}
				}
				
				$dests = $this->request->getVar('dests');
				$origins = $this->request->getVar('origins');
				if(isset($dests)) {
					foreach($dests as $qdata) {
						$qdata = explode("|",$qdata);
						$desttype[] = $qdata[0];
						$destid[] = $qdata[1];
					}
					foreach($origins as $qdata) {
						$qdata = explode("|",$qdata);
						$origtype[] = $qdata[0];
						$origid[] = $qdata[1];
					}
					$unitgroupid = $this->request->getVar('unitgroupid');
					$lotnumber = $this->request->getVar('lotnumber');
					$qty = $this->request->getVar('qty');
					$conditions = $this->request->getVar('conditions');
					$itxdate = $this->request->getVar('itxdate');
					$purpose = $this->request->getVar('purpose');
					$sql = "INSERT INTO invtrans ( actid, desttype, destid, origtype, origid, unitgroupid, lotnumber, qty, conditions, purpose, itxdate ) VALUES ";
					foreach($origid as $qid => $qorigid) {
						$sql .= "( '$actid', '".$desttype[$qid]."', '".$destid[$qid]."', '".$origtype[$qid]."', '".$qorigid."', '".
							$unitgroupid[$qid]."', '".$lotnumber[$qid]."', '".$qty[$qid]."', '".$conditions[$qid]."', '".$purpose[$qid]."', '".$itxdate[$qid]."' ),"; 
					}
					$sql = rtrim($sql, ',');
					//echo "$sql";
					$query = $db->query($sql);
				}
				$reportdate = substr($data['new_value']['reportdate'],0,10);
				return redirect()->to('activities/?reportdate='.$reportdate);
			} else {
				$data['validation'] = $this->validator;
				return view('activities_editor',$data);
			}
		}
		$data['actid'] = $actid;
		$data['refer_page'] = false; // Khusus untuk controller refer
		return view('activities_editor',$data);
	}

	public function createrefer($actid) {

		$db = \Config\Database::connect();

		// Digunakan Untuk Get Reff ID saja
		$sql = "SELECT a.actid, a.subject, CONCAT(u.firstname,' ',u.lastname) as fullname, s.sitename, a.userid_owner
				FROM activities a
				LEFT JOIN sites s ON a.`siteid`=s.`siteid`
				LEFT JOIN users u ON a.`userid_owner`=u.`userid`
				WHERE a.activitystatus='R' and a.actid=$actid";
				// -- AND a.actid = $actid
		$query = $db->query($sql);
		$results = $query->getResultArray();
		if (empty($results)) {// Jika KOSONG ALIAS TIDAK ADA REFF ID	
			return redirect()->to('/activities');
		}
		if (session()->get('userid') == $results[0]['userid_owner']) {// Agar User tidak bisa buat reff id pada dirinya sendiri	
			return redirect()->to('/activities');
		}
		$data['reff'] = $results;

		// Hilangkan Reff ID
		unset($this->data['stats']['R']);
		unset($this->data['stats']['A']);
		unset($this->data['stats']['P']);
		$data['controller'] = $this;
		// $data['actid'] = $actid;
		$siteid = '';
		$actby = '';
		
		$sql = "select * from activities where actid=$actid";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['activities'] = $results;

		$data['activities'][0]['reportdate'] = date("Y-m-d H:i:s");
		$data['activities'][0]['opendate'] = date("Y-m-d H:i:s");
		$data['activities'][0]['closedate'] = null;
		$data['activities'][0]['reportfrom'] = null;
		$data['activities'][0]['subject'] = null;
		$data['activities'][0]['activitystatus'] = 'O';
		$data['activities'][0]['action'] = null;
		$data['activities'][0]['userid_owner'] = $_SESSION['userid'];
		$data['activities'][0]['userid_creator'] = $_SESSION['userid'];
		$data['activities'][0]['attachment'] = null;
		$data['actid_ref'] = $actid;

		$siteid = $results[0]['siteid'];
		$actby = $results[0]['actby'];

		$sql = "select userid, firstname, lastname from users where enddate is null order by firstname";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users'] = $results;
		
		$sql = "select siteid, enddate, sitename from sites where enddate is null order by siteid";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		
		$sql = "select * from acttype";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttype'] = $results;

		$sql = "select * from acttext";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttext'] = $results;
		
		$data['medias'] = $this->data['medias'];
		$data['actions'] = $this->data['actions'];
		$data['stats'] = $this->data['stats'];
		$data['actbys'] = $this->data['actbys'];
		
		// invtrans
		$data['purposes'] = $this->data['itx_purposes'];
		$data['conditions'] = $this->data['itx_conditions'];
		
		$sql = " SELECT u.*, c.`productname`, c.catalognumber FROM unitgroup u
			LEFT JOIN productcatalog c ON u.`catalogid`=c.`catalogid`
			WHERE c.productaliasid<>0 AND u.`enddate` IS NULL";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['unitgroup'] = $results;
		
		$sql = "SELECT p.productid, s.sitename, pc.productname, p.productnumber FROM products p
			LEFT JOIN productcatalog pc ON p.`catalogid`=pc.`catalogid`
			LEFT JOIN sites s ON s.`siteid`=p.`siteid`";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products'] = $results;
		
		$sql = "SELECT * FROM invcounters";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['invcounters'] = $results;
		
		$sql = "SELECT * FROM vendors";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['vendors'] = $results;
		
		if( $this->request->getVar('siteid') != '' ) { $siteid = $this->request->getVar('siteid');  }
		
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'subject' => 'required',
				'siteid' => 'required',
				'userid_creator' => 'required',
				'reportdate' => 'required',
				'activitystatus' => 'required',
				'actdetailid' => 'required'
			];
			$data['new_value'] = [
				'actid_ref' => $this->request->getVar('actid_ref'),
				'actby' => $this->request->getVar('actby'),
				'siteid' => $this->request->getVar('siteid'),
				'acttypeid' => $this->request->getVar('acttypeid'),
				'userid_owner' => $this->request->getVar('userid_owner'),
				'userid_creator' => $this->request->getVar('userid_creator'),
				'activitystatus' => $this->request->getVar('activitystatus'),
				'reportfrom' => $this->request->getVar('reportfrom'),
				'reportdate' => $this->request->getVar('reportdate'),
				'opendate' => $this->request->getVar('opendate'),
				'closedate' => $this->request->getVar('closedate'),
				'media' => $this->request->getVar('media'),
				'action' => $this->request->getVar('action'),
				'subject' => $this->request->getVar('subject'),
				'attachment' => $this->request->getVar('attachment'),
				'actdetailid' => $this->request->getVar('actdetailid'),
				'acttextid' => $this->request->getVar('acttextid'),
				'textvalue' => $this->request->getVar('textvalue')
			];

			$actby = $this->request->getVar('actby');
			if($actby == 'P') { 
				$data['new_value']['productid'] = $this->request->getVar('productid'); 
				$data['new_value']['swversion'] = $this->request->getVar('swversion'); 
				$data['new_value']['vendorid'] = null;
			} elseif($actby == 'V') { 
				$data['new_value']['vendorid'] = $this->request->getVar('vendorid');
				$data['new_value']['productid'] = null; 
				$data['new_value']['swversion'] = null;
			} else {
				$data['new_value']['vendorid'] = null;
				$data['new_value']['productid'] = null; 
				$data['new_value']['swversion'] = null; 
			}
				
			if($this->validate($rules)) {	
				
				// Cek apakah ada duplikasi data
				$exists = $db->table('activities')
					->where('subject', $data['new_value']['subject'])
					->where('siteid', $data['new_value']['siteid'])
					->where('reportdate', $data['new_value']['reportdate'])
					->where('opendate', $data['new_value']['opendate'])
					->where('closedate', $data['new_value']['closedate'])
					->where('userid_creator', $data['new_value']['userid_creator'])
					->get()->getRow();
				if ($exists) { // Jika ada maka Redirect
					return redirect()->to('/activities');
				}

				// Create Activities
				$activitiesModel = new ActivitiesModel();
				$activitiesModel->set('createdate', 'NOW()', FALSE);
				$activitiesModel->insert($data['new_value']);
				
				// REFF UPDATE
				if ($data['new_value']['activitystatus'] == 'C') {
					// Update field 'activitystatus' menjadi 'C' untuk actid yang REF
					$activitiesModel->update($actid, ['activitystatus' => 'C']);
				}

				// Create Activities Status Log
				$actid = $activitiesModel->getInsertID();
				$actstatus = $data['new_value']['activitystatus'];
				$userid = $data['new_value']['userid_creator'];
				$sql = "INSERT INTO actstatus_log (activityid, activitystatus, userid, logdate) 
						VALUES ($actid,'$actstatus', $userid, NOW())";
				$query = $db->query($sql);

				$acttextid = $data['new_value']['acttextid'];
				$textvalue = $data['new_value']['textvalue'];
				foreach($data['new_value']['acttextid'] as $qindex => $qacttextid) {
					$qtextvalue = $db->escapeString($textvalue[$qindex]);
					$sql = "insert into actdetail (actid, acttextid, textvalue, createdate) values ('$actid','$qacttextid', '$qtextvalue', NOW())";
					$query = $db->query($sql);
				}
				
				// act by consumables
				$actconid_delete = $this->request->getVar('actconid_delete');
				if($actconid_delete != '') {
					$actconid_del = explode(' ',$actconid_delete);
					foreach($actconid_del as $actconid) {
						$sql = "delete from actconsumables where actconid='$actconid'";
						$query = $db->query($sql);	
					}
				}
				$catalogid = $this->request->getVar('catalogid');
				if(isset($catalogid)) {
					$lotnumber = $this->request->getVar('lotnumber');
					$sql = "INSERT INTO actconsumables ( actid, catalogid, lotnumber ) VALUES ";
					foreach($catalogid as $qid => $qvalue) {
						$sql .= "( '$actid' , '". $catalogid[$qid]."', '". $lotnumber[$qid]."' ),"; 
					}
					$sql = rtrim($sql, ',');
					$query = $db->query($sql);
				}
				
				// invtrans 
				$itxid_delete = $this->request->getVar('itxid_delete');
				if($itxid_delete!='') {
					$itxid_del =explode(' ',$itxid_delete);
					foreach($itxid_del as $itxid) {
						$sql = "delete from invtrans where itxid='$itxid'";
						$query = $db->query($sql);	
					}
				}
				
				$dests = $this->request->getVar('dests');
				$origins = $this->request->getVar('origins');
				if(isset($dests)) {
					foreach($dests as $qdata) {
						$qdata = explode("|",$qdata);
						$desttype[] = $qdata[0];
						$destid[] = $qdata[1];
					}
					foreach($origins as $qdata) {
						$qdata = explode("|",$qdata);
						$origtype[] = $qdata[0];
						$origid[] = $qdata[1];
					}
					$unitgroupid = $this->request->getVar('unitgroupid');
					$lotnumber = $this->request->getVar('lotnumber');
					$qty = $this->request->getVar('qty');
					$conditions = $this->request->getVar('conditions');
					$itxdate = $this->request->getVar('itxdate');
					$purpose = $this->request->getVar('purpose');
					$sql = "INSERT INTO invtrans ( actid, desttype, destid, origtype, origid, unitgroupid, lotnumber, qty, conditions, purpose, itxdate ) VALUES ";
					foreach($origid as $qid => $qorigid) {
						$sql .= "( '$actid', '".$desttype[$qid]."', '".$destid[$qid]."', '".$origtype[$qid]."', '".$qorigid."', '".
							$unitgroupid[$qid]."', '".$lotnumber[$qid]."', '".$qty[$qid]."', '".$conditions[$qid]."', '".$purpose[$qid]."', '".$itxdate[$qid]."' ),"; 
					}
					$sql = rtrim($sql, ',');
					//echo "$sql";
					$query = $db->query($sql);
				}
				$reportdate = substr($data['new_value']['reportdate'],0,10);
				return redirect()->to('activities/?reportdate='.$reportdate);
			} else {
				$data['validation'] = $this->validator;
				return view('activities_editor',$data);
			}
		}
		$data['actid'] = $actid;
		$data['actid_ref_status'] = ''; // Khusus untuk refer
		$data['refer_page'] = true; // Khusus untuk controller refer
		return view('activities_editor',$data);

	}
	
	public function newtextarea($textareaid=null) {
		$db = \Config\Database::connect();
		$sql = "select * from acttext";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttext'] = $results;
		$data['textareaid'] = $textareaid;
		return view('activities_newtextarea', $data);
		//return $datas;
	}
	
	public function getproduct($siteid=null, $productid=null, $swversion=null){
		$db = \Config\Database::connect();
		$sql = "SELECT p.*, pc.`productname`, p.`productnumber`
			FROM products p
			LEFT JOIN productcatalog pc ON pc.`catalogid`=p.`catalogid`
			LEFT JOIN producttype pt ON pt.`producttypeid`= pc.`producttypeid`
			WHERE p.siteid=$siteid and productaliasid<>0
			ORDER BY FIELD(pt.producttypeid, 20, 19, 21, 12, 10, 14, 11, 13, 4, 3) DESC, pc.productname";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['products'] = $results;
		$data['productid'] = $productid;
		$data['swversion'] = $swversion;		
		return view('activities_getproduct', $data);
		//return $datas;
	}

	public function getvendor($vendorid=null){
		$db = \Config\Database::connect();
		$sql = "SELECT vendorid, vendorname from vendors";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['vendors'] = $results;
		$data['vendorid'] = $vendorid;
		return view('activities_getvendor', $data);
	}

	public function getconsumable($actid=null){
		$db = \Config\Database::connect();
		$sql = "SELECT c.catalogid, c.catalognumber, c.productname, v.`vendorname`
			FROM productcatalog c 
			LEFT JOIN vendors v ON v.`vendorid`=c.`vendorid`
			WHERE c.producttypeid IN (6,7) AND c.productaliasid > 0";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['consumables'] = $results;
		if($actid > 0) {
			$sql = "SELECT ac.actconid, ac.catalogid, ac.lotnumber
				FROM actconsumables ac
				where ac.actid='$actid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['actcons'] = $results;
		}
		return view('activities_getconsumable', $data);
		//return $datas;
	}
	
	public function getcontact($siteid=null){
		$db = \Config\Database::connect();
		$sql = "SELECT c.firstname, c.lastname from contacts c 
			left join sitecontact sc on sc.contactid=c.contactid
			where sc.siteid=$siteid";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$datas = '';
		foreach ($results as $data) {
			$qfirstname = $data['firstname'];
			$qlastname = $data['lastname'];
			$datas .= "<option value='$qfirstname $qlastname'>";
		}
		//return view('activities_getproduct', $datas);
		return $datas;
	}
	
	public function upload(){
		if ($this->request->getMethod() === 'POST') {
			if ( 0 < $_FILES['file']['error'] ) {
				echo 'Error: ' . $_FILES['file']['error'] . '<br>';
			}
			else {
				move_uploaded_file($_FILES['file']['tmp_name'], 'upload/' . $_FILES['file']['name'] );
			}
		}	
    }

	public function act_content($actid, $filter_email=false) { // Parameter Ke-2 Untuk Email
		$db = \Config\Database::connect();
        $sql = "select a.*, v.vendorname, v2.vendorname as vendorname_2, u.firstname, u.lastname, atyp.fulltext, atyp.acttypecode, s.sitename, pc.productname, c.firstname as cfname, c.lastname as clname, p.productnumber
        from activities a
		left join users u on a.userid_owner=u.userid
		left join acttype atyp on a.acttypeid=atyp.acttypeid
		left join sites s on a.siteid=s.siteid
		left join products p on a.productid=p.productid
		left join productcatalog pc on p.catalogid=pc.catalogid
        left join vendors v on v.vendorid=pc.vendorid
		left join vendors v2 on v2.vendorid=a.vendorid
        left join contacts c on a.contactid=c.contactid
		where actid='$actid'";

        $query = $db->query($sql);
        $result = $query->getResultArray();
        $data['activities'] = $result;
		
		if($data['activities'][0]['actby'] == 'C'){
			$sql = "SELECT c.*, p.`catalognumber`, p.`productname` FROM actconsumables c 
				LEFT JOIN productcatalog p ON p.catalogid=c.`catalogid`
				WHERE c.`actid`='$actid'";
			$query = $db->query($sql);
			$result = $query->getResultArray();
			$data['consumables'] = $result;
		}
		$data['stats'] = $this->data['stats'];

		// Filter Tidak Menampilkan Internal Note
		$filter_internalnote = $filter_email === true ? ' AND ad.acttextid NOT IN(3) ' : ' ';

		$sql = "SELECT ad.*, ate.`fulltext` AS acttextname 
			FROM actdetail ad
			LEFT JOIN acttext ate ON ate.`acttextid`=ad.`acttextid`
			WHERE ad.actid=$actid $filter_internalnote -- Filter Email
			ORDER BY CASE 
			WHEN ad.acttextid = 1 THEN 1
			WHEN ad.acttextid = 5 THEN 5
			WHEN ad.acttextid = 2 THEN 2
			WHEN ad.acttextid = 3 THEN 3
			WHEN ad.acttextid = 6 THEN 4
			WHEN ad.acttextid = 34 THEN 5
			WHEN ad.acttextid = 4 THEN 99
			ELSE 6 END";
        $query = $db->query($sql);
        $result = $query->getResultArray();
        $data['actdetail'] = $result;
		
		$data['medias'] = $this->data['medias'];

		if($data['activities'][0]['action'] != ''){
			$actions = $this->data['actions'];
			$data['activities'][0]['action'] = $actions[$data['activities'][0]['action']];
		}

		$data['itx_purposes'] = $this->data['itx_purposes'];
		
		// Filter Email Hanya Menampilkan Replace Saja ke Customers
		if ($filter_email === true){
			$sql = "SELECT pc.`catalognumber`, pc.`productname`, i.`lotnumber`, i.qty, u.unit FROM invtrans i 
				LEFT JOIN unitgroup u ON u.`unitgroupid`=i.`unitgroupid`
				LEFT JOIN productcatalog pc ON pc.`catalogid`=u.`catalogid`
				WHERE i.actid='$actid' AND i.`purpose` IN ('PR', 'PB', 'PU', 'PF')
				GROUP BY pc.`catalognumber` ORDER BY i.itxid";
		} else {
			$sql = "SELECT pc.`catalognumber`, pc.`productname`, i.`lotnumber`, i.qty, i.`purpose`, u.unit FROM invtrans i 
				LEFT JOIN unitgroup u ON u.`unitgroupid`=i.`unitgroupid`
				LEFT JOIN productcatalog pc ON pc.`catalogid`=u.`catalogid`
				WHERE i.actid='$actid'";
		}

		$query = $db->query($sql);
        $result = $query->getResultArray();
        $data['invtrans'] = $result;

		return view('activities_content', $data);
	}
	
	public function detail($actid){
		$data['content'] = $this->act_content($actid);

		$db = \Config\Database::connect();
        $sql = "select attachment from activities where actid='$actid'";
        $query = $db->query($sql);
        $result = $query->getResultArray();
		$data['attachment'] = $result[0];
		
		$sql = "SELECT * FROM actsend_log where actid='$actid' order by logdate";
        $query = $db->query($sql);
        $result = $query->getResultArray();
        $data['actsend_log'] = $result;
		
		return view('activities_detail', $data);
	}
	
	public function servicereport($actid){
		$db = \Config\Database::connect();
		$data['actid'] = $actid;
		
        $sql = "select a.*, v.vendorname, v2.vendorname as vendorname_2, u.firstname, u.lastname, atyp.fulltext, 
			atyp.acttypecode, s.sitename, pc.productname, c.firstname as cfname, c.lastname as clname, p.productnumber
        from activities a
		left join users u on a.userid_owner=u.userid
		left join acttype atyp on a.acttypeid=atyp.acttypeid
		left join sites s on a.siteid=s.siteid
		left join products p on a.productid=p.productid
		left join productcatalog pc on p.catalogid=pc.catalogid
        left join vendors v on v.vendorid=pc.vendorid
		left join vendors v2 on v2.vendorid=a.vendorid
        left join contacts c on a.contactid=c.contactid
		where actid='$actid'";
        $query = $db->query($sql);
        $result = $query->getResultArray();
        $data['activities'] = $result;
		
		$sql = "SELECT ad.*, ate.`fulltext` AS acttextname 
			FROM actdetail ad
			LEFT JOIN acttext ate ON ate.`acttextid`=ad.`acttextid`
			WHERE ad.actid=$actid
			ORDER BY CASE 
			WHEN ad.acttextid = 1 THEN 1
			WHEN ad.acttextid = 5 THEN 5
			WHEN ad.acttextid = 2 THEN 2
			WHEN ad.acttextid = 3 THEN 3
			WHEN ad.acttextid = 6 THEN 4
			WHEN ad.acttextid = 34 THEN 5
			WHEN ad.acttextid = 4 THEN 99
			ELSE 6 END";
        $query = $db->query($sql);
        $result = $query->getResultArray();
        $data['actdetails'] = $result;
		
		$sql = "SELECT pc.`catalognumber`, pc.`productname`, i.`lotnumber`, i.qty, u.unit, i.purpose FROM invtrans i 
				LEFT JOIN unitgroup u ON u.`unitgroupid`=i.`unitgroupid`
				LEFT JOIN productcatalog pc ON pc.`catalogid`=u.`catalogid`
				WHERE i.actid='$actid' AND i.`purpose` IN ('PR', 'PB', 'PU', 'PF')
				GROUP BY pc.`catalognumber` ORDER BY i.itxid";
		$query = $db->query($sql);
        $result = $query->getResultArray();
        $data['invtrans'] = $result;
		
		$data['purposes'] = $this->data['itx_purposes'];
		
		return view('activities_servicereport', $data);
	}
	
	public function count(){
		$db = \Config\Database::connect();
		$opendate = date("Y-m-01");
		$closedate = date("Y-m-d");
		$pos = '';
		if ($this->request->getMethod() === 'POST') {
			$opendate = $this->request->getPost('opendate');
			$closedate = $this->request->getPost('closedate');
			$pos = $this->request->getPost('pos');
			$sql_pos = '';
			$sql_dept = '';

			if($pos == 'TSO') { $sql_dept = 'AND u.userdeptid = 1';}
			elseif($pos == 'IVD') { $sql_dept = 'AND u.userdeptid = 1'; $sql_pos = 'AND u.userposid in (1,2,4)'; }
			elseif($pos == 'IVDR') {$sql_dept = 'AND u.userdeptid = 1'; $sql_pos = 'AND u.userposid in (1,2,4) AND (u.userid = 2 OR u.reportto = 2)'; } //Timur
			elseif($pos == 'IVDH') {$sql_dept = 'AND u.userdeptid = 1'; $sql_pos = 'AND u.userposid in (1,2,4) AND (u.userid = 10 OR u.reportto = 10)'; } //Tengah
			elseif($pos == 'IVDT') {$sql_dept = 'AND u.userdeptid = 1'; $sql_pos = 'AND u.userposid in (1,2,4) AND (u.userid = 3 OR u.reportto = 3)'; } //Barat
			elseif($pos == 'IT') {$sql_dept = 'AND u.userdeptid = 1'; $sql_pos = 'AND u.userposid in (1,3,5)'; }
			elseif($pos == 'PS') {$sql_dept = 'AND u.userdeptid = 2'; $sql_pos = 'AND u.userposid in (6,14)'; }
			elseif($pos == 'MT') {$sql_dept = 'AND u.userdeptid = 2'; $sql_pos = 'AND u.userposid in (6,14)'; }

			$sql = "SELECT u.firstname, u.lastname, u.userdeptid, u.userid, u.userposid,
			SUM(CASE WHEN aty.acttypecode='CR' THEN 1 ELSE 0 END) AS CR,
			SUM(CASE WHEN aty.acttypecode='IR' THEN 1 ELSE 0 END) AS IR,
			SUM(CASE WHEN aty.acttypecode='MN' THEN 1 ELSE 0 END) AS MN,
			SUM(CASE WHEN aty.acttypecode='SP' THEN 1 ELSE 0 END) AS SP,
			SUM(CASE WHEN aty.acttypecode='PR' THEN 1 ELSE 0 END) AS PR,
			SUM(CASE WHEN aty.acttypecode='RF' THEN 1 ELSE 0 END) AS RF,
			SUM(CASE WHEN aty.acttypecode='TR' THEN 1 ELSE 0 END) AS TR,
			COUNT(a.actid) AS total
			FROM users u
			LEFT JOIN activities a ON u.userid = a.userid_owner AND a.closedate BETWEEN '$opendate 00:00:00' AND '$closedate 23:59:59'
			LEFT JOIN acttype aty ON aty.acttypeid = a.acttypeid
			WHERE
			a.activitystatus LIKE 'C' AND ( u.enddate is null OR u.enddate < a.opendate )
			$sql_dept 
			$sql_pos
			GROUP BY u.userid, u.firstname, u.lastname
			ORDER BY total DESC, u.firstname";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['count'] = $results;
			
        }
		$data['opendate'] = $opendate;
		$data['closedate'] = $closedate;
		$data['userpos'] = $this->data['userpos'];
		$data['pos'] = $pos;
		return view('activities_count', $data);
	}

	public function savesend(){
		if($this->request->getPost('product') == ''){
			$productid = '';
			$productnumber = '';
		} elseif($this->request->getPost('product') != ''){
			$productid = strtok(($this->request->getPost('product')), '|');
			$productnumber = substr(($this->request->getPost('product')), strpos(($this->request->getPost('product')), "|") + 1);
		}

		$data['activities'] = [
			'ref_actid' => $this->request->getPost('refer'),
			'acttypeid' => strtok($this->request->getPost('type'), '|'),
			'subject' => $this->request->getPost('subject'),
			'productid' => $productid,
			'siteid' => $this->request->getPost('site'),
			'contactid' => $this->request->getPost('report'),
			'media' => $this->request->getPost('media'),
			// 'contractid' => $this->request->getPost('contractid'),
			'productnumber' => $productnumber,
			'softwareversion' => $this->request->getPost('softwareversion'),
			// 'department' => $this->request->getPost('department'),
			'userid' => $this->request->getPost('owner'),
			'creator_userid' => $this->request->getPost('owner'),
			'reportdate' => str_replace("T"," ",($this->request->getPost('reportdate'))),
			'startdate' => str_replace("T"," ",($this->request->getPost('open'))),
			'enddate' => str_replace("T"," ",($this->request->getPost('close'))),
			'activitystatus' => $this->request->getPost('status'),
			'attachment' => $this->request->getPost('attachment'),
		];

		$model = new ActivitiesModel();
		$model->save($data['activities']);
		$actid = $model->insertID;
        $siteid = $this->request->getPost('site');

		$createdate = date("Y-m-d h:i", time());
		$data['actdetail'] = [
			'actid' => $actid,
			'acttextid' => $this->request->getPost('acttextid'),
			'detail' => $this->request->getPost('detail'),
			'solution' => $this->request->getPost('solution'),
			'suggestion' => $this->request->getPost('suggestion'),
			'createdate' => $createdate,
		];
		
		$model = new ActdetailModel();
		$model->save($data['actdetail']);
		
		return redirect()->to('/activities/compose/'.$actid.'/'.$siteid);
	}
	
	public function email_compose($actid){
		function cleanmail ($data) {
			$data = implode(",",$data);
			$data = explode(",",$data);
			$data = array_unique($data);
			return $data;
		}
		
		$db = \Config\Database::connect();
		$userid = $_SESSION['userid'];
		$data['content'] = $this->act_content($actid, true);
		
		$sql = "SELECT u.`firstname`, u.`lastname`, o.`offaddress`, o.`offphone`, u.email_1 FROM users u
			LEFT JOIN offices o ON u.`offid`=o.`offid`
			where u.userid='$userid'";
        $query = $db->query($sql);
        $result = $query->getResultArray();
		$data['userinfo'] = $result[0];
		
		$sql = "select subject, attachment,siteid from activities where actid='$actid'";
        $query = $db->query($sql);
        $result = $query->getResultArray();
		$data['attachment'] = $result[0]['attachment'];
		$data['subject'] = $result[0]['subject'];
		$siteid = $result[0]['siteid'];
		
		$data['replyto'] = $_SESSION['email'];
		
		$sql = "select mailgroupname, mailgrouptext from mailgroups";
        $query = $db->query($sql);
        $result = $query->getResultArray();
        $data['mailgroups'] = $result;
		
		$sql = "SELECT contactemail FROM sitecontact WHERE siteid='$siteid' and enddate is null";
        $query = $db->query($sql);
        $result = $query->getResultArray();
        $data['sitecontact'] = $result;
		
      	$sql = "select contactemail as email from sitecontact where siteid = '$siteid' and enddate is null
			UNION SELECT distinct email_1 as emails FROM users WHERE `enddate` IS NULL 
			UNION SELECT email_2 FROM users WHERE `enddate` IS NULL
			UNION SELECT email_1 FROM contacts WHERE `enddate` IS NULL
			UNION SELECT email_2 FROM contacts WHERE `enddate` IS NULL
			UNION SELECT email from emails WHERE enddate IS NULL";
        $query = $db->query($sql);
        $result = $query->getResultArray();
		foreach ($result as $ping) { 
			$data['emails'][] = $ping['email'];
		}
		$data['emails'] = array_unique($data['emails']);
		$data['emails'] = array_filter($data['emails']);
		
		if ($this->request->getMethod() === 'POST') {

			// $check = $db->query("SELECT sendmail FROM activities WHERE actid='$actid'")->getRow();
			// if ($check && $check->sendmail == '1') {
			// 	return redirect()->to('activities/')->with('error', 'Email Sudah Pernah Dikirim');
			// }

			$email = \Config\Services::email();
			$sql = "update activities set sendmail='1' where actid='$actid'";
			$query = $db->query($sql);
			
			$replyto = $this->request->getVar('replyto');
			$to = $this->request->getVar('to');
			$cc =  $this->request->getVar('cc');
			$bcc = $this->request->getVar('bcc');
			$subject = $this->request->getVar('subject');
			$message = $this->request->getVar('message');
			$attachment = $this->request->getVar('attachment');
			$attachments = explode(',',$attachment);

			/*
			$email->setFrom('noreply@services.summit.co.id', 'SUMMIT CRM');
			$email->setReplyTo($replyto);
			$email->setTo(cleanmail($to));
			if($cc != '') { $email->setCC(cleanmail($cc)); }
			if($bcc != '') { $email->setBCC(cleanmail($bcc)); }
			$email->setSubject($subject);
			$email->setMessage($message);
			foreach($attachments as $attachment) {
				if($attachment != '') {
					$attachment = FCPATH."/upload/".$attachment;					
					$email->attach($attachment);
				}
			}
			//$email->set_newline("\r\n");
			//$email->send();
			# debugging email CI4
			//$email->send(FALSE);
			$myfile = fopen("log.txt", "a+") or die("Unable to open file!");
			if ( $email->send(FALSE) ) {
				fwrite($myfile, "\nemail sent success");
			} else {
				fwrite($myfile, "\n".$email->printDebugger() );
			}
			fclose($myfile);
			*/
			$tos = join(",",$to);
			if(isset($cc)) { $ccs = join(",",$cc); } else { $ccs = ''; }
			if(isset($bcc)) { $bccs = join(",",$bcc); } else { $bccs = ''; }
			$sql = "INSERT into actsend_log (actid, replyto, emailto, emailcc, emailbcc, logdate) values ( '$actid', '$replyto', '$tos', '$ccs', '$bccs', NOW() )";
			$query = $db->query($sql);

			// Untuk Simpan Email Otomatis
			$this->syncEmails($tos, $ccs, $bccs);

			$data = [
				'replyto' => $replyto,	
				'to' => $tos,
				'cc' => $ccs,
				'bcc' => $bccs,
				'subject' => $subject,
				'message' => $message,
				'attachment' => $attachment,
			];
			$jsonData = json_encode($data);
			//print_r($jsonData);
			//$url = 'http://localhost/work/phpmailer/server.php';
			$url = 'https://sadewa.services-summit.my.id/server.php';
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
			curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$response = curl_exec($ch);
			if(curl_errno($ch)) { echo 'Curl error: '.curl_error($ch); }
			//echo "sending email";
			//echo "$jsonData <br/>";
			//echo "<pre>$response</pre>";
			curl_close($ch);
			/*
			$myfile = fopen("log.txt", "a+") or die("Unable to open file!");
			fwrite($myfile,$response);
			fclose($myfile);
			*/
			// if ($response) {
			// 	$db->query("UPDATE activities SET sendmail='1' WHERE actid='$actid'");
			// }
			return redirect()->to('activities/');
		} else {
			return view('activities_compose', $data);
		}
	}

	// Untuk Simpan Email Otomatis
	public function syncEmails($tos="", $ccs="", $bccs="") {
		$db = \Config\Database::connect();
		
		// Khusus Untuk Simpan email yg dimasukkan 
		$allEmails = $tos .",". $ccs .",". $bccs;
		// pecah jadi array
		$emailArr = array_filter(array_map('trim', explode(',', $allEmails)));
		// optional: lowercase biar konsisten
		$emailArr = array_map('strtolower', $emailArr);
		// buang duplikat di request
		$emailArr = array_unique($emailArr);

		// GUARD CLAUSE (WAJIB)
		if (empty($emailArr)) {
			return;
		}

		// CEK email
		$placeholders = implode(',', array_fill(0, count($emailArr), '?'));
		$sql = "SELECT email FROM emails WHERE email IN ($placeholders)";
		$query = $db->query($sql, array_values($emailArr));
		$existingEmails = array_column($query->getResultArray(), 'email');
		$newEmails = array_diff($emailArr, $existingEmails);

		if (!empty($newEmails)) {
			$values = [];
			$binds  = [];

			foreach ($newEmails as $email) {
				$values[] = "(?, NULL)";
				$binds[]  = $email;
			}
			$sql = "INSERT INTO emails (email, enddate) VALUES " . implode(',', $values);
			$db->query($sql, $binds);
		}
	}
	
	public function export(){
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM sites";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		
		$sql = "SELECT * FROM users";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users'] = $results;
		
		$sql = "select * from acttype";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttype'] = $results;
		
		if($opendate = $this->request->getPost('opendate') == ''){
			$opendate = date("Y-m-01");
		} else {
			$opendate = $this->request->getPost('opendate'); 
		}
		if($closedate = $this->request->getPost('closedate') == ''){
			$closedate = date("Y-m-d");
		} else {
			$closedate = $this->request->getPost('closedate');
		}
		
		$data['opendate'] = $opendate;
		$data['closedate'] = $closedate;
		$data['exports'] = $this->data['exports'];

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

			if($opendate = $this->request->getPost('opendate') == ''){
				$opendate = date("Y-m-01");
			} else {
				$opendate = $this->request->getPost('opendate'); 
			}
			if($closedate = $this->request->getPost('closedate') == ''){
				$closedate = date("Y-m-d");
			} else {
				$closedate = $this->request->getPost('closedate');
			}
	
			$data['opendate'] = $opendate;
			$data['closedate'] = $closedate;
	
			$filterquery = '';
	
			$siteid = $this->request->getPost('siteid');
			if ($this->request->getPost('productid') !== null) {
				$productid = $this->request->getPost('productid');
			} else {
				$productid = "";
			}
			$acttypeid = $this->request->getPost('acttypeid');
			$userid_owner = $this->request->getPost('userid_owner');
	
			if($siteid != ''){
				$filterquery .= "and act.siteid = '$siteid'";
			}
			if($productid != ''){
				$filterquery .= "and act.productid = '$productid'";
			}
			if($acttypeid != ''){
				$filterquery .= "and act.acttypeid = '$acttypeid'";
			}
			if($userid_owner != ''){
				$filterquery .= "and act.userid_owner = '$userid_owner'";
			}
	
			$sql = "select atyp.fulltext, u.firstname, u.lastname, act.subject, act.actid, act.actid_ref, act.acttypeid, act.userid_owner, act.media, act.siteid, s.sitename, 
				act.contactid, act.opendate, act.closedate, act.reportdate, act.productid, act.activitystatus, pc.productname, p.productnumber, act.reportfrom,
				act.swversion, act.action, act.actby
				from activities act
				left join users u on act.userid_owner=u.userid
				left join sites s on act.siteid=s.siteid
				left join acttype atyp on act.acttypeid=atyp.acttypeid
				left join products p on act.productid=p.productid
				left join productcatalog pc on p.catalogid=pc.catalogid
				WHERE act.opendate between '$opendate 00:00:00' and '$closedate 23:59:59' and act.activitystatus='C' $filterquery";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['export'] = $results;

			foreach ( $data['export'] as $cdata ) {
				$actid =  $cdata['actid'];
				$sql = "SELECT c.*, p.`catalognumber`, p.`productname` FROM actconsumables c 
				LEFT JOIN productcatalog p ON p.catalogid=c.`catalogid`
				WHERE c.`actid`='$actid'";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				$data['consumables'][$actid] = $results;
			}

			foreach ( $data['export'] as $qdata ) {
				$actid =  $qdata['actid'];
				$sql = "SELECT ad.actid, ad.createdate, ate.`fulltext`, ad.`textvalue` FROM actdetail ad
				LEFT JOIN acttext ate ON ad.`acttextid`=ate.`acttextid`
				WHERE ad.actid in ($actid)
				ORDER BY ad.acttextid, ad.`createdate`";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				$data['actdetails'][$actid] = $results;
			}

			foreach ( $data['export'] as $idata ) {
				$actid =  $idata['actid'];
				$sql = "SELECT pc.`catalognumber`, pc.`productname`, i.`lotnumber`, i.qty, u.unit FROM invtrans i 
						LEFT JOIN unitgroup u ON u.`unitgroupid`=i.`unitgroupid`
						LEFT JOIN productcatalog pc ON pc.`catalogid`=u.`catalogid`
					where i.actid='$actid'";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				$data['invtrans'][$actid] = $results;
			}

			if ($this->request->getPost('export') == 'E') { // Pilih Excel
				return view('activities_export_excel', $data);
			} else if ($this->request->getPost('export') == 'P') { // Pilih PDF
				return view('activities_export_pdf', $data);
			}
			
		}
		return view('activities_export', $data);
	}
	
	// Suspend
	public function suspend($actid=null) {

		$db = \Config\Database::connect();
		$tb_activities = $db->table('activities');
		$tb_activities = $tb_activities->select('activitystatus')->where('actid', $actid)->get()->getRowArray();

		if ($tb_activities['activitystatus'] == 'S') {
			$actstatus_new = "O";
		} else if ($tb_activities['activitystatus'] == 'O') {
			$actstatus_new = "S";
		} else {
			$actstatus_new = "S";
		}

		// Update Table Activities
        $sql = "UPDATE activities SET activitystatus = '$actstatus_new'  WHERE actid = $actid";
        $db->query($sql);
		
		$userid =  session()->get('userid');
		// Create Activities Status Log
		$sql = "INSERT INTO actstatus_log (activityid, activitystatus, userid, logdate) 
				VALUES ($actid,'$actstatus_new', $userid, NOW())";
		$query = $db->query($sql);
        
		return redirect()->to('activities/');
	}
	
	public function disable($actid=null) {

		$db = \Config\Database::connect();
		$tb_activities = $db->table('activities');
		$tb_activities = $tb_activities->select('activitystatus')->where('actid', $actid)->get()->getRowArray();

		if ($tb_activities['activitystatus'] == 'D') {
			$actstatus_new = "O";
		} else if ($tb_activities['activitystatus'] == 'O') {
			$actstatus_new = "D";
		} else {
			$actstatus_new = "D";
		}

		// Update Table Activities
        $sql = "UPDATE activities SET activitystatus = '$actstatus_new'  WHERE actid = $actid";
        $db->query($sql);
		
		$userid =  session()->get('userid');
		// Create Activities Status Log
		$sql = "INSERT INTO actstatus_log (activityid, activitystatus, userid, logdate) 
				VALUES ($actid,'$actstatus_new', $userid, NOW())";
		$query = $db->query($sql);
        
		return redirect()->to('activities/');
	}

	// public function delete($actid=null) {
	// 	$db = \Config\Database::connect();
    //     $sql = "delete from activities where actid=$actid";
    //     $db->query($sql);
    //     $sql = "delete from actdetail where actid=$actid";
    //     $db->query($sql);
	// 	$sql = "delete from actstatus_log where activityid=$actid";
    //     $db->query($sql);
	// 	return redirect()->to('activities/');
	// }
	
	/* invtrans index */
	public function invtrans_index() {
		$data = array();
		$date1 = date('Y-m-01');
		$date2 = date('Y-m-t');
		if ($this->request->getMethod() === 'POST') {
			$date1 =  $this->request->getPost('date1') ;
			$date2 =  $this->request->getPost('date2') ;
			$db = \Config\Database::connect();
			$sql = "SELECT a.actid, a.subject, CONCAT(us.firstname, ' ', us.lastname) as username, c.`catalognumber`, c.productname, itx.qty, u.unit, itx.lotnumber,
				#origin
				CASE 
				  WHEN origtype='C' THEN (SELECT CONCAT('Counter ',counternumber,' | ',countername) FROM invcounters WHERE counterid=itx.origid)
				  WHEN origtype='V' THEN (SELECT CONCAT('Vendor ',vendorname) FROM vendors WHERE vendorid=itx.origid)
				  WHEN origtype='P' THEN (
					SELECT CONCAT(s.sitename, ' - ', c.productname, ' (', p.productnumber, ')' )
					FROM products p 
					  LEFT JOIN sites s ON p.siteid=s.siteid
					  LEFT JOIN productcatalog c ON c.catalogid=p.catalogid
					WHERE p.productid=itx.origid
				  )
				END AS origin,
				#dest
				CASE 
				  WHEN desttype='C' THEN (SELECT CONCAT('Counter ',counternumber,' | ',countername) FROM invcounters WHERE counterid=itx.destid)
				  WHEN desttype='V' THEN (SELECT CONCAT('Vendor ',vendorname) FROM vendors WHERE vendorid=itx.destid)
				  WHEN desttype='P' THEN (
					SELECT CONCAT(s.sitename, ' - ', c.productname, ' (', p.productnumber, ')' )
					FROM products p 
					  LEFT JOIN sites s ON p.siteid=s.siteid
					  LEFT JOIN productcatalog c ON c.catalogid=p.catalogid
					WHERE p.productid=itx.destid
				  )
				END AS dest
				FROM invtrans itx
				LEFT JOIN activities a ON itx.`actid`=a.actid
				LEFT JOIN unitgroup u ON itx.`unitgroupid`=u.`unitgroupid`
				LEFT JOIN productcatalog c ON c.`catalogid`=u.`catalogid`
				LEFT JOIN users us ON us.userid=a.userid_owner
				WHERE itx.itxdate BETWEEN '$date1 00:00' AND '$date2 23:59'
				ORDER BY a.`actid`";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['invtrans'] = $results;
		}
		$data['date1']=$date1;
		$data['date2']=$date2;
		
		return view('invtrans_index', $data);
	}
}