<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;

class Visit extends Model
{
    protected $table = 'visits';
    protected $fillable = [
        'user_id',
        'check_in_id',
        'customer_type_id',
        'customer_id',
        'note',
        'image',
        'lat',
        'lng',
    ];

    protected function casts(): array
    {
        return [
            'user_id' => 'int',
            'check_in_id' => 'int',
            'customer_type_id' => 'int',
            'customer_id' => 'int',
            'note' => 'string',
            'image' => 'string',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

    protected function imageFullPath(): Attribute
    {
        return Attribute::make(
            get: function () {
                if (!$this->image) return null;

                return Storage::url('visit/'.$this->avatar);
            }
        );
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function customer(): BelongsTo {
        return $this->belongsTo(Customer::class);
    }

    public function customerType(): BelongsTo {
        return $this->belongsTo(CustomerType::class);
    }

    protected function createdAtWib(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => Carbon::parse($attributes['created_at'])
                ->timezone('Asia/Jakarta')
                ->format('d/m/Y H:i:s'),
        );
    }

    protected function createdAtDate(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => Carbon::parse($attributes['created_at'])
                ->timezone('Asia/Jakarta')
                ->format('d/m/Y'),
        );
    }

    protected function createdAtTime(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => Carbon::parse($attributes['created_at'])
                ->timezone('Asia/Jakarta')
                ->format('H:i:s'),
        );
    }
}
