<?php

namespace App\Models;

use Wibiesana\Padi\Core\ActiveRecord;
use Wibiesana\Padi\Core\Query;

class SarprasBangunan extends ActiveRecord
{
    protected string $table = 'sarpras_bangunan';
    protected string|array $primaryKey = 'id';
    
    protected array $fillable = [
        'kode_bangunan', 'nama_bangunan', 'deskripsi', 'luas_tanah', 'jumlah_lantai', 'kondisi', 'tahun_pembangunan'
    ];
    
    protected array $hidden = [];
    protected bool $useAudit = true;
    protected string $timestampFormat = 'datetime';

    public function ruangan()
    {
        return $this->hasMany(\App\Models\SarprasRuangan::class, 'bangunan_id');
    }

    protected function buildSearchConditions(string $keyword): array
    {
        $conditions = ['OR'];
        foreach ($this->fillable as $field) {
            $conditions[] = ["{$this->table}.{$field}", 'LIKE', $keyword];
        }
        return $conditions;
    }

    public function searchPaginate(string $keyword, int $page = 1, int $perPage = 25, ?string $orderBy = null): array
    {
        $keyword = "%{$keyword}%";
        $conditions = $this->buildSearchConditions($keyword);

        $query = Query::find()
            ->select("{$this->table}.*")
            ->from($this->table)
            ->where($conditions);

        if ($orderBy) {
            $query->orderBy($orderBy);
        } else {
            $query->orderBy("{$this->table}.id DESC");
        }

        $result = $query->paginate($perPage, $page);

        if (!empty($result['data'])) {
            $this->loadRelations($result['data']);
            $result['data'] = $this->hideFields($result['data']);
        }

        return [
            'data' => $result['data'],
            'meta' => [
                'total' => (int)$result['total'],
                'per_page' => $result['per_page'],
                'current_page' => $result['current_page'],
                'last_page' => $result['last_page'],
                'from' => ($result['current_page'] - 1) * $result['per_page'] + 1,
                'to' => min($result['current_page'] * $result['per_page'], $result['total'])
            ]
        ];
    }
}
