<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Casts\Attribute;

#[Fillable(['shipping', 'tax', 'user_id', 'state_id', 'payment', 'reference', 'pick', 'total'])]
class Order extends Model
{
    use HasFactory;

    /**
     * @return HasMany
     */
    public function addresses(): HasMany
    {
        return $this->hasMany(OrderAddress::class);
    }

    /**
     * @return HasMany
     */
    public function products(): HasMany
    {
        return $this->hasMany(OrderProduct::class);
    }

    /**
     * @return BelongsTo
     */
    public function state(): BelongsTo
    {
        return $this->belongsTo(State::class);
    }

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

    /**
     * @return HasOne
     */
    public function payment_infos(): HasOne
    {
        return $this->hasOne(Payment::class);
    }

    /**
     * @return Attribute
     */
    protected function paymentText(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => match ($attributes['payment']) {
                'carte' => 'Carte bancaire',
                'virement' => 'Virement',
                'cheque' => 'Chèque',
                'mandat' => 'Mandat administratif',
                default => $value,
            },
        );
    }

    /**
     * @return Attribute
     */
    protected function totalOrder(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) => $attributes['total'] + $attributes['shipping'],
        );
    }

    /**
     * @return Attribute
     */
    protected function tva(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) =>
            $attributes['tax'] > 0 ? $attributes['total'] / (1 + $attributes['tax']) * $attributes['tax'] : 0,
        );
    }

    /**
     * @return Attribute
     */
    protected function ht(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) =>
                $attributes['total'] / (1 + ($attributes['tax'] ?? 0)),
        );
    }
}
