<?php

namespace App\Models\Ecommerce\Payouts;

use App\Models\Ecommerce\Channel\Channel;
use App\Models\Ecommerce\Product\Order\OrderItem;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;

class Payout extends Model
{
    use HasFactory;

    /**
     * Protected fields
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $fillable = [
        'channel_id',
        'start_date',
        'end_date',
        'total_sum',
        'postshop_total',
        'entrepreneur_total',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
    ];

    /**
     * Related channel
     */
    public function channel(): BelongsTo
    {
        return $this->belongsTo(Channel::class);
    }

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::updated(function ($payout) {
            $order_item_ids = [];

            foreach ($payout->order_items_ids as $key => $value) {
                if (! $value) {
                    $order_item_ids[] = $key;
                }
            }

            DB::table('payout_items')
                ->where('payout_id', $payout->id)
                ->whereIntegerInRaw('order_item_id', $order_item_ids)
                ->delete();
        });
    }

    /**
     * Order items
     */
    public function orderItems(): BelongsToMany
    {
        return $this->belongsToMany(OrderItem::class, 'payout_items');
    }
}
