<?php

namespace App\Controllers;

use App\Models\UserDepartmentModel;

class UserDepartment extends BaseController {
	public function index() {
		$db = \Config\Database::connect();
		$sql = "select * from userdepartment";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userdepartment'] = $results;
		return view('userdepartment_index', $data);
	}
	
	public function create() {
		$db = \Config\Database::connect();
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'shorttext' => 'required',
				'texts' => 'required',
			];
			$data['new_value'] = [
				'shorttext' => $this->request->getVar('shorttext'),
				'texts' => $this->request->getVar('texts')
			];
			if($this->validate($rules)){
				$userdepartmentModel = new UserDepartmentModel();
				$userdepartmentModel->set('createdate', 'NOW()', FALSE);
				$userdepartmentModel->insert($data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('userdepartment_create',$data);
			}
		}
		return view('userdepartment_create');
	}
	
	public function edit($userdeptid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM userdepartment WHERE userdeptid='$userdeptid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userdepartment'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'userdeptid' => 'required',
				'shorttext' => 'required',
				'texts' => 'required',
			];
			$data['new_value'] = [
				'userdeptid' => $this->request->getVar('userdeptid'),
				'shorttext' => $this->request->getVar('shorttext'),
				'texts' => $this->request->getVar('texts')
			];
			if($this->validate($rules)){
				$userdepartmentModel = new UserDepartmentModel();
				$userdepartmentModel->update($userdeptid, $data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('userdepartment_edit',$data);
			}
		}
		return view('userdepartment_edit', $data);
	}
	
	public function toggle($userdeptid = 0) {
		$db = \Config\Database::connect();
		$sql = "update userdepartment set enddate=
				case when enddate is not null then null
				else NOW()
				end
			where userdeptid='$userdeptid'";
		if($db->query($sql)) { return view('form_success'); } 
		else { return view('form_fail'); }
	}
	
}