<?php
namespace App\Models\Location;
use App\Models\BaseModel;

class LocationModel extends BaseModel {
  protected $table      = 'location';
  protected $primaryKey = 'LocationID';
  protected $allowedFields = ['SiteID', 'LocCode', 'Parent', 'LocFull', 'Description', 'LocType', 'CreateDate', 'EndDate']; 
		
  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, v.VDesc as LocTypeText")
      ->join("valueset v", "v.VID=location.loctype", 'left');
    if($LocName != '') { $sql->like('LocFull', $LocName, 'both'); }
    if($LocCode != '') { $sql->like('LocCode', $LocCode, 'both'); }
    $rows = $sql->findAll();
    return $rows;
	}

  public function getLocation($LocationID) {
    //'Street1', 'Street2', 'City', 'Province', 'PostCode', 'GeoLocationSystem', 'GeoLocationData',
    $row = $this->select("location.*, la.Street1, la.Street2, la.PostCode, la.GeoLocationSystem, la.GeoLocationData, 
      v.VDesc as LocTypeText, prop.AreaGeoID as ProvinceID, prop.AreaName as Province, city.AreaGeoID as CityID, city.AreaName as City, site.SiteID, site.SiteName")
    ->join("locationaddress la", "location.LocationID=la.LocationID", "left")
    ->join("valueset v", "v.VID=location.loctype", "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();
    return $row;
  }

  public function saveLocation(array $data): array {
    $modelAddress = new \App\Models\Location\LocationAddressModel();
    $db = \Config\Database::connect();
    $db->transBegin();
    try {
			if (!empty($data['LocationID'])) {
				$LocationID = $data['LocationID'];
				$this->update($LocationID, $data);
        $modelAddress->update($LocationID, $data);
			} else {
				$LocationID = $this->insert($data, true);
        $data['LocationID'] = $LocationID;
        $modelAddress->insert($data);
			}
      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;
    }
	}
}
 