<?php

namespace App\Controllers;

use App\Models\SitesModel;
use App\Models\SitesLogModel;

class Sites extends BaseController {

	// CONTACTS dan SITES
	public function index() {

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

			$db = \Config\Database::connect();
			
			$sitename = strtolower($this->request->getVar('sitename'));
			
			$data['sitename'] = $sitename;
			$sql = "SELECT distinct * FROM sites st 
					LEFT JOIN accounts ac ON ac.accountid=st.accountid where st.enddate is null";
			if($sitename != '') { $sql .= " and lower(st.sitename) like '%$sitename%' "; }
			
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['sites'] = $results;
			return view('sites_index', $data);
		}
		
		return view('sites_index');
	}
	
	public function view($siteid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT s.`siteid`, s.`sitename`, a.`accountname`, a.`initial`,
			concat(u.`firstname`,' ',u.lastname) as marketing, s.createdate
			FROM sites s 
			LEFT JOIN accounts a ON a.`accountid`=s.`accountid`
			LEFT JOIN users u ON u.`userid`=s.`userid`
			WHERE s.siteid='$siteid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		$db = \Config\Database::connect();
		$sql = "SELECT sitelogid, user, userstartdate, userenddate from sites_log where siteid='$siteid' ORDER BY sitelogid DESC;";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites_log'] = $results;
		
		return view('sites_view', $data);
	}
	
	public function edit($siteid = null) {

		$db = \Config\Database::connect();
		
		if($siteid != 0) {
			$sql = "SELECT siteid, sitename, s.userid, accountid, CONCAT(u.`firstname`,' ',u.`lastname`) AS username, userstartdate FROM sites s
				LEFT JOIN users u ON u.userid=s.`userid`
				WHERE siteid='$siteid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['sites'] = $results;
		}

		//$sql = "SELECT accountid, accountname FROM accounts WHERE parentaccount='0'";
		$sql = "SELECT accountid, accountname, initial FROM accounts";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['accounts'] = $results;

		$sql = "SELECT userid, firstname, lastname FROM users WHERE userdeptid='2'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users'] = $results;

		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'siteid' => 'required',
				'sitename' => 'required',
				'accountid' => 'required',
				'userid' => 'required',
			];
			$data['new_value'] = [
				'siteid' => $this->request->getVar('siteid'),
				'sitename' => $this->request->getVar('sitename'),
				'accountid'  => $this->request->getVar('accountid'),
				'userid'  => $this->request->getVar('userid'),
				'userstartdate' => $this->request->getVar('startdate'),
			];
			
			if($this->validate($rules)){
			
				// User yang sudah ada
				if($siteid != 0) {

					// Get Log_Users
					$sql = "SELECT sitelogid, siteid FROM sites_log WHERE siteid=$siteid ORDER BY sitelogid DESC LIMIT 1";
					$query = $db->query($sql);
					$results = $query->getResultArray();
					
					if($results != null){

						// Update Site
						$sitesModel = new SitesModel();
						$sitesModel->update($siteid, $data['new_value']);

						// Update Site Logs Sebelumnya
						$sitelogid = $results[0]['sitelogid'];
						$userstartdate = $this->request->getVar('startdate');
						$data['log_sites'] = [
							'userenddate' => $userstartdate
						];
						$sitesLogModel= new SitesLogModel();
						$sitesLogModel->update($sitelogid, $data['log_sites']);

						// Insert Data Baru Site Log
						$userid  = $this->request->getVar('userid');
						// Get Full Name Form User
						$sql = "SELECT CONCAT(firstname, ' ', lastname) as fullname FROM users WHERE userid = $userid";
						$query = $db->query($sql);
						$results = $query->getResultArray();
						$username = $results[0]['fullname'];
						// Insert Data For Sites Log
						$data['log_sites'] = [
							'siteid' => $siteid,
							'user' => $username,
							'userstartdate' => $userstartdate
						];
						$sitesLogModel = new SitesLogModel();
						$sitesLogModel->set('createdate', 'NOW()', FALSE);
						$sitesLogModel->insert($data['log_sites']);
					
					// Kondisi Awal Ketika Sites Sudah Ada Namun Sites_Log Belum Ada
					} else {

						$userstartdate = $this->request->getVar('startdate');

						// Insert Data Baru Site Log
						$userid  = $this->request->getVar('userid');

						// Get Full Name Form User
						$sql = "SELECT CONCAT(firstname, ' ', lastname) as fullname FROM users WHERE userid = $userid";
						$query = $db->query($sql);
						$results = $query->getResultArray();
						$username = $results[0]['fullname'];

						$data['new_log_sites'] = [
							'siteid' => $siteid,
							'user' => $username,
							'userstartdate' => $userstartdate
						];

						$sitesLogModel = new SitesLogModel();
						$sitesLogModel->set('createdate', 'NOW()', FALSE);
						$sitesLogModel->insert($data['new_log_sites']);

						// Update Site
						$sitesModel = new SitesModel();
						$sitesModel->update($siteid, $data['new_value']);

					}

					return view('form_success');
				
				// User Baru/Fresh
				} else {			

					// Input ke sites
					$sitesModel = new SitesModel();
					$sitesModel->set('createdate', 'NOW()', FALSE);
					$sitesModel->insert($data['new_value']);
					
					// Get Last ID 
					$site_id = $sitesModel->getInsertID();
					// Get Last Data Form Sites
					$sql = "SELECT * FROM sites WHERE siteid=$site_id";
					$query = $db->query($sql);
					$results = $query->getResultArray();
					$site_id = $results[0]['siteid'];
					$userid = $results[0]['userid'];
					$userstartdate = $results[0]['userstartdate'];

					// Kondisi untuk form marketing jika diisi
					if ($userid != 0) {	
						// Get Full Name Form User
						$sql = "SELECT CONCAT(firstname, ' ', lastname) as fullname FROM users WHERE userid = $userid";
						$query = $db->query($sql);
						$results = $query->getResultArray();
						$username = $results[0]['fullname'];

						// Insert Data For Sites Log
						$data['log_sites'] = [
							'siteid' => $site_id,
							'user' => $username,
							'userstartdate' => $userstartdate
						];
						$sitesLogModel = new SitesLogModel();
						$sitesLogModel->set('createdate', 'NOW()', FALSE);
						$sitesLogModel->insert($data['log_sites']);
					}
					return view('form_success');
				}
			} else {
				$data['validation'] = $this->validator;
				return view('sites_editor',$data);
			}
		}

		$data['siteid']= $siteid;
		return view('sites_editor', $data);
	}

	public function toggle($siteid = 0) {
		$db = \Config\Database::connect();
		$sql = "update sites set enddate=
				case when enddate is not null then null
				else NOW()
				end
			where siteid='$siteid'";
		if($db->query($sql)) { return view('form_success'); } 
		else { return view('form_fail'); }
	}
	
	public function siteslog_edit($sitelogid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT sitelogid, user, userstartdate, userenddate FROM sites_log
			WHERE sitelogid='$sitelogid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites_log'] = $results;

		if ($this->request->getMethod() === 'POST') {
			
			$rules = [
				'user' => 'required',
				'userstartdate' => 'required',
			];

			$data['new_value'] = [
				'sitelogid' => $this->request->getVar('sitelogid'),
				'user' => $this->request->getVar('user'),
				'userstartdate'  => ($this->request->getVar('userstartdate') == '') ? NULL : $this->request->getVar('userstartdate'),
				'userenddate'  => ($this->request->getVar('userenddate') == '') ? NULL : $this->request->getVar('userenddate')
				
			];

			if($this->validate($rules)){
				$sitesLogModel = new SitesLogModel();
				$sitesLogModel->update($sitelogid, $data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('siteslog_edit',$data);
			}
		}
		return view('siteslog_edit', $data);
	}
	
	public function sitecontact_edit($siteid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT siteid, sitename FROM sites WHERE siteid='$siteid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sites'] = $results;
		$sql = "SELECT * FROM sitecontact WHERE siteid='$siteid' and enddate is null";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['sitecontact'] = $results;
		$sql = "SELECT contactid, firstname, lastname, email_1 FROM contacts";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['contacts'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'siteid' => 'required',
				'contactid' => 'required'
			];	
			if($this->validate($rules)){
				$siteid = $this->request->getVar('siteid');
				$contactid = $this->request->getVar('contactid');
				$contactemail = $this->request->getVar('contactemail');
				$jobtitle = $this->request->getVar('jobtitle');
				$department = $this->request->getVar('department');
				$sitecontactid_delete = $this->request->getVar('sitecontactid_delete');
				if($sitecontactid_delete !='') {
					$sitecontactid_del = explode(' ',$sitecontactid_delete);
					foreach($sitecontactid_del as $sitecontactid) {
						// delete query -> enddate is now
						if($sitecontactid != 0) {
							$sql = "update sitecontact set enddate=now() where sitecontactid='$sitecontactid'";
							$query = $db->query($sql);	
						}
					}
				}
				foreach($contactid as $i => $qcontactid) { 
					if($qcontactid <> '') {
						$qcontactemail = is_null($contactemail) ? '' : $contactemail[$i];
						$qjobtitle= is_null($jobtitle) ? '' : $jobtitle[$i];
						$qdepartment = is_null($department) ? '' : $department[$i];
						// insert query
						$sql = "insert into sitecontact(siteid, contactid, contactemail, jobtitle, department, startdate) 
							VALUES ('$siteid', '$qcontactid', '$qcontactemail', '$qjobtitle', '$qdepartment', NOW())
							on duplicate key update contactemail='$qcontactemail', jobtitle='$qjobtitle', department='$qdepartment', enddate=null ";
						$db->query($sql);
					}
				}
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('sitecontact_edit',$data);
			}
		}
		return view('sitecontact_edit', $data);
	}
	
	public function sitecontact_getEmail_1($contactid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT email_1 FROM contacts where contactid='$contactid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		return $results[0]['email_1'];
	}
	
	public function sitecontact_newrow($contactid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT contactid, firstname, lastname, email_1 FROM contacts";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['contacts'] = $results;
		return view('sitecontact_newrow', $data);
	}
	
	public function siteslog_delete($sitelogid = null) {
		$db = \Config\Database::connect();
		$sql = "delete from sites_log where sitelogid='$sitelogid'";
		if($db->query($sql)) { return redirect()->to('/sites');}//return view('form_success'); } 
		else { return view('form_fail'); }
	}
}