<?php

namespace App\Controllers;

use App\Models\InvTransModel;
use CodeIgniter\Controller;

class InvTrans extends BaseController {
	protected array $data;

	function __construct() {
		$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 view_itd($itdid=null) {
		$db = \Config\Database::connect();
		$sql ="SELECT itd.itdid, itd.subject, 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 unitgroup u ON itx.`unitgroupid`=u.`unitgroupid`
		LEFT JOIN productcatalog c ON c.`catalogid`=u.`catalogid`
		LEFT JOIN invtransdata itd ON itd.itdid=itx.itdid
		WHERE itd.itdid='$itdid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['invtrans'] = $results;
		$data['itdid'] = $itdid;
		$data['subject'] = $results[0]['subject'];
		return view('invtrans_view', $data);
	}
	
	public function view_act($actid=null) {
		$db = \Config\Database::connect();
		$sql ="SELECT a.actid, a.subject, 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`
		WHERE a.actid='$actid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['invtrans'] = $results;
		$data['actid'] = $actid;
		$data['subject'] = $results[0]['subject'];
		return view('invtrans_view', $data);
	}
	
	public function edit($itdid=null) {
		$db = \Config\Database::connect();
		$data['itdid'] = $itdid;
		if($itdid != 0) {
			$sql = "select * from invtrans where itdid='$itdid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['invtrans'] = $results;
			
			$sql = "select * from invtransdata where itdid='$itdid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['itd'] = $results;
		}
		// 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 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->getMethod() === 'POST') {
			$subject = $this->request->getVar('subject');
			if($itdid == 0) {
				$userid = $_SESSION['userid'];
				$sql = "insert into invtransdata(subject, itddate, userid) VALUES (". $db->escape($subject). ", NOW(), '$userid')";
				$query = $db->query($sql);
				$itdid = $db->insertID();
			} else {
				$sql = "update invtransdata set subject=".$db->escape($subject)." where itdid='$itdid'";
				$query = $db->query($sql);
			}
			$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 ( itdid, desttype, destid, origtype, origid, unitgroupid, lotnumber, qty, conditions, purpose, itxdate ) VALUES ";
				foreach($origid as $qid => $qorigid) {
					$sql .= "( '$itdid', '".$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);
			}
			return view('form_success');
		}
		return view('invtrans_editor', $data);
	}
	
	public function index_user($userid=null) {
		$data = array();
		$data['date1'] = date('Y-m-01');
		$data['date2'] = date('Y-m-t');
		$db = \Config\Database::connect();
		if ($this->request->getMethod() === 'POST') {
			$date1 = $this->request->getVar('date1');
			$date2 = $this->request->getVar('date2');
			$data['date1'] = $date1;
			$data['date2'] = $date2;
			$sql = "SELECT itdid, `subject` FROM invtransdata WHERE userid='$userid' and itddate between '$date1' and '$date2'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['invtrans_itd'] = $results;
			$sql = "select distinct i.actid, a.`subject` from invtrans i
				left join activities a on a.`actid`=i.`actid`
				where a.userid_owner='$userid' and a.opendate between '$date1' and '$date2'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['invtrans_act'] = $results;
		}
		return view('invtrans_indexuser', $data);
	}
	
	public function approve($itxid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT itx.*, u.firstname, u.lastname,
			CASE
				WHEN itx.desttype='P' THEN CONCAT(s.sitename, ' - ', pc.`productname`, '(',p.`productnumber`,')')
				WHEN itx.desttype='V' THEN CONCAT(v.initial,' - ',v.vendorname)
			END AS dest
			FROM invtransactions itx
			LEFT JOIN users u ON itx.`userid`=u.`userid`
			LEFT JOIN products p ON itx.desttype='P' AND itx.`destid`=p.`productid`
				LEFT JOIN productcatalog pc ON pc.`catalogid`=p.`catalogid`
				LEFT JOIN sites s ON s.`siteid`=p.`siteid`
			LEFT JOIN vendors v ON itx.desttype='V' AND itx.destid=v.vendorid
			WHERE itx.itxid='$itxid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$results[0]['purpose'] = $this->data['purposes'][$results[0]['purpose']];
		$data['itx'] = $results;
		$sql ="SELECT itd.*,
			CASE
				WHEN itd.origintype='P' THEN CONCAT(s.sitename, ' - ', pc.`productname`, '(',p.`productnumber`,')')
				WHEN itd.origintype='V' THEN CONCAT(v.initial,' - ',v.vendorname)
				WHEN itd.origintype='C' THEN CONCAT('Counter ', c.counternumber,' - ',c.countername)
			END AS origin, px.catalognumber, px.productname
			FROM invtransdetail itd
			LEFT JOIN productcatalog px ON itd.catalogid=px.catalogid
			LEFT JOIN products p ON itd.origintype='P' AND itd.originid=p.`productid`
				LEFT JOIN productcatalog pc ON pc.`catalogid`=p.`catalogid`
				LEFT JOIN sites s ON s.`siteid`=p.`siteid`
			LEFT JOIN vendors v ON itd.origintype='V' AND itd.originid=v.vendorid
			LEFT JOIN invcounters c ON itd.origintype='C' AND itd.originid=c.counterid
			WHERE itd.itxid=$itxid";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['itd'] = $results;
		$data['conditions'] = $this->data['conditions'];
		return view('invtransactions_approve', $data);
	}
	
	public function reportusage($userid=null) {
		$data = array();
		$data['date1'] = date('Y-m-01');
		$data['date2'] = date('Y-m-t');
		$db = \Config\Database::connect();
		if ($this->request->getMethod() === 'POST') {
			$date1 = $this->request->getVar('date1');
			$date2 = $this->request->getVar('date2');
			$data['date1'] = $date1;
			$data['date2'] = $date2;
			$sql = "SELECT v.`vendorname`, ar.`areaname`, s.`sitename`, p.productnumber, pc.`catalognumber`, pc.`productname`, itx.`qty`, ug.`baseunit`, itx.`itxdate`
				FROM invtrans itx
				LEFT JOIN unitgroup ug ON ug.`unitgroupid`=itx.`unitgroupid` 
				LEFT JOIN productcatalog pc ON pc.`catalogid`=ug.`catalogid`
				LEFT JOIN vendors v ON v.`vendorid`=pc.`vendorid`
				LEFT JOIN products p ON p.`productid`=itx.`destid`
				LEFT JOIN sites s ON p.`siteid`=s.`siteid`
				LEFT JOIN accounts a ON a.`accountid`=s.`accountid`
				LEFT JOIN areazone az ON az.zoneid=a.`zoneid`
				LEFT JOIN areas ar ON ar.`areaid`=az.`areaid`
				WHERE itx.itxdate BETWEEN '$date1 00:00' AND '$date2 23:59' 
				AND itx.desttype='P'
				ORDER BY itx.actid";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['usage'] = $results;
		}
		return view('invtrans_reportusage', $data);
	}
}