<?php

namespace App\Models\Contact;

use App\Models\BaseModel;

class ContactModel extends BaseModel {
  protected $table      = 'contact';
  protected $primaryKey = 'ContactID';
  protected $allowedFields = ['NameFirst', 'NameLast', 'Title', 'Initial', 'Birthdate', 'EmailAddress1', 'EmailAddress2', 'Phone', 
  	'MobilePhone1', 'MobilePhone2', 'Specialty', 'SubSpecialty', 'CreateDate', 'EndDate']; 
	
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = "EndDate";

	public function getContactsWithDetail() {
 		$rows = $this->select("contact.ContactID, cd.SiteID, cd.ContactCode, NameFirst, NameLast, Specialty")
			->join("contactdetail cd", "contact.ContactID=cd.ContactID", "left") 
			->join("occupation o","cd.OccupationID=o.OccupationID", "left")
			->get()->getResultArray();

		return $rows;
	}

	public function getContacts($ContactName, $Specialty) {
 		$sql = $this->select("ContactID, NameFirst, NameLast, Title, Initial, Specialty");
		if($ContactName !='') { $sql->like('NameFirst',$ContactName,'both')->orLike('NameLast',$ContactName,'both'); }
		if($Specialty != '') { $sql->like('Specialty',$Specialty); }
		$rows = $sql->get()->getResultArray();
		return $rows;
	}

  public function getContactWithDetail($ContactID) {
		$rows = $this->join('contactdetail cd', 'contact.ContactID=cd.ContactID','left')->where('contact.ContactID', $ContactID)->findAll();
		$contact = [];
		
		foreach ($rows as $row) {
			if(empty($contact['NameFirst'])) {
				$contact = [
					'ContactID' => $ContactID,
					'NameFirst' => $row['NameFirst'] ?? null,
					'NameLast' => $row['NameLast'] ?? null,
					'Title' => $row['Title'] ?? null,
					'Initial' => $row['Initial'] ?? null,
					'Birthdate' => $row['Birthdate'] ?? null,
					'EmailAddress1' => $row['EmailAddress1'] ?? null,
					'EmailAddress2' => $row['EmailAddress2'] ?? null,
					'Phone' => $row['Phone'] ?? null,
					'MobilePhone1' => $row['MobilePhone1'] ?? null,
					'MobilePhone2' => $row['MobilePhone2'] ?? null,
					'Specialty' => $row['Specialty'] ?? null,
					'SubSpecialty' => $row['SubSpecialty'] ?? null,
					'Details' => []
				];
			}
			if (!empty($row['ContactDetID'])) {
				$contact['Details'][] = [
					'SiteID' => $row['SiteID'] ?? null, 
					'ContactDetID' => $row['ContactDetID'],
					'ContactCode' => $row['ContactCode'] ?? null,
					'ContactEmail' => $row['ContactEmail'] ?? null,
					'OccupationID' => $row['OccupationID'] ?? null,
					'JobTitle'  => $row['JobTitle'] ?? null,
					'Department'  => $row['Department'] ?? null,
					'ContactStartDate' => $row['ContactStartDate'] ?? null,
					'ContactEndDate' => $row['ContactEndDate'] ?? null
				];
			}
		}
	
		return $contact;
	}

	public function saveContact(array $data): array {
    $db = \Config\Database::connect();
    $db->transStart();

    try {
			$details = $data['Details'] ?? [];
			unset($data['Details']);

			if (!empty($data['ContactID'])) {
				$contactId = $data['ContactID'];
				$this->update($contactId, $data);
			} else {
				$contactId = $this->insert($data, true);
			}

			if (!$contactId) {
				throw new \RuntimeException('Failed to save contact');
			}

			if (!empty($details)) {
				$modelDetail = new \App\Models\Contact\ContactDetailModel();
				$result = $modelDetail->syncDetails($contactId, $details);

				if ($result['status'] !== 'success') {
					throw new \RuntimeException('SyncDetails failed: ' . $result['message']);
				}
			}

			$db->transComplete();

			return [
				'status'    => 'success',
				'ContactID' => $contactId,
				'DetailsCount' => count($details),
			];
    } catch (\Throwable $e) {
			$db->transRollback();

			return [
				'status'  => 'error',
				'message' => $e->getMessage(),
			];
    }
	}

}
