<?php

namespace App\Models\Base;

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

class SarprasPeminjaman extends ActiveRecord
{
    protected string $table = 'sarpras_peminjaman';
    protected string|array $primaryKey = 'id';
    
    protected array $fillable = [
        'kode_transaksi', 'item_id', 'peminjam_id', 'petugas_id', 'tanggal_pinjam', 'tanggal_rencana_kembali', 'tanggal_kembali', 'jumlah_pinjam', 'keperluan', 'status', 'denda'
    ];
    
    protected array $hidden = [];

    /**
     * Audit fields detected: created_at, updated_at, created_by, updated_by
     * These will be auto-populated by ActiveRecord
     */
    protected bool $useAudit = true;
    
    /**
     * Timestamp format: 'datetime'
     * 'datetime' = Y-m-d H:i:s (DATETIME/TIMESTAMP columns)
     * 'unix' = integer timestamp (INT/BIGINT columns)
     */
    protected string $timestampFormat = 'datetime';


    public function item()
    {
        return $this->belongsTo(\App\Models\SarprasItem::class, 'item_id');
    }

    public function peminjam()
    {
        return $this->belongsTo(\App\Models\SarprasPeminjam::class, 'peminjam_id');
    }

    public function petugas()
    {
        return $this->belongsTo(\App\Models\SarprasPetuga::class, 'petugas_id');
    }

    /**
     * Build global search conditions
     * Searches all fillable fields + related table display columns
     */
    protected function buildSearchConditions(string $keyword): array
    {
        $conditions = ['OR'];

        // Search all fillable fields from this table
        foreach ($this->fillable as $field) {
            $conditions[] = ["{$this->table}.{$field}", 'LIKE', $keyword];
        }

            // Search in related tables
            $conditions[] = ['sarpras_items.id', 'LIKE', $keyword];
            $conditions[] = ['sarpras_peminjam.email', 'LIKE', $keyword];
            $conditions[] = ['sarpras_petugas.id', 'LIKE', $keyword];

        return $conditions;
    }

    /**
     * Search with pagination and joins
     */
    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)
            ->leftJoin('sarpras_items AS sarpras_items', 'sarpras_peminjaman.item_id = sarpras_items.id')
            ->leftJoin('sarpras_peminjam AS sarpras_peminjam', 'sarpras_peminjaman.peminjam_id = sarpras_peminjam.id')
            ->leftJoin('sarpras_petugas AS sarpras_petugas', 'sarpras_peminjaman.petugas_id = sarpras_petugas.id')
            ->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'])
            ]
        ];
    }

    /**
     * Search sarpras_peminjaman (simple limit)
     */
    public function search(string $keyword, ?string $orderBy = null): array
    {
        $keyword = "%{$keyword}%";
        $conditions = $this->buildSearchConditions($keyword);

        $query = Query::find()
            ->select("{$this->table}.*")
            ->from($this->table)
            ->leftJoin('sarpras_items AS sarpras_items', 'sarpras_peminjaman.item_id = sarpras_items.id')
            ->leftJoin('sarpras_peminjam AS sarpras_peminjam', 'sarpras_peminjaman.peminjam_id = sarpras_peminjam.id')
            ->leftJoin('sarpras_petugas AS sarpras_petugas', 'sarpras_peminjaman.petugas_id = sarpras_petugas.id')
            ->where($conditions)
            ->limit(100);

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

        $results = $query->all();

        if (!empty($results)) {
            $this->loadRelations($results);
            $results = $this->hideFields($results);
        }

        return $results;
    }
}