<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class LeaveCredit extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'leave_credits';  // ✅ FIXED: plural name
    protected $primaryKey = 'LC_id';
    public $timestamps = true;

    protected $fillable = [
        'LC_Code',
        'LT_Id',
        'Fr_Date',
        'To_Date',
        'Dsg_Id',
        'Dpt_Id',
        'PRB_id',
        'Est_Id',
        'ETy_Id',
        'Emp_Id',
        'Tot_Emps',
        'Acr_Plcy',
        'Acr_Days',
        'Documents',
        'Act_Id',
        'created_at',
        'updated_at',
        'deleted_at'
    ];

    protected $casts = [
        'Dsg_Id' => 'array',
        'Dpt_Id' => 'array',
        'Emp_Id' => 'array',
        'Documents' => 'array',
        'Fr_Date' => 'date',
        'To_Date' => 'date',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime'
    ];

    protected $appends = [
        'departments_list',
        'designations_list',
        'employees_list'
    ];

    /* ================= ACCESSORS ================= */

    public function getDepartmentsListAttribute()
    {
        if (empty($this->Dpt_Id)) {
            return collect([]);
        }
        return Department::whereIn('Dpt_id', $this->Dpt_Id)->get();
    }

    public function getDesignationsListAttribute()
    {
        if (empty($this->Dsg_Id)) {
            return collect([]);
        }
        return DesignationMaster::whereIn('Dsg_id', $this->Dsg_Id)->get();
    }

    public function getEmployeesListAttribute()
    {
        if (empty($this->Emp_Id)) {
            return collect([]);
        }
        return EmployeeMaster::whereIn('Emp_Id', $this->Emp_Id)->get();
    }

    /* ================= RELATIONSHIPS ================= */

    public function leaveType()
    {
        return $this->belongsTo(LeaveTypeMaster::class, 'LT_Id', 'LT_id');
    }

    public function payrollBill()
    {
        return $this->belongsTo(PayrollBill::class, 'PRB_id', 'PRB_id');
    }

    public function employeeStatus()
    {
        return $this->belongsTo(EmployeeStatusMaster::class, 'Est_Id', 'Est_Id');
    }

    public function employeeType()
    {
        return $this->belongsTo(EmpTypeMaster::class, 'ETy_Id', 'ETy_Id');
    }

    public function action()
    {
        return $this->belongsTo(ActionMaster::class, 'Act_Id', 'Act_Id');
    }

    /* ================= HELPER METHODS ================= */

   public static function generateCode()
{
    $lastRecord = self::orderBy('LC_id', 'desc')->first();

    if (!$lastRecord) {
        $number = 1;
    } else {
        $lastCode = $lastRecord->LC_Code;
        $lastNumber = intval(substr($lastCode, 2)); // Skip 'LC'
        $number = $lastNumber + 1;
    }

    // Format: LC + 8-digit number (total 10 chars)
    return 'LC' . str_pad($number, 8, '0', STR_PAD_LEFT);
}
    /**
     * ✅ Get filtered employees with JSON search for departments
     */
    public static function getFilteredEmployees($filters)
    {
        $query = EmployeeMaster::query();

        // Filter by Payroll Bill (through profile)
        if (!empty($filters['PRB_id'])) {
            $query->whereHas('profile', function($q) use ($filters) {
                $q->where('PBillNo', $filters['PRB_id']);
            });
        }

        // ✅ Department filter with JSON search
        if (!empty($filters['Dpt_Id']) && is_array($filters['Dpt_Id'])) {
            $query->whereHas('profile', function($q) use ($filters) {
                $q->where(function($subQ) use ($filters) {
                    foreach ($filters['Dpt_Id'] as $deptId) {
                        $subQ->orWhereRaw('JSON_CONTAINS(Dpt_id, \''.$deptId.'\')');
                    }
                });
            });
        }

        // Filter by Designations
        if (!empty($filters['Dsg_Id']) && is_array($filters['Dsg_Id'])) {
            $query->whereHas('profile', function($q) use ($filters) {
                $q->whereIn('Dsg_Id', $filters['Dsg_Id']);
            });
        }

        // Filter by Employee Status
        if (!empty($filters['Est_Id'])) {
            $query->whereHas('profile', function($q) use ($filters) {
                $q->where('Est_Id', $filters['Est_Id']);
            });
        }

        // Filter by Employee Type
        if (!empty($filters['ETy_Id'])) {
            $query->whereHas('profile', function($q) use ($filters) {
                $q->where('ETy_Id', $filters['ETy_Id']);
            });
        }

        // Filter by specific Employee IDs
        if (!empty($filters['Emp_Id']) && is_array($filters['Emp_Id'])) {
            $query->whereIn('Emp_Id', $filters['Emp_Id']);
        }

        // Only active employees
        $query->where('Is_Active', 1);

        return $query->get();
    }
}
