<?php

namespace App\Controllers;

use App\Models\OfficesModel;

class Offices extends BaseController {

	// CONTACTS dan SITES
	public function index() {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM offices";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['offices'] = $results;
		return view('offices_index', $data);		
	}
	
	public function view($offid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM offices where offid='$offid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['offices'] = $results;		
		return view('offices_view', $data);
	}
	
	public function edit($offid = null) {
		$db = \Config\Database::connect();
		$data = array();
		if($offid != 0) {
			$sql = "SELECT offname, offphone, offaddress from offices WHERE offid='$offid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['offices'] = $results;
		}

		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'offid' => 'required',
				'offname' => 'required'
			];
			$data['new_value'] = [
				'offname' => $this->request->getVar('offname'),
				'offaddress'  => $this->request->getVar('offaddress'),
				'offphone'  => $this->request->getVar('offphone')
			];
			if($this->validate($rules)){			
				$model = new OfficesModel();
				if($offid != 0) {
					$model->update($offid, $data['new_value']);
				} else {
					$model->set('createdate', 'NOW()', FALSE);
					$model->insert($data['new_value']);
				}
				return view('form_success');
			}
			return view('offices_editor', $data);
		}
		return view('offices_editor', $data);
	}

}