<?php

namespace App\Models\Application;

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

class ZoneReportDetail extends Model
{
    use HasFactory;

    protected $table = 'sy_zones_report_details';
    public $timestamps = false;

    protected $fillable = [
        'id',
        'fk_zone_report',
        'fk_group',
        'delivery',
        'failure',
        'subtotal',
        'recovered',
        'total',
        'sales',
        'commissionpercent',
        'commission',
        'incoming',
        'outgoing',
        'extraweek',
        'bills',
        'fund',
        'comments',
        'visible',
        'available',
        'fk_usercreator',
        'created_at',
        'fk_userupdater',
        'updated_at',
        'is_active'
    ];

    protected $casts = [
        'id' => 'integer',
        'fk_zone_report' => 'integer',
        'fk_group' => 'integer',
        'delivery' => 'float',
        'failure' => 'float',
        'subtotal' => 'float',
        'recovered' => 'float',
        'total' => 'float',
        'sales' => 'float',
        'commissionpercent' => 'float',
        'commission' => 'float',
        'incoming' => 'float',
        'outgoing' => 'float',
        'extraweek' => 'float',
        'bills' => 'float',
        'fund' => 'float',
        'visible' => 'boolean',
        'available' => 'boolean',
        'fk_usercreator' => 'integer',
        'created_at' => 'timestamp',
        'fk_userupdater' => 'integer',
        'updated_at' => 'timestamp',
        'is_active' => 'boolean'
    ];

    protected $hidden = [
        'fk_zone_report',
        'fk_group',
        'fk_usercreator',
        'created_at',
        'fk_userupdater',
        'updated_at',
        'is_active'
    ];

    public static function booted()
    {
        static::updated(function ($item) {
            Log::channel('zonereportdetails')->info('Zone Report Detail Item Updated', [
                'id' => $item->id,
                'fk_userupdater' => $item->fk_userupdater,
                'updated_at' => Carbon::now(),
                'changes' => $item->getChanges()
            ]);
        });
    }

    public function zone_report()
    {
        return $this->hasOne(ZoneReport::class, 'id', 'fk_zone_report');
    }

    public function group()
    {
        return $this->hasOne(Group::class, 'id', 'fk_group');
    }

    public function user_creator()
    {
        return $this->hasOne(User::class, 'id', 'fk_usercreator')->select('id', 'username');
    }

    public function user_updater()
    {
        return $this->hasOne(User::class, 'id', 'fk_userupdater')->select('id', 'username');
    }
}
