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

class DisciplineModel extends BaseModel {
  protected $table = 'discipline';
  protected $primaryKey = 'DisciplineID';
  protected $allowedFields = ['DisciplineCode', 'DisciplineName', 'SiteID', 'Parent', 'SeqScr', 'SeqRpt', 'CreateDate', 'EndDate']; 
		
  protected $useTimestamps = true;
  protected $createdField = 'CreateDate';
  protected $updatedField = '';
  protected $useSoftDeletes = true;
  protected $deletedField = 'EndDate';
  
	public function getDisciplines($filter) {
		$builder = $this->select('discipline.DisciplineID, discipline.DisciplineCode, discipline.DisciplineName, discipline.SiteID, 
        discipline.Parent, discipline.SeqScr, discipline.SeqRpt, d.DisciplineCode as ParentCode,d.DisciplineName as ParentName')
      ->join('discipline as d', 'd.DisciplineID = discipline.Parent', 'left');
      
		if (!empty($filter['DisciplineCode'])) {
			$builder->like('DisciplineCode', $filter['DisciplineCode'], 'both');
		}
		if (!empty($filter['DisciplineName'])) {
			$builder->like('DisciplineName', $filter['DisciplineName'], 'both');
		}

    $rows = $builder->findAll();
    // Build nested structure: parent with children
    $parents = [];
    $children = [];
    foreach ($rows as $row) {
      if (empty($row['Parent'])) {
        $parents[$row['DisciplineID']] = $row;
        $parents[$row['DisciplineID']]['children'] = [];
      } else {
        $children[$row['Parent']][] = $row;
      }
    }
    // Attach children to parents
    foreach ($children as $parentId => $childList) {
      if (isset($parents[$parentId])) {
        $parents[$parentId]['children'] = $childList;
      }
    }
    // Return as indexed array
    return array_values($parents);
  }
}
