<?php

namespace App\Models;

use CodeIgniter\Model;

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

    protected $allowedFields = [
        'employee_id', 'asset_type_id', 'asset_name', 'identifier', 'quantity',
        'assigned_date', 'returned_date', 'status', 'condition_on_assign',
        'condition_on_return', 'notes', 'assigned_by', 'returned_by',
        'created_by', 'updated_by',
    ];

    protected $validationRules = [
        'employee_id'    => 'required|integer',
        'asset_type_id'  => 'required|integer',
        'asset_name'     => 'required|min_length[1]|max_length[200]',
        'assigned_date'  => 'required|valid_date[Y-m-d]',
        'status'         => 'permit_empty|in_list[assigned,returned,lost,damaged]',
        'quantity'       => 'permit_empty|decimal',
    ];

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

        if ($assetTypeId) {
            $this->where('employee_asset_assignments.asset_type_id', $assetTypeId);
        }

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

        if ($search) {
            $this->groupStart()
                ->like('employee_asset_assignments.asset_name', $search)
                ->orLike('employee_asset_assignments.identifier', $search)
                ->groupEnd();
        }

        return $this;
    }

    public function getForEmployee(int $employeeId, ?string $status = null): array
    {
        $builder = $this->select('employee_asset_assignments.*, asset_types.name as type_name, asset_types.code as type_code, asset_types.category')
            ->join('asset_types', 'asset_types.id = employee_asset_assignments.asset_type_id')
            ->where('employee_asset_assignments.employee_id', $employeeId);

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

        return $builder->orderBy('employee_asset_assignments.assigned_date', 'DESC')->findAll();
    }

    public function getActiveForEmployee(int $employeeId): array
    {
        return $this->getForEmployee($employeeId, 'assigned');
    }
}
