<?php

namespace App\Models;

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

class EmpAttendance extends Model
{
    use SoftDeletes;

    protected $table = 'emp_attendance';
    protected $primaryKey = 'EA_id';

    protected $fillable = [
        'EA_Code',
        'EA_Month',
        'Fr_Year',
        'PRB_id',
        'attendance_data',
        'total_present',
        'total_absent',
        'total_wop',
        'total_weekly_off',
        'total_holiday',
        'total_working_hours',
        'total_overtime_hours',
        'total_late_days',
        'total_early_departure_days',
        'raw_shift_data',
        'raw_in_time_data',
        'raw_out_time_data',
        'raw_late_by_data',
        'raw_early_by_data',
        'raw_duration_data',
        'raw_status_data',
        'remarks',
        'Status'
    ];

    protected $casts = [
        'attendance_data' => 'array',
        'total_working_hours' => 'decimal:2',
        'total_overtime_hours' => 'decimal:2',
    ];

    // 🔗 Relations - For backward compatibility
    public function employee()
    {
        // This will return null for main record, but we'll handle in accessor
        return $this->belongsTo(EmployeeMaster::class, 'Emp_Id', 'Emp_Id');
    }

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

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

    // ✅ NEW: Get WoffPattern for a specific employee
    public function getWoffPatternForEmployee($empId)
    {
        $employee = EmployeeMaster::with('profile')->find($empId);
        if ($employee && $employee->profile && $employee->profile->WOP_id) {
            return WoffPattern::find($employee->profile->WOP_id);
        }
        return null;
    }

    // ✅ NEW: Get all employees with their details including WOP pattern
    public function getEmployeesWithDetailsAttribute()
    {
        $employees = [];
        if (is_array($this->attendance_data)) {
            foreach ($this->attendance_data as $empData) {
                $empId = $empData['Emp_Id'];
                $employee = EmployeeMaster::with('profile')->find($empId);
                if ($employee) {
                    // Get WOP pattern details
                    $woffPattern = null;
                    $wopDetails = null;

                    if ($employee->profile && $employee->profile->WOP_id) {
                        $woffPattern = WoffPattern::find($employee->profile->WOP_id);
                        if ($woffPattern) {
                            $wopDetails = $woffPattern->getFormattedPattern();
                        }
                    }

                    $employees[] = [
                        'employee' => $employee,
                        'WOP_id' => $employee->profile ? $employee->profile->WOP_id : null,
                        'woff_pattern' => $wopDetails,  // ✅ Full pattern details
                        'attendance' => $empData
                    ];
                }
            }
        }
        return $employees;
    }

    // ✅ NEW: Get employee details for a specific Emp_Id with WOP pattern
    public function getEmployeeAttendance($empId)
    {
        if (is_array($this->attendance_data)) {
            foreach ($this->attendance_data as $empData) {
                if ($empData['Emp_Id'] == $empId) {
                    $employee = EmployeeMaster::with('profile')->find($empId);

                    // Get WOP pattern details
                    $woffPattern = null;
                    $wopDetails = null;

                    if ($employee && $employee->profile && $employee->profile->WOP_id) {
                        $woffPattern = WoffPattern::find($employee->profile->WOP_id);
                        if ($woffPattern) {
                            $wopDetails = $woffPattern->getFormattedPattern();
                        }
                    }

                    return [
                        'employee' => $employee,
                        'WOP_id' => $employee && $employee->profile ? $employee->profile->WOP_id : null,
                        'woff_pattern' => $wopDetails,
                        'attendance' => $empData
                    ];
                }
            }
        }
        return null;
    }

    // ✅ NEW: Get summary with WOP pattern for API response
    public function getFormattedAttendance($empId = null)
    {
        $employees = [];

        foreach ($this->attendance_data as $empData) {
            $currentEmpId = $empData['Emp_Id'];

            // Filter by employee if specified
            if ($empId && $currentEmpId != $empId) {
                continue;
            }

            $employee = EmployeeMaster::with('profile')->find($currentEmpId);
            if (!$employee) {
                continue;
            }

            // Get WOP pattern
            $woffPattern = null;
            $wopDetails = null;
            $weeklyOffDays = [];

            if ($employee->profile && $employee->profile->WOP_id) {
                $woffPattern = WoffPattern::find($employee->profile->WOP_id);
                if ($woffPattern) {
                    $wopDetails = $woffPattern->getFormattedPattern();
                    // Get week-off dates for this month/year
                    $weeklyOffDays = $woffPattern->getWeekOffDatesForMonth($this->Fr_Year, $this->EA_Month);
                }
            }

            $employees[] = [
                'employee' => [
                    'Emp_Id' => $employee->Emp_Id,
                    'Emp_Code' => $employee->Emp_Code,
                    'First_Name' => $employee->First_Name,
                    'Last_Name' => $employee->Last_Name,
                    'profile' => $employee->profile
                ],
                'WOP_id' => $employee->profile ? $employee->profile->WOP_id : null,
                'woff_pattern' => $wopDetails,
                'weekly_off_dates' => $weeklyOffDays,
                'summary' => $empData['summary'] ?? null,
                'days' => $empData['days'] ?? []
            ];
        }

        return $employees;
    }
}
