<?php
namespace App\Models\Patient;

use App\Models\BaseModel;
use App\Models\BaseUtcModel;

class PatComModel extends BaseModel {
  protected $table      = 'patcom';
  protected $primaryKey = 'PatComID ';
  protected $allowedFields = ['InternalPID', 'Comment', 'CreateDate', 'EndDate'];
    
  protected $useTimestamps  = true;
  protected $createdField   = 'CreateDate';
  protected $updatedField   = '';
  protected $useSoftDeletes = true;
  protected $deletedField   = 'EndDate';

  protected $beforeInsert = ['normalizeDatesToUTC'];
  protected $beforeUpdate = ['normalizeDatesToUTC'];
  protected $afterFind    = ['convertDatesToUTCISO'];
  protected $afterInsert  = ['convertDatesToUTCISO'];
  protected $afterUpdate  = ['convertDatesToUTCISO'];

  public function createPatCom(string $patcom, string $newInternalPID) {
    $this->insert(["InternalPID" => $newInternalPID, "Comment" => $patcom]);
  }

  public function updatePatCom(string $patcom, string $InternalPID) {
    $exists = $this->withDeleted()->where('InternalPID', $InternalPID)->first();

    if ($exists) {
      //Update
      $this->where('InternalPID', $InternalPID)->set(['EndDate' => null,'Comment' => $patcom])->update();
    } else {
      //Insert
      $this->insert(['InternalPID' => $InternalPID, 'Comment' => $patcom]);
    }
  }

  public function deletePatCom(string $InternalPID) {
    $this->where('InternalPID', $InternalPID)->delete();
  }

}
