<?php

namespace App\Controllers;

use App\Models\ActTextModel;
use CodeIgniter\Controller;

class ActText extends Controller {

	public function index() {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM acttext order by enddate, createdate";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttext'] = $results;
		return view('acttext_index', $data);
	}
	
	public function edit($acttextid = null) {
		$db = \Config\Database::connect();
		$sql = "select * from acttext where acttextid='$acttextid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttext'] = $results;
		$sql = "select * from acttype";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttype'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'acttextid' => 'required',
				'acttextcode' => 'required',
				'fulltext' => 'required'
			];
			$data['new_value'] = [
				'acttextid' => $this->request->getVar('acttextid'),
				'acttextcode' => $this->request->getVar('acttextcode'),
				'fulltext'  => $this->request->getVar('fulltext')
			];
			if($this->validate($rules)){
				$actTextModel = new ActTextModel();
				$actTextModel->update($acttextid, $data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('acttext_edit',$data);
			}
		}
		return view('acttext_edit', $data);
	}
	
	public function create() {
		$db = \Config\Database::connect();
		$data = array();
		$sql = "select * from acttype";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['acttype'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'acttextcode' => 'required',
				'fulltext' => 'required'
			];
			$data['new_value'] = [
				'acttextcode' => $this->request->getVar('acttextcode'),
				'fulltext'  => $this->request->getVar('fulltext')
			];
			if($this->validate($rules)){
				$actTextModel = new ActTextModel();
				$actTextModel->set('createdate', 'NOW()', FALSE);
				$actTextModel->insert($data['new_value']);
				return view('form_success');
			} else {
				$data['validation'] = $this->validator;
				return view('acttext_create',$data);
			}
		}
		return view('acttext_create', $data);
	}
	
	public function toggle($acttextid = 0) {
		$db = \Config\Database::connect();
		$sql = "update acttext set enddate=
				case when enddate is not null then null
				else NOW()
				end
			where acttextid='$acttextid'";
		if($db->query($sql)) { return view('form_success'); } 
		else { return view('form_fail'); }
	}
}