<?php

namespace App\Models;

use CodeIgniter\Model;

class AttendanceCorrectionModel extends Model
{
    protected $table         = 'attendance_corrections';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';

    protected $allowedFields = [
        'attendance_record_id', 'original_clock_in', 'original_clock_out', 'original_status',
        'corrected_clock_in', 'corrected_clock_out', 'corrected_status',
        'reason', 'status', 'requested_by', 'approved_by', 'approved_at', 'rejection_reason',
    ];

    protected $validationRules = [
        'attendance_record_id' => 'required|integer',
        'reason'               => 'required|min_length[5]',
        'status'               => 'permit_empty|in_list[pending,approved,rejected]',
    ];

    public function scopeForList(?string $status = null, ?int $employeeId = null): self
    {
        if ($status) {
            $this->where('attendance_corrections.status', $status);
        }

        return $this;
    }

    public function getWithDetails(?string $status = null): array
    {
        $builder = $this->db->table('attendance_corrections ac')
            ->select('ac.*, ar.attendance_date, ar.employee_id, e.full_name, e.employee_number')
            ->join('attendance_records ar', 'ar.id = ac.attendance_record_id')
            ->join('employees e', 'e.id = ar.employee_id')
            ->where('e.deleted_at', null);

        if ($status) {
            $builder->where('ac.status', $status);
        }

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