<?php

namespace App\Models;

class SiteDiary extends BaseModel
{
    protected $fillable = [
        'site_id',
        'customer_id',
        'workspace_id',
        'diary_date',
        'weather',
        'work_log',
        'notes',
        'created_by',
        'summary',
        'created_by_type',
        'del',
    ];

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

    protected $appends = [
        'creator_info',
    ];

    protected $casts = [
        'diary_date' => 'date'
    ];

    // Log relationship
    public function logs()
    {
        return $this->morphMany(SiteDiaryLog::class, 'loggable');
    }

    // All logs for this diary and its related models
    public function allLogs()
    {
        return $this->hasMany(SiteDiaryLog::class, 'site_diary_id');
    }

    // Relationships
    public function site()
    {
        return $this->belongsTo(Sites::class, 'site_id')->select('id', 'title', 'description', 'longitude', 'latitude');
    }

    public function equipment()
    {
        return $this->hasMany(SiteDiaryEquipment::class, 'site_diary_id');
    }

    public function tasks()
    {
        return $this->hasMany(SiteDiaryTask::class, 'site_diary_id');
    }

    public function images()
    {
        return $this->hasMany(SiteDiaryImage::class, 'site_diary_id');
    }

    public function createdByCustomer()
    {
        return $this->belongsTo(User::class, 'created_by')->select('id', 'name', 'email');
    }

    public function createdByEmployee()
    {
        return $this->belongsTo(EmpPersonalDetails::class, 'created_by', 'emp_id')
            ->select('emp_id', 'first_name', 'middle_name', 'last_name');
    }

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