<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'employee_id', 'shift_id', 'attendance_date', 'clock_in', 'clock_out',
        'status', 'late_minutes', 'early_exit_minutes', 'overtime_minutes',
        'work_minutes', 'source', 'notes', 'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'employee_id'     => 'required|integer',
        'attendance_date' => 'required|valid_date[Y-m-d]',
        'status'          => 'permit_empty|in_list[present,absent,late,half_day,on_leave,holiday,auto_present]',
        'source'          => 'permit_empty|in_list[clock,manual,auto,correction]',
    ];

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

        if ($dateTo) {
            $this->where('attendance_date <=', $dateTo);
        }

        if ($employeeId) {
            $this->where('employee_id', $employeeId);
        }

        if ($status) {
            $this->where('status', $status);
        }

        if ($shiftId) {
            $this->where('shift_id', $shiftId);
        }

        return $this;
    }

    public function findForEmployeeOnDate(int $employeeId, string $date): ?array
    {
        return $this->where('employee_id', $employeeId)
            ->where('attendance_date', $date)
            ->first() ?: null;
    }

    public function getForDateWithEmployees(string $date, ?string $search = null): array
    {
        $builder = $this->db->table('attendance_records ar')
            ->select('ar.*, e.full_name, e.employee_number, e.department_id, s.name as shift_name, s.code as shift_code')
            ->join('employees e', 'e.id = ar.employee_id', 'left')
            ->join('attendance_shifts s', 's.id = ar.shift_id', 'left')
            ->where('ar.attendance_date', $date)
            ->where('e.deleted_at', null);

        if ($search) {
            $builder->groupStart()
                ->like('e.full_name', $search)
                ->orLike('e.employee_number', $search)
                ->groupEnd();
        }

        return $builder->orderBy('e.full_name', 'ASC')->get()->getResultArray();
    }

    public function getMonthlySummary(int $year, int $month, ?int $employeeId = null, ?int $departmentId = null): array
    {
        $startDate = sprintf('%04d-%02d-01', $year, $month);
        $endDate   = date('Y-m-t', strtotime($startDate));

        $builder = $this->db->table('attendance_records ar')
            ->select('ar.*, e.full_name, e.employee_number, e.department_id, s.name as shift_name')
            ->join('employees e', 'e.id = ar.employee_id', 'left')
            ->join('attendance_shifts s', 's.id = ar.shift_id', 'left')
            ->where('ar.attendance_date >=', $startDate)
            ->where('ar.attendance_date <=', $endDate)
            ->where('e.deleted_at', null);

        if ($employeeId) {
            $builder->where('ar.employee_id', $employeeId);
        }

        if ($departmentId) {
            $builder->where('e.department_id', $departmentId);
        }

        return $builder->orderBy('ar.attendance_date', 'ASC')
            ->orderBy('e.full_name', 'ASC')
            ->get()
            ->getResultArray();
    }

    public function getLateArrivals(string $dateFrom, string $dateTo, ?int $employeeId = null): array
    {
        $builder = $this->db->table('attendance_records ar')
            ->select('ar.*, e.full_name, e.employee_number, s.name as shift_name')
            ->join('employees e', 'e.id = ar.employee_id', 'left')
            ->join('attendance_shifts s', 's.id = ar.shift_id', 'left')
            ->where('ar.attendance_date >=', $dateFrom)
            ->where('ar.attendance_date <=', $dateTo)
            ->where('ar.late_minutes >', 0)
            ->where('e.deleted_at', null);

        if ($employeeId) {
            $builder->where('ar.employee_id', $employeeId);
        }

        return $builder->orderBy('ar.attendance_date', 'DESC')
            ->orderBy('ar.late_minutes', 'DESC')
            ->get()
            ->getResultArray();
    }

    public function getEarlyExits(string $dateFrom, string $dateTo, ?int $employeeId = null): array
    {
        $builder = $this->db->table('attendance_records ar')
            ->select('ar.*, e.full_name, e.employee_number, s.name as shift_name')
            ->join('employees e', 'e.id = ar.employee_id', 'left')
            ->join('attendance_shifts s', 's.id = ar.shift_id', 'left')
            ->where('ar.attendance_date >=', $dateFrom)
            ->where('ar.attendance_date <=', $dateTo)
            ->where('ar.early_exit_minutes >', 0)
            ->where('e.deleted_at', null);

        if ($employeeId) {
            $builder->where('ar.employee_id', $employeeId);
        }

        return $builder->orderBy('ar.attendance_date', 'DESC')
            ->orderBy('ar.early_exit_minutes', 'DESC')
            ->get()
            ->getResultArray();
    }

    public function getOvertimeRecords(string $dateFrom, string $dateTo, ?int $employeeId = null): array
    {
        $builder = $this->db->table('attendance_records ar')
            ->select('ar.*, e.full_name, e.employee_number, s.name as shift_name')
            ->join('employees e', 'e.id = ar.employee_id', 'left')
            ->join('attendance_shifts s', 's.id = ar.shift_id', 'left')
            ->where('ar.attendance_date >=', $dateFrom)
            ->where('ar.attendance_date <=', $dateTo)
            ->where('ar.overtime_minutes >', 0)
            ->where('e.deleted_at', null);

        if ($employeeId) {
            $builder->where('ar.employee_id', $employeeId);
        }

        return $builder->orderBy('ar.attendance_date', 'DESC')
            ->orderBy('ar.overtime_minutes', 'DESC')
            ->get()
            ->getResultArray();
    }
}
