<?php

namespace App\Models;

use CodeIgniter\Model;

class RawAttLogModel extends Model
{
    protected $table            = 'raw_att_log';
    protected $primaryKey       = ['dtr_emp_id', 'log_date', 'log_time', 'log_type'];
    protected $useAutoIncrement = false;
    protected $returnType       = \App\Entities\RawAttLog::class;
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = ['dtr_emp_id', 
                                   'log_date', 
                                   'log_time', 
                                   'log_type', 
                                   'branch_code',
                                   'att_from',
                                   'att_to',];

    protected bool $allowEmptyInserts = false;

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

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

    public function assignCreatedBy(array $data)
    {
        $data['data']['created_by'] = auth()->user()->employee_id;
        return $data;
    }

    public function addBatchData($data, $ignoreDuplicate = false)
    {
        $builder = $this->db->table('raw_att_log');
        // ignore($ignoreDuplicate) will ignore duplicate data
        return $builder->ignore($ignoreDuplicate)->insertBatch($data);
    }

    public function getEmployeeDaysCount($logDataFrom, $logDataTo)
    {
        $builder = $this->db->table('raw_att_log');
        $builder->distinct()->select(['raw_att_log.dtr_emp_id', 'employee.employee_id', 'employee.last_name', 'employee.first_name', 'raw_att_log.log_date']);
        $builder->join('employee', 'employee.dtr_emp_id = raw_att_log.dtr_emp_id');
        return $builder->getWhere(['raw_att_log.log_date >='=>$logDataFrom, 'raw_att_log.log_date <='=>$logDataTo])->getResult();
    }
}
