<?php
namespace App\Models\Location;
use App\Libraries\ValueSet;
use App\Models\BaseModel;
use App\Models\Location\LocationAddressModel;

class LocationModel extends BaseModel {
  protected $table      = 'location';
  protected $primaryKey = 'LocationID';
  protected $allowedFields = ['SiteID', 'LocCode', 'Parent', 'LocFull', 'Description', 'LocType', 'CreateDate', 'EndDate']; 

  private array $locationEditableFields = ['SiteID', 'LocCode', 'Parent', 'LocFull', 'Description', 'LocType'];
  private array $addressEditableFields = ['Street1', 'Street2', 'City', 'Province', 'PostCode', 'GeoLocationSystem', 'GeoLocationData', 'Phone', 'Email'];
	
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = 'EndDate';

  public function getLocations($LocCode, $LocName) {
    $sql = $this->select("LocationID, LocCode, Parent, LocFull, LocType");
    if($LocName != '') { $sql->like('LocFull', $LocName, 'both'); }
    if($LocCode != '') { $sql->like('LocCode', $LocCode, 'both'); }
    $rows = $sql->findAll();
    $rows = ValueSet::transformLabels($rows, [
      'LocType' => 'location_type',
    ]);
    return $rows;
 	}

  public function getLocation($LocationID) {
    $row = $this->select("location.*, la.Street1, la.Street2, la.PostCode, la.GeoLocationSystem, la.GeoLocationData, 
      la.Province as Province, prop.AreaName as ProvinceLabel, la.City as City, city.AreaName as CityLabel, site.SiteID, site.SiteName")
    ->join("locationaddress la", "location.LocationID=la.LocationID", "left")
    ->join("areageo prop", "la.Province=prop.AreaGeoID", "left")
    ->join("areageo city", "la.City=city.AreaGeoID", "left")
    ->join("site", "site.SiteID=location.SiteID", "left")
    ->where('location.LocationID', (int) $LocationID)->first();
    
    if (!$row) return null;
    
    $row = ValueSet::transformLabels([$row], [
      'LocType' => 'location_type',
    ])[0];
    
    return $row;
  }

  private function extractLocationFields(array $data): array
  {
    return $this->filterFields($data, $this->locationEditableFields);
  }

  private function extractAddressFields(array $data): array
  {
    return $this->filterFields($data, $this->addressEditableFields);
  }

  private function filterFields(array $data, array $fields): array
  {
    return array_intersect_key($data, array_flip($fields));
  }

  private function persistAddressFields(int $LocationID, array $data, LocationAddressModel $modelAddress, bool $forceInsert = false): void
  {
    $addressPayload = $this->extractAddressFields($data);
    if ($addressPayload === [] && !$forceInsert) {
      return;
    }

    $payloadWithId = array_merge(['LocationID' => $LocationID], $addressPayload);

    if ($forceInsert) {
      $modelAddress->insert($payloadWithId);
      return;
    }

    $existingAddress = $modelAddress->find($LocationID);
    if ($existingAddress === null) {
      $modelAddress->insert($payloadWithId);
      return;
    }

    $modelAddress->update($LocationID, $addressPayload);
  }

  public function saveLocation(array $data): array {
    $modelAddress = new LocationAddressModel();
    $db = \Config\Database::connect();
    $db->transBegin();
    try {
		if (!empty($data['LocationID'])) {
			$LocationID = $data['LocationID'];
			$locationPayload = $this->extractLocationFields($data);
			if ($locationPayload !== []) {
				$this->update($LocationID, $locationPayload);
			}
		  $this->persistAddressFields($LocationID, $data, $modelAddress);
		} else {
			$LocationID = $this->insert($data, true);
		  $this->persistAddressFields($LocationID, $data, $modelAddress, true);
		}
      if ($db->transStatus() === false) {
        $error = $db->error();
        $db->transRollback();
        throw new \Exception($error['message'] ?? 'Transaction failed');
      }
      $db->transCommit();
			return [ 'status' => 'success', 'LocationID' => $LocationID ];
    } catch (\Throwable $e) {
      $db->transRollback();
      throw $e;
    }
	}

  public function deleteLocation(array $data): array {
    $modelAddress = new \App\Models\Location\LocationAddressModel();
    $db = \Config\Database::connect();
    $db->transBegin();
    try {
      $LocationID = $data['LocationID'];
			$this->delete($LocationID);
      $modelAddress->delete($LocationID);
      if ($db->transStatus() === false) {
        $error = $db->error();
        $db->transRollback();
        throw new \Exception($error['message'] ?? 'Transaction failed');
      }
      $db->transCommit();
			return [ 'status' => 'success', 'LocationID' => $LocationID ];
    } catch (\Throwable $e) {
      $db->transRollback();
      throw $e;
    }
	}
}
