<?php

namespace App\Models;

class SiteDiaryLog extends BaseModel
{
    protected $table = 'site_diary_logs';

    protected $fillable = [
        'site_diary_id',
        'loggable_type',
        'loggable_id',
        'user_id',
        'emp_id',
        'action_type',
        'old_values',
        'new_values',
        'notes',
        'customer_id',
        'workspace_id',
        'created_by_type',
    ];

    protected $casts = [
        'old_values' => 'json',
        'new_values' => 'json',
        'action_type' => 'string', // Ensure action_type is treated as string
    ];

    protected $appends = [
        'creator_info',
    ];

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

    // Polymorphic relationship to the model being logged
    public function loggable()
    {
        return $this->morphTo();
    }

    // Main site diary relationship
    public function siteDiary()
    {
        return $this->belongsTo(SiteDiary::class);
    }

    // User who made the change (if it was a customer user)
    public function createByUser()
    {
        return $this->belongsTo(User::class, 'user_id', 'id')->select('id', 'name', 'email');
    }

    // Employee who made the change (if it was an employee)
    public function createByEmployee()
    {
        return $this->belongsTo(EmpPersonalDetails::class, 'emp_id', 'emp_id')
            ->select('emp_id', 'first_name', 'last_name');
    }

    public function getCreatorInfoAttribute()
    {
        if ($this->created_by_type === 'employee') {
            $employee = $this->createByEmployee;
            if ($employee) {
                return [
                    'id' => $employee->emp_id,
                    'name' => trim($employee->first_name . ' ' . $employee->last_name),
                    'email' => null // Add email if available in employee details
                ];
            }
        } else {
            $user = $this->createByUser;
            if ($user) {
                return [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email
                ];
            }
        }
        return null;
    }


}
