<?php

namespace App\Controllers;

use App\Models\ContactsModel;
use CodeIgniter\Controller;

class Contacts extends Controller {

	protected $helper = ['form'];
	
	public function index() {
		$db = \Config\Database::connect();
		$sql = "select c.contactid, c.firstname, c.lastname, c.title, c.initial, c.createdate, c.email_1 from contacts c";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['contacts'] = $results;
		return view('contacts_index', $data);
	}
	
	public function view($contactid = null) {
		$db = \Config\Database::connect();
		$sql = "SELECT * FROM contacts where contactid='$contactid'";
		$query = $db->query($sql);
		$results = $query->getResultArray();
		$data['contacts'] = $results;
		return view('contacts_view', $data);
	}

	public function edit($contactid = null) {
		$db = \Config\Database::connect();
		$data = array();
		if($contactid != 0) {
			$sql = "select * from contacts where contactid='$contactid'";
			$query = $db->query($sql);
			$results = $query->getResultArray();
			$data['contacts'] = $results;
		}
		if ($this->request->getMethod() === 'POST') {
			$rules = [
				'contactid' => 'required',
				'firstname' => 'required',
				'email_1' => 'required',
				'initial' => 'required'
			];
			$data['new_value'] = [
				'firstname' => $this->request->getVar('firstname'),
				'lastname' => $this->request->getVar('lastname'),
				'title'  => $this->request->getVar('title'),
				'initial'  => $this->request->getVar('initial'),
				'birthdate'  => ($this->request->getVar('birthdate') == '') ? NULL : $this->request->getVar('birthdate'),
				'email_1'  => $this->request->getVar('email_1'),
				'email_2'  => $this->request->getVar('email_2'),
				'phone'  => $this->request->getVar('phone'),
				'mobile_1'  => $this->request->getVar('mobile_1'),
				'mobile_2'  => $this->request->getVar('mobile_2')
			];

			if($this->validate($rules)){
				if($contactid != 0) {
					$contactsModel = new contactsModel();	
					$contactsModel->set('enddate', NULL);
					$contactsModel->update($contactid, $data['new_value']);
					return view('form_success');
				} else {
					$contactsModel = new ContactsModel();
					$contactsModel->set('createdate', 'NOW()', FALSE);
					$contactsModel->set('enddate', NULL);
					$contactsModel->insert($data['new_value']);
					return view('form_success');
				}
			} else {
				$data['validation'] = $this->validator;
				return view('contacts_editor',$data);
			}
		}
		return view('contacts_editor', $data);
	}
}