<?php
namespace App\Models\Patient;

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

class PatAttModel extends BaseModel {
  protected $table      = 'patatt';
  protected $primaryKey = 'PatAttID';
  protected $allowedFields = ['InternalPID', 'Address', 'UserID', 'CreateDate', 'DelDate'];
    
  protected $useTimestamps  = true;
  protected $createdField   = 'CreateDate';
  protected $updatedField   = '';
  protected $useSoftDeletes = true;
  protected $deletedField   = 'DelDate';

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

  public function createPatAtt($patatt, string $newInternalPID) {
    foreach ($patatt as &$row) {
      $row['InternalPID'] = (string)$newInternalPID;
    }
    $this->insertBatch($patatt);
  }

  public function updatePatAtt(array $patatt, string $InternalPID) {
    // Ambil daftar address aktif saat ini dari DB
    $oldActive = $this->getActiveAddresses($InternalPID);

    // Normalisasi input baru (hapus duplikat & pastikan punya key 'Address')
    $mapNew = [];
    foreach ($patatt as $row) {
      if (empty($row['Address'])) continue;
      $mapNew[$row['Address']] = $row; // overwrite duplikat
    }

    $newData = array_keys($mapNew);

    // Hitung data yang ditambah & dihapus
    $added   = array_diff($newData, $oldActive); // address baru
    $removed = array_diff($oldActive, $newData); // address lama dihapus

    // Soft delete yang dihapus
    if (!empty($removed)) {
      $this->softDeleteByAddresses($InternalPID, $removed);
    }

    // Tambahkan / re-activate yang baru
    foreach ($added as $addr) {
      $data = $mapNew[$addr];
      $data['InternalPID'] = $InternalPID;

      // Coba re-activate dulu
      $this->reactivateAddress($InternalPID, $addr);

      // Cek apakah ada baris yang di-update (re-activate)
      if ($this->db->affectedRows() === 0) {
          // Tidak ada baris lama yang dihapus → insert baru
          $this->insert($data);
      }
    }
  }

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

  // Dapatkan daftar alamat aktif berdasarkan InternalPID
  public function getActiveAddresses(string $InternalPID): array {
    $rows = $this->select('Address')->where('InternalPID', $InternalPID)->where('DelDate', null)->findAll();
    return array_column($rows, 'Address');
  }
  // Soft delete beberapa address sekaligus
  public function softDeleteByAddresses(string $InternalPID, array $addresses) {
    if (empty($addresses)) return;
    $this->where('InternalPID', $InternalPID)->whereIn('Address', $addresses)->delete(); 
  }
  // Reactivate (hapus DelDate) 1 address jika pernah dihapus
  // Return true jika berhasil re-activate
  public function reactivateAddress(string $InternalPID, string $Address): bool {
    return $this->where('InternalPID', $InternalPID)->where('Address', $Address)->where('DelDate IS NOT NULL', null, false)->set('DelDate', null)->orderBy('PatAttID', 'DESC')->limit(1)->update();
  }
}
