<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Log;

class CustomerAccount extends Model
{
    use HasFactory;
    protected $guarded = ['id'];
    protected $table = 'customer_accounts';

    public function clients()
    {
        return $this->belongsTo(Client::class, 'client_id', 'id');
    }


    public function clientsInfo()
    {
        return $this->belongsTo(Clientsinfo::class, 'client_id', 'client_id');
    }

    public function getIsDueAmountNegativeAttribute()
    {
        return $this->attributes['dueAmount'] < 0;
    }

    static function updateCustomrAccount($id, $due = 0, $payment = 0, $discount = 0, $totalbill = 0)
    {

        $account = CustomerAccount::whereClient_id($id);

        // dd($due);

        if ($discount > 0) {
            $due = $due - $discount;
        }

        if ($account->count() < 1) {

            return CustomerAccount::create([
                'client_id'       => $id,
                'totalPaid'       => $payment,
                'dueAmount'       => $due,
                'totalDiscount'   => $discount,
                'totalBillAmount' => $due
            ]);
        } else {

            $account->increment('dueAmount', $due);
            $account->increment('totalPaid', $payment);
            $account->increment('totalDiscount', $discount);
            $account->increment('totalBillAmount', $totalbill);
        }
        // Log::info($id.' Customer Account Updated');
        return true;
    }
}
