<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use App\Models\User;

class EmployeeAttendance extends BaseModel
{
    use HasFactory;
    protected $fillable = [
        'employee_id',
        'site_id',
        'added_by',
        'status',
        'approved_by',
        'check_in',
        'check_out',
        'date',
        'working_hours',
        'image',
        'customer_id',
        'workspace_id',
    ];

    protected $hidden = [
        'customer_id',
        'workspace_id',
    ];

     protected $appends = ['type']; // 👈 Add this line

    /**
     * Override setAttribute to handle datetime fields properly
     */
    public function setAttribute($key, $value)
    {
        // Handle time fields (check_in, check_out) - store only time in HH:mm format
        if (in_array($key, ['check_in', 'check_out']) && $value) {
            try {
                // Parse the datetime value and extract only the time part
                $carbonDate = \Carbon\Carbon::parse($value);
                $this->attributes[$key] = $carbonDate->format('H:i'); // Store only time in 24-hour format
                return $this;
            } catch (\Exception $e) {
                // If parsing fails, try to extract time from various formats
                if (is_string($value)) {
                    // Try to match time patterns
                    if (preg_match('/(\d{1,2}):(\d{2})(?::\d{2})?\s*(AM|PM)?/i', $value, $matches)) {
                        $hour = (int)$matches[1];
                        $minute = $matches[2];
                        $ampm = isset($matches[3]) ? strtoupper($matches[3]) : null;
                        
                        // Convert 12-hour to 24-hour format if needed
                        if ($ampm === 'PM' && $hour < 12) {
                            $hour += 12;
                        } elseif ($ampm === 'AM' && $hour == 12) {
                            $hour = 0;
                        }
                        
                        $this->attributes[$key] = sprintf('%02d:%02d', $hour, $minute);
                        return $this;
                    }
                }
                
                // If all parsing fails, let parent handle it
                Log::warning("Failed to parse time for field '{$key}' with value '{$value}': " . $e->getMessage());
            }
        }
        
        return parent::setAttribute($key, $value);
    }

    /**
     * Override toArray to format check_in and check_out according to system settings
     */
    public function toArray()
    {
        $array = parent::toArray();
        
        // Get system time format settings
        $systemTimeFormat = $this->getSystemTimeFormat();
        
        // Format check_in and check_out according to system settings
        if (isset($array['check_in']) && $array['check_in']) {
            try {
                // Check if it's already in time-only format (HH:mm)
                if (preg_match('/^(\d{1,2}):(\d{2})$/', $array['check_in'], $matches)) {
                    $hour = (int)$matches[1];
                    $minute = (int)$matches[2];
                    
                    // Create a Carbon instance with today's date and the stored time
                    $carbonDate = \Carbon\Carbon::createFromTime($hour, $minute);
                    $array['check_in'] = $carbonDate->format($systemTimeFormat);
                } else {
                    // Handle old datetime format (extract time only)
                    $carbonDate = \Carbon\Carbon::parse($array['check_in']);
                    $array['check_in'] = $carbonDate->format($systemTimeFormat);
                }
            } catch (\Exception $e) {
                // Keep original value if parsing fails
            }
        }
        
        if (isset($array['check_out']) && $array['check_out']) {
            try {
                // Check if it's already in time-only format (HH:mm)
                if (preg_match('/^(\d{1,2}):(\d{2})$/', $array['check_out'], $matches)) {
                    $hour = (int)$matches[1];
                    $minute = (int)$matches[2];
                    
                    // Create a Carbon instance with today's date and the stored time
                    $carbonDate = \Carbon\Carbon::createFromTime($hour, $minute);
                    $array['check_out'] = $carbonDate->format($systemTimeFormat);
                } else {
                    // Handle old datetime format (extract time only)
                    $carbonDate = \Carbon\Carbon::parse($array['check_out']);
                    $array['check_out'] = $carbonDate->format($systemTimeFormat);
                }
            } catch (\Exception $e) {
                // Keep original value if parsing fails
            }
        }
        
        return $array;
    }

    public function empcompanydetails()
    {
        return $this->belongsTo(EmpCompanyDetails::class, 'employee_id', 'id');
    }

    // 👇 Accessor for appending `type`
    public function getTypeAttribute()
    {
        $userType = optional($this->empcompanydetails)->user_type;

        if ($userType == 0) {
            return 'internal';
        } elseif ($userType == 1) {
            return 'external';
        }

        return null; // fallback
    } 
    
    
    public function empPersonalDetails()
    {
        return $this->belongsTo(EmpPersonalDetails::class,'employee_id', 'emp_id');
    }

    public function empTeamsMembers()
    {
        return $this->hasMany(EmpTeamsMember::class, 'emp_id', 'employee_id')->with('empTeamsList');
    }


    public function addedby()
    {
        return $this->belongsTo(EmpPersonalDetails::class, 'added_by', 'emp_id')
            ->withDefault(function ($model, $parent) {
                // If added_by is 0, get admin user from customer_id
                if ($parent->added_by == 0) {
                    $admin = User::where('id', $parent->customer_id)->first();
                    if ($admin) {
                        // Create a new EmpPersonalDetails instance with admin data
                        $empModel = new EmpPersonalDetails();
                        $empModel->fill([
                            'id' => $admin->id,
                            'emp_id' => $admin->id,
                            'first_name' => $admin->name,
                            'middle_name' => '',
                            'last_name' => '',
                            'mobile' => $admin->mobile_number,
                            'image' => $admin->avatar,
                            'streat_address' => '',
                            'suburb' => '',
                            'state' => '',
                            'postcode' => '',
                            'date_of_birth' => null,
                            'blood_group' => '',
                            'bank_name' => '',
                            'account_holder_name' => '',
                            'ibn_number' => '',
                            'account_number' => '',
                            'created_by' => $admin->created_by,
                            'del' => '0',
                            'created_at' => null,
                            'updated_at' => null,
                        ]);
                        
                        // Add a custom attribute to identify this as admin
                        $empModel->setAttribute('is_admin', true);
                        $empModel->exists = true; // Mark as existing to prevent save operations
                        
                        return $empModel;
                    }
                }
                return new EmpPersonalDetails();
            });
    }

    public function sites()
    {
        return $this->belongsTo(Sites::class,'site_id');
    }
    public function breaks()
    {
        return $this->hasMany(EmployeeBreak::class, 'emp_attendance_id');
    }
    public function rosterassign()
    {
        return $this->HasOne(RosterAssign::class,'assign_to','employee_id');
    }
    public function assignto()
    {
        return $this->HasOne(EmpPersonalDetails::class,'employee_id','assign_to');
    }

    public function present_employee_details()
    {
        return $this->belongsTo(EmpPersonalDetails::class,'employee_id', 'emp_id')->select('emp_id','first_name','middle_name','last_name','image');
    }
    public function present_employee_company_details()
    {
        return $this->belongsTo(EmpCompanyDetails::class, 'employee_id', 'id')->select('id', 'employee_email', 'access_role');
    }
    public function employee_site()
    {
        return $this->belongsTo(Sites::class,'site_id')->select('id','title');
    }

    /**
     * Get system time format from settings
     */
    private function getSystemTimeFormat()
    {
        try {
            // Get settings from authenticated user's context
            $customerId = auth()->id();
            $setting = \App\Models\Adminsettings::where('key', 'system_time_format')
                ->where('customer_id', $customerId)
                ->first();
            
            if ($setting && $setting->value) {
                // Check if the format contains AM/PM
                if (str_contains(strtoupper($setting->value), 'AM') || str_contains(strtoupper($setting->value), 'PM')) {
                    return 'g:i A'; // 12-hour format with AM/PM
                }
            }
        } catch (\Exception $e) {
            // Log error but continue with default
        }
        return 'H:i'; // Default 24-hour format
    }
}
