<?php

namespace App\Controllers;

use App\Models\ZonesModel;
use CodeIgniter\Controller;

class Zones extends BaseController {

	protected $data = array();
	
	function __construct() {
		$this->data['zoneclass'] = array('PROP'=>'Province', 'KAB'=> 'Kabupaten', 'KOTA' => 'Kota');
	} 
	
	public function index() {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM zones";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['zones'] = $results;
		return view('zones_index', $data);
	}
		
	public function edit($zoneid = null) {
		$db = \Config\Database::connect();
		$data = array();
		$data['zoneclasses'] = $this->data['zoneclass'];
		
		$sql = "SELECT * from zones where zoneclass='PROP'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['parentzones'] = $results;
		
		if($zoneid!= 0) {
			$sql = "SELECT * from zones where zoneid='$zoneid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['zones'] = $results;
		}
		
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'zonecode' => 'required',
				'zoneclass' => 'required',
				'zonename' => 'required'
			];
			$data['new_value'] = [
				'zonecode' => $this->request->getVar('zonecode'),
				'zoneclass' => $this->request->getVar('zoneclass'),
				'zonename' => $this->request->getVar('zonename')
			];
			if($this->validate($rules)){
				if($zoneid!= 0 ) {
					$zonesModel = new ZonesModel();	
					$zonesModel->update($zoneid, $data['new_value']);
					return view('form_success');
				} else {
					$zonesModel = new ZonesModel();
					$zonesModel->set('createdate', 'NOW()', FALSE);
					$zonesModel->insert($data['new_value']);
					return view('form_success');
				}
			} else {
				$data['validation'] = $this->validator;
				return view('zones_editor',$data);
			}
		}
		return view('zones_editor', $data);
	}
	
}