<?php

namespace App\Controllers;

use App\Models\ContactsModel;
use App\Models\SiteContactModel;
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 c.*, ct.cert_name, ct.file_url, ct.issued_date FROM contacts c 
				LEFT join certificates_training ctt on ctt.contact_id = c.contactid
				LEFT join certificates ct on ct.cert_id = ctt.cert_id
				WHERE contactid=$contactid
				order by ct.issued_date DESC";
		$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') {

			if ($contactid != 0) {
				$ruleInitial = "required|is_unique[contacts.initial,contactid,{$contactid}]"; 
			} else {
				$ruleInitial = "required|is_unique[contacts.initial]";
			}
			$rules = [
				'firstname' => 'required',
				'email_1' => 'required|valid_email',
				'initial' => $ruleInitial
			];
			$messages = [
				'firstname' => [
					'required' => 'Nama depan harus diisi, tidak boleh kosong.'
				],
				'email_1' => [
					'required'    => 'Email wajib diisi.',
					'valid_email' => 'Format email yang anda masukkan tidak valid.'
				],
				'initial' => [
					'required'  => 'Initial tidak boleh kosong.',
					'is_unique' => 'Initial ini sudah dipakai orang lain, silakan cari yang unik.'
				]
			];
			$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'),
				'siteid'  => $this->request->getVar('siteid') ?? null //Untuk Create dari AR
			];

			if($this->validate($rules, $messages)){
				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']);
					$contactid = $contactsModel->getInsertID();

					if($this->request->getVar('siteid') != null) {
						$siteContactModel = new SiteContactModel();
						$siteContactValue = [
							'siteid'  => $this->request->getVar('siteid'),
							'contactid' => $contactid,
							'contactemail'  => $this->request->getVar('email_1'),
						];
						$siteContactModel->insert($siteContactValue);
					}

					return view('form_success');
				}
			} else {
				$data['validation'] = $this->validator;
				return view('contacts_editor',$data);
			}
		}
		return view('contacts_editor', $data);
	}

	public function createFromActivities() {
		$db = \Config\Database::connect();

		$rules = [
			'firstname' => 'required',
			'email_1' => 'required|valid_email',
			'initial' => 'required|is_unique[contacts.initial]'
		];
		$messages = [
			'firstname' => [
				'required' => 'Nama depan harus diisi, tidak boleh kosong.'
			],
			'email_1' => [
				'required'    => 'Email wajib diisi.',
				'valid_email' => 'Format email yang anda masukkan tidak valid.'
			],
			'initial' => [
				'required'  => 'Initial tidak boleh kosong.',
				'is_unique' => 'Initial ini sudah dipakai orang lain, silakan cari yang unik.'
			]
		];
		$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'),
			'siteid'  => $this->request->getVar('siteid') ?? null //Untuk Create dari AR
		];

		if ($this->validate($rules, $messages)) {
			
			$contactsModel = new ContactsModel();
			$contactsModel->set('createdate', 'NOW()', FALSE);
			$contactsModel->set('enddate', NULL);
			$contactsModel->insert($data['new_value']);
			$contactid = $contactsModel->getInsertID();

			if ($this->request->getVar('siteid') != null) {
				$siteContactModel = new SiteContactModel();
				$siteContactValue = [
					'siteid'       => $this->request->getVar('siteid'),
					'contactid'    => $contactid,
					'contactemail' => $this->request->getVar('email_1'),
				];
				$siteContactModel->insert($siteContactValue);
			}
			
			// Kembalikan JSON Sukses
			return $this->response->setJSON(['status' => 'success', 'message' => 'Data berhasil disimpan']);

		} else {
			// --- JIKA VALIDASI GAGAL ---
			// Ubah HTTP Status menjadi 400 (Bad Request) agar AJAX tahu ini adalah "Error"
			return $this->response->setStatusCode(400)->setJSON([
				'status' => 'error',
				'errors' => $this->validator->getErrors() // Ambil list errornya
			]);
		}
		
	}
}