<?php

namespace App\Models;

use CodeIgniter\Model;

class PerizinanModel extends Model
{
    protected $table            = 'perizinan';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $allowedFields    = [
        'santri_id', 'jenis_izin', 'waktu_keluar', 'waktu_kembali', 
        'alasan', 'status', 'catatan_tolak', 'token_izin', 'created_by', 'created_at'
    ];

    // Get perizinan detailed with santri name
    public function getDetailed($id = null)
    {
        $builder = $this->db->table($this->table)
            ->select('perizinan.*, santri.nama as santri_nama, santri.nis as santri_nis, santri.kelas as santri_kelas, santri.asrama as santri_asrama, users.nama_lengkap as pembuat_nama')
            ->join('santri', 'santri.id = perizinan.santri_id')
            ->join('users', 'users.id = perizinan.created_by');

        if ($id !== null) {
            return $builder->where('perizinan.id', $id)->get()->getRowArray();
        }

        return $builder->orderBy('perizinan.created_at', 'DESC')->get()->getResultArray();
    }

    // Get by Wali ID
    public function getByWali($waliId)
    {
        return $this->db->table($this->table)
            ->select('perizinan.*, santri.nama as santri_nama, santri.nis as santri_nis, santri.kelas as santri_kelas, santri.asrama as santri_asrama')
            ->join('santri', 'santri.id = perizinan.santri_id')
            ->where('santri.wali_id', $waliId)
            ->orderBy('perizinan.created_at', 'DESC')
            ->get()->getResultArray();
    }

    // Get by Token Securely
    public function getByToken($token)
    {
        return $this->db->table($this->table)
            ->select('perizinan.*, santri.nama as santri_nama, santri.nis as santri_nis, santri.kelas as santri_kelas, santri.asrama as santri_asrama')
            ->join('santri', 'santri.id = perizinan.santri_id')
            ->where('perizinan.token_izin', $token)
            ->get()->getRowArray();
    }
}
