<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    protected $fillable = [
        'firstname',
        'lastname',
        'phone_number',
        'adress',
        'taxNumber',
    ];

    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    public function discounts()
    {
        return $this->hasMany(Discount::class);
    }

    /**
     * Calculate remaining credit for the client
     * remaining_credit = SUM(orders.total_price) - (SUM(payments.amount) + SUM(discounts.amount))
     * All payments and discounts reduce the remaining credit.
     */
    public function getRemainingCreditAttribute()
    {
        $totalOrders = $this->orders()->sum('total_price');
        $totalPayments = $this->payments()->sum('amount');
        $totalDiscounts = $this->discounts()->sum('amount');
        
        return $totalOrders - ($totalPayments + $totalDiscounts);
    }

    /**
     * Get total amount of all orders
     */
    public function getTotalOrdersAttribute()
    {
        return $this->orders()->sum('total_price');
    }

    /**
     * Get total amount of all payments
     */
    public function getTotalPaymentsAttribute()
    {
        return $this->payments()->sum('amount');
    }

    /**
     * Get total amount of pending payments
     */
    public function getTotalPendingPaymentsAttribute()
    {
        return $this->payments()->where('status', 'pending')->sum('amount');
    }

    /**
     * Get total amount of validated payments
     */
    public function getTotalValidatedPaymentsAttribute()
    {
        return $this->payments()->where('status', 'validated')->sum('amount');
    }

    /**
     * Get total amount of all discounts
     */
    public function getTotalDiscountsAttribute()
    {
        return $this->discounts()->sum('amount');
    }

    /**
     * Apply a discount to the client
     * 
     * @param float $amount The discount amount
     * @param string|null $reason Optional reason for the discount
     * @return Discount
     */
    public function applyDiscount(float $amount, string $reason = null)
    {
        return $this->discounts()->create([
            'amount' => $amount,
            'reason' => $reason,
            'date' => now(),
        ]);
    }
}
