<?php

namespace App\Models\Contact;

use App\Models\BaseModel;

class ContactDetailModel extends BaseModel {
  protected $table      = 'contactdetail';
  protected $primaryKey = 'ContactDetID';
  protected $allowedFields = ['ContactID', 'SiteID', 'ContactCode', 'ContactEmail', 'OccupationID', 'JobTitle', 'Department', 'ContactStartDate', 'ContactEndDate']; 
  
  protected $useTimestamps = true;
  protected $createdField = 'ContactStartDate';
  protected $updatedField = '';

  public function syncDetails(int $ContactID, array $contactDetails) {
    try {
      $keptSiteIDs = [];

      foreach ($contactDetails as $detail) {
        if (empty($detail['SiteID'])) {
          continue;
        }

        $detail['ContactID'] = $ContactID;

        $existing = $this->where('ContactID', $ContactID)
          ->where('SiteID', $detail['SiteID'])
          ->first();

        if ($existing) {
          $this->update($existing[$this->primaryKey], $detail);
        } else {
          $this->insert($detail);
        }

        $keptSiteIDs[] = $detail['SiteID'];
      }

      // Delete missing rows
      if (!empty($keptSiteIDs)) {
        $this->where('ContactID', $ContactID)
          ->whereNotIn('SiteID', $keptSiteIDs)
          ->delete();
      } else {
        $this->where('ContactID', $ContactID)->delete();
      }

      return [
        'status'   => 'success',
        'inserted' => count($contactDetails) - count($keptSiteIDs),
        'kept'     => count($keptSiteIDs),
      ];
    } catch (\Throwable $e) {
        log_message('error', 'syncDetails error: ' . $e->getMessage());

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