<?php

namespace App\Controllers;

use App\Models\UserPositionModel;

class UserPosition extends BaseController {
	public function index() {
		$db = \Config\Database::connect();
		$sql = "select * from userposition";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['userposition'] = $results;
		return view('userposition_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)){
				$userpositionModel = new UserPositionModel();
				$userpositionModel->set('createdate', 'NOW()', FALSE);
				$userpositionModel->insert($data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('userposition_create',$data);
			}
		}
		return view('userposition_create');
	}
	
	public function edit($userposid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM userposition WHERE userposid='$userposid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['usertype'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'userposid' => 'required',
				'shorttext' => 'required',
				'texts' => 'required',
			];
			$data['new_value'] = [
				'userposid' => $this->request->getVar('userposid'),
				'shorttext' => $this->request->getVar('shorttext'),
				'texts' => $this->request->getVar('texts')
			];
			if($this->validate($rules)){
				$userpositionModel = new UserPositionModel();
				$userpositionModel->update($userposid, $data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('userposition_edit',$data);
			}
		}
		return view('userposition_edit', $data);
	}
	
	public function toggle($userid = 0) {
		$db = \Config\Database::connect();
		$sql = "update userposition set enddate=
				case when enddate is not null then null
				else NOW()
				end
			where userposid='$userposid'";
		if($db->query($sql)) { return view('form_success'); } 
		else { return view('form_fail'); }
	}
}