<?php

namespace App\Models;

use CodeIgniter\Model;

class LetterLogModel extends Model
{
    protected $table            = 'letter_logs';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'letter_type',
        'letter_number',
        'student_id',
        'student_name',
        'student_nis',
        'letter_date',
        'purpose',
        'destination',
        'reason',
        'printed_by',
        'created_at',
        // Surat Tugas & SPPD
        'officer_name',
        'teacher_id',
        'officer_nip',
        'teacher_id_number',
        'teacher_id_label',
        'officer_rank',
        'officer_position',
        'task_description',   // uraian tugas / kegiatan
        'origin',             // tempat tujuan
        'transport',          // alat angkutan
        'date_start',         // tanggal mulai
        'date_end',           // tanggal selesai
        'budget_source',      // sumber biaya
        'is_reference',
        'reference_officer',
        'reference_number',
        'reference_date',
        'reference_theme',
    ];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = '';
    protected $deletedField  = '';

    // Validation
    protected $validationRules      = [
        'letter_type'   => 'required|in_list[keterangan_aktif,mutasi_keluar,surat_tugas,sppd]',
        'letter_number' => 'required|max_length[100]',
        'letter_date'   => 'required|valid_date',
        'printed_by'    => 'required|numeric',
    ];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    /**
     * Get letter logs with optional filtering
     */
    public function getLogs($type = null, $limit = 50, $offset = 0)
    {
        $builder = $this->select('letter_logs.*, users.username as printed_by_username')
                        ->join('users', 'users.id = letter_logs.printed_by', 'left')
                        ->orderBy('letter_logs.created_at', 'DESC');

        if ($type) {
            $builder->where('letter_logs.letter_type', $type);
        }

        return $builder->limit($limit, $offset)->get()->getResultArray();
    }

    /**
     * Save letter log
     */
    public function saveLog(array $data)
    {
        $data['created_at'] = date('Y-m-d H:i:s');
        $this->insert($data);
        return $this->db->insertID();
    }

    /**
     * Check if letter number already exists
     */
    public function isLetterNumberExists($letterNumber, $excludeId = null)
    {
        $builder = $this->where('letter_number', $letterNumber);

        if ($excludeId) {
            $builder->where('id !=', $excludeId);
        }

        return $builder->countAllResults() > 0;
    }
}