<?php

namespace App\Controllers;

use App\Models\InvCountersModel;
use CodeIgniter\Controller;

class InvCounters extends BaseController {
		
	public function index() {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM invcounters";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['invcounters'] = $results;
		return view('invcounters_index', $data);
	}
		
	public function edit($counterid = null) {
		$db = \Config\Database::connect();
		$data['counterid']= $counterid;
		if($counterid != 0) {
			$sql = "SELECT counternumber, countername FROM invcounters where counterid='$counterid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['invcounters'] = $results;
		}
		
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'counternumber' => 'required',
				'countername' => 'required'
			];
			$data['new_value'] = [
				'counternumber' => $this->request->getVar('counternumber'),
				'countername' => $this->request->getVar('countername')
			];
			if($this->validate($rules)){
				if($counterid != 0 ) {
					$invcountersModel = new InvcountersModel();	
					$invcountersModel->update($counterid, $data['new_value']);
					return view('form_success');
				} else {
					$invcountersModel = new InvcountersModel();
					$invcountersModel->set('createdate', 'NOW()', FALSE);
					$invcountersModel->insert($data['new_value']);
					return view('form_success');
				}
			} else {
				$data['validation'] = $this->validator;
				return view('invcounters_editor',$data);
			}
		}
		return view('invcounters_editor', $data);
	}

}