<?php

namespace App\Controllers;

use App\Models\UnitGroupModel;
use CodeIgniter\Controller;

class UnitGroup extends BaseController {
	public function index() {		
		$data = array();
		if ($this->request->getMethod() === 'POST') {
			$db = \Config\Database::connect();
			$productname= strtolower($this->request->getVar('productname'));
			$sql = "SELECT u.*, c.`productname`, c.`catalognumber` FROM unitgroup u".
				" LEFT JOIN productcatalog c ON c.`catalogid`=u.`catalogid` ".
				" where lower(c.productname) like '%$productname%' ";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['unitgroup'] = $results;
		}
		return view('unitgroup_index',$data);
	}

	public function edit($unitgroupid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM unitgroup WHERE unitgroupid='$unitgroupid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['unitgroup'] = $results;
		$sql = "SELECT * FROM productcatalog";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['productcatalog'] = $results;
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'catalogid' => 'required',
				'unitgroupcode' => 'required',
				'unit' => 'required',
				'quantity' => 'required',
				'baseunit' => 'required'
			];
			$data['new_value'] = [
				'catalogid' => $this->request->getVar('catalogid'),
				'unitgroupcode'  => $this->request->getVar('unitgroupcode'),
				'unit'  => $this->request->getVar('unit'),
				'quantity'  => $this->request->getVar('quantity'),
				'baseunit'  => $this->request->getVar('baseunit')
			];
			if($this->validate($rules)){
				if($unitgroupid!=0) {
					$model = new UnitGroupModel();
					$model->update($unitgroupid, $data['new_value']);
					return view('form_success');
				} else {
					$model = new UnitGroupModel();
					$model->set('logdate', 'NOW()', FALSE);
					$model->insert($data['new_value']);
					return view('form_success');
				}
			} else {
				$data['validation'] = $this->validator;
				return view('unitgroup_editor',$data);
			}
		}
		return view('unitgroup_editor', $data);
	}

	public function toggle($unitgroupid = 0) {
		$db = \Config\Database::connect();
		$sql = "update unitgroup set enddate=
				case when enddate is not null then null
				else NOW()
				end
			where unitgroupid ='$unitgroupid'";
		if($db->query($sql)) { return view('form_success'); } 
		else { return view('form_fail'); }
	}
}