<?php

namespace App\Controllers;

use App\Models\UsersModel;
use App\Models\UsersLogModel;

class Users extends BaseController {
	protected array $data;

	function __construct() {
		$this->data['levels'] = array('0'=>'None', '1'=>'Super User', '2'=> 'Technical Support Manager', '3' => 'TSO IVD', '4'=>'Product Spesialis');
	}
	
	public function index() {
		$db = \Config\Database::connect();
		$sql = "select u.*, up.texts as userposition, ud.texts as userdepartment from users u
			left join userposition up on u.userposid=up.userposid
			left join userdepartment ud on u.userdeptid=ud.userdeptid
			order by enddate";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users'] = $results;
		return view('users_index', $data);
	}
	
	public function view($userid = null) {

		$db = \Config\Database::connect();
		
		$sql = "select u.*, up.texts as userposition, ud.texts as userdepartment, 
			CONCAT(ur.firstname,' ',ur.lastname) AS userreportto, o.offname
			from users u
			left join userposition up on u.userposid=up.userposid
			left join userdepartment ud on u.userdeptid=ud.userdeptid
			left join users ur on ur.userid=u.reportto
			left join offices o on o.offid=u.offid
			where u.userid='$userid'
			order by enddate";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users'] = $results;

		$sql = "select * from users_log where userid='$userid' ORDER BY createdate DESC;";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users_log'] = $results;
		
		return view('users_view', $data);
	}
	
	public function edit($userid = null) {
		$db = \Config\Database::connect();
		if($userid != 0) {
			$sql = "SELECT *, up.texts as userposition, ud.texts as userdepartment 
				FROM users u
				left join userposition up on up.userposid=u.userposid
				left join userdepartment ud on ud.userdeptid=u.userdeptid
				WHERE userid='$userid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['users'] = $results;
		}

		$sql = "SELECT * FROM userposition";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userposition'] = $results;
		$sql = "SELECT * FROM userdepartment";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userdepartment'] = $results;

		//$sql = "SELECT userid, firstname, lastname FROM users WHERE userposid IN (1,2,3)";
		$sql = "SELECT userid, firstname, lastname FROM users"; // Sementara
		$query = $db->query($sql);
		
		$results = $query->getResultArray();
		$data['userreportto'] = $results;
		$sql = "SELECT * FROM offices";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['offices'] = $results;
		
		$data['levels'] = $this->data['levels'];

		if ($this->request->getMethod() === 'POST') {
			
			// Mencegah Tanggal Agar Tidak 0000-00-00
			$enddate = $this->request->getVar('enddate');
			if($this->request->getVar('enddate') === ''){$enddate=null;} 
			
			// Untuk User Baru
			if ($this->request->getVar('userid') == 0) {
				$rules = [
					'userid' => 'required',
					'usernumber' => 'required',
					'firstname' => 'required',
					'initial' => 'required',
					'email_1' => 'required',
					'phone' => 'required',
					'userposid' => 'required',
					'userdeptid' => 'required',
					'startdate' => 'required',
				];
				$data['new_value'] = [
					'userid' => $this->request->getVar('userid'),
					'usernumber' => $this->request->getVar('usernumber'),
					'firstname' => $this->request->getVar('firstname'),
					'lastname' => $this->request->getVar('lastname'),
					'initial'  => $this->request->getVar('initial'),
					'birthdate'  => ($this->request->getVar('birthdate') == '') ? NULL : $this->request->getVar('birthdate'),
					'email_1'  => $this->request->getVar('email_1'),
					'email_2'  => $this->request->getVar('email_2'),
					'phone'  => $this->request->getVar('phone'),
					'level' => $this->request->getVar('level'),
					'userposid'  => $this->request->getVar('userposid'),
					'userdeptid'  => $this->request->getVar('userdeptid'),
					'reportto'  => $this->request->getVar('reportto'),
					'offid'  => $this->request->getVar('offid'),
					'startdate'  => $this->request->getVar('startdate'),
					'enddate'  => $enddate
				];

			// Untuk User Yang Sudah Ada
			} else {

				$rules = [
					'userid' => 'required',
					'usernumber' => 'required',
					'firstname' => 'required',
					'initial' => 'required',
					'email_1' => 'required',
					'phone' => 'required',
					'startdate' => 'required',
				];

				$data['new_value'] = [
					'userid' => $this->request->getVar('userid'),
					'usernumber' => $this->request->getVar('usernumber'),
					'firstname' => $this->request->getVar('firstname'),
					'lastname' => $this->request->getVar('lastname'),
					'initial'  => $this->request->getVar('initial'),
					'birthdate'  => ($this->request->getVar('birthdate') == '') ? NULL : $this->request->getVar('birthdate'),
					'email_1'  => $this->request->getVar('email_1'),
					'email_2'  => $this->request->getVar('email_2'),
					'phone'  => $this->request->getVar('phone'),
					'level' => $this->request->getVar('level'),
					'startdate'  => $this->request->getVar('startdate'),
					'enddate'  => $enddate
				];
			}
			
			if($this->validate($rules)) {

				// Untuk Mengupdate User yg Sudah Ada
				if($userid != 0) {
					$usersModel= new UsersModel();
					$usersModel->update($userid, $data['new_value']);
					return view('form_success');
				
				// Untuk User Baru/Fresh
				} else {

					// Input Tabel Users
					$usersModel= new UsersModel();
					$usersModel->set('createdate', 'NOW()', FALSE);
					$usersModel->insert($data['new_value']);

					// Input Tabel User Logs
					// get data
					$userdeptid = $data['new_value']['userdeptid'];
					$sql = "SELECT texts FROM userdepartment WHERE userdeptid = $userdeptid";
					$query = $db->query($sql);
					$results = $query->getResultArray();
					$userdepartmenttext = $results[0]['texts'];
					// get data
					$userposid = $data['new_value']['userposid'];
					$sql = "SELECT texts FROM userposition WHERE userposid = $userposid";
					$query = $db->query($sql);
					$results = $query->getResultArray();
					$userpostext = $results[0]['texts'];
					// get data
					$userreportid = $data['new_value']['reportto'];
					$sql = "SELECT CONCAT(firstname, ' ', lastname) as fullname FROM users WHERE userid='$userreportid'";
					$query = $db->query($sql);
					$results = $query->getResultArray();
					$userreporttext = $results[0]["fullname"];
					// get data
					$useroffid = $data['new_value']['offid'];
					$sql = "SELECT offname FROM offices WHERE offid = $useroffid";
					$query = $db->query($sql);
					$results = $query->getResultArray();
					$userofftext = $results[0]['offname'];
					// set data
					$data['new_log_value'] = [
						'userid' => $usersModel->getInsertID(),
						'userdepartment' => $userdepartmenttext,
						'userposition' => $userpostext,
						'reportto' => $userreporttext,
						'office' => $userofftext,
						'startdate' => $data['new_value']['startdate'],
						'enddate' => $data['new_value']['enddate']
					];
					$UsersLogModel = new UsersLogModel();
					$UsersLogModel->set('createdate', 'NOW()', FALSE);
					$UsersLogModel->insert($data['new_log_value']);
					
					return view('form_success');
				}

			} else {
				$data['validation'] = $this->validator;
				return view('users_editor',$data);
			}
		}
		return view('users_editor', $data);
	}
	
	public function edit_password($userid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM users WHERE userid='$userid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'userid' => 'required',
				'password' => 'required',
				'password_confirm' => 'required|matches[password]'
			];
			$data['new_value'] = [
                'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
			];
			if($this->validate($rules)){
				$usersModel= new UsersModel();
				$usersModel->update($userid, $data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('users_edit_password',$data);
			}
		}
		return view('users_edit_password', $data);
	}
	
	public function toggle($userid = 0) {
		$db = \Config\Database::connect();
		$sql = "update users set enddate=
				case when enddate is not null then null
				else NOW()
				end
			where userid='$userid'";
		if($db->query($sql)) { return view('form_success'); } 
		else { return view('form_fail'); }
	}

	// Update Jabatan
	public function edit_role($userid){

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

		$startwork = date('Y-m-d');
		$data['startwork'] = $startwork;

		if($userid != 0) {
			$sql = "SELECT *, up.texts as userposition, ud.texts as userdepartment 
			FROM users u
			left join userposition up on up.userposid=u.userposid
			left join userdepartment ud on ud.userdeptid=u.userdeptid
			WHERE userid='$userid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['users'] = $results;
		}

		$sql = "SELECT * FROM userposition";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userposition'] = $results;
		
		$sql = "SELECT * FROM userdepartment";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userdepartment'] = $results;

		//$sql = "SELECT userid, firstname, lastname FROM users WHERE userposid IN (1,2,3)";
		$sql = "SELECT userid, firstname, lastname FROM users"; // Sementara
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userreportto'] = $results;

		$sql = "SELECT offid, offname FROM offices";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['offices'] = $results;

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

			$rules = [
			'userid' => 'required',
			'userposid' => 'required',
			'userdeptid' => 'required',
			'reportto' => 'required',
			'offid' => 'required',
			'startdate' => 'required',
			];

			$userid = $this->request->getVar('userid');
			$userposid = $this->request->getVar('userposid');
			$userdeptid = $this->request->getVar('userdeptid');
			$reportto = $this->request->getVar('reportto');
			$offid = $this->request->getVar('offid');
			$startdate = $this->request->getVar('startdate');

			$data['new_value'] = [
				'userid' => $this->request->getVar('userid'),
				'userposid'  => $this->request->getVar('userposid'),
				'userdeptid'  => $this->request->getVar('userdeptid'),
				'reportto'  => $this->request->getVar('reportto'),
				'offid'  => $this->request->getVar('offid'),
			];

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

				// Update Users
				$usersModel= new UsersModel();
				$usersModel->update($userid, $data['new_value']);


				// Update Log_Users
				$sql = "SELECT userlogid FROM users_log where userid=$userid order by userlogid desc limit 1";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				
				if($results != null){
					$userlogid = $results[0]['userlogid'];
					$data['users_log'] = [
						'enddate' => $startdate
					];

					$usersLogModel= new UsersLogModel();
					$usersLogModel->update($userlogid, $data['users_log']);
				}

				// Insert Log_Users
				$sql = "SELECT texts FROM userdepartment WHERE userdeptid = $userdeptid";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				$userdepttext = $results[0]['texts'];

				$sql = "SELECT texts FROM userposition WHERE userposid = $userposid";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				$userposidtext = $results[0]['texts'];

				$sql = "SELECT CONCAT(firstname, ' ', lastname) as fullname FROM users WHERE userid = $reportto";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				if($results != null) {$usernametext = $results[0]['fullname'];} else {$usernametext=null;}
				
				$sql = "SELECT offname as texts FROM offices WHERE offid = $offid";
				$query = $db->query($sql);
				$results = $query->getResultArray();
				$offname = $results[0]['texts'];

				$data['users_log'] = [
					'userid' => $userid,
					'userposition'  => $userposidtext,
					'userdepartment'  => $userdepttext,
					'reportto'  => $usernametext,
					'office'  => $offname,
					'startdate'  => $this->request->getVar('startdate'),
				];
				
				$usersLogModel= new UsersLogModel();
				$usersLogModel->set('createdate', 'NOW()', FALSE);
				$usersLogModel->insert($data['users_log']);

				
				return view('form_success');

			} else {
				$data['validation'] = $this->validator;
				return view('users_position_editor',$data);
			}
		}

		return view('usersrole_editor',$data);
	}
	
	// Edit History Jabatan
	public function users_log_edit($userlogid = 0) {
		$db = \Config\Database::connect();
		
		$sql = "SELECT * FROM users_log WHERE userlogid='$userlogid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['users_log'] = $results;
		$userid = $results[0]['userid']; 

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

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

			$enddate = $this->request->getVar('enddate');
			if($enddate === ''){$enddate=null;}

			$rules = [
				'startdate' => 'required'
			];
			$data['new_value'] = [
				'startdate' => $this->request->getVar('startdate'), 
				'enddate' => $enddate,
			];
			if($this->validate($rules)){
				$usersLogModel = new UsersLogModel();
				$usersLogModel->update($userlogid, $data['new_value']);
				
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('userslog_edit',$data);
			}
		}

		return view('userslog_edit', $data);
	}
	
	// Hapus History Jabatan
	public function users_log_delete($userlogid = 0) {
		$db = \Config\Database::connect();
		$sql = "DELETE FROM users_log WHERE userlogid='$userlogid'";
		if($db->query($sql)) { 
			//return view('form_success'); 
			return redirect()->to('/users');} 
		else { 
			//return view('form_fail'); 
			return redirect()->to('/users');}
	}
}