<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Sale extends Model
{
    protected $primaryKey = 'id_sales';
    protected $table = 'sales';
    protected $fillable = [
        'business_id',
        'good_receipts_truck_id',
        'customer_id',
        'date',
        's_no',
        'bill_no',
        'details',
        'bori_details',
        'balance',
        'paid',
        'total_amount',
        'status',
        'created_by',
    ];
    protected $casts = [

        'date' => 'datetime'

    ];

    public function goodReceiptTruck()
    {
        return $this->belongsTo(GoodReceiptTruck::class, 'good_receipts_truck_id');
    }

    public function customer()
    {
        return $this->belongsTo(Customer::class, 'customer_id');
    }

    public function salesItemsDetails()
    {
        return $this->hasMany(SalesItemDetail::class, 'sales_id');
    }

    public function salesPerBoriWeight()
    {
        return $this->hasMany(SalesPerBoriWeight::class, 'sales_id');
    }

    public function goodReceiptDetails()
    {
        return $this->hasManyThrough(GoodReceiptDetail::class, SalesItemDetail::class, 'sales_id', 'id_grd', 'id_sales', 'good_detail_id');
    }
    public function productMainCate()
    {
        return $this->belongsTo(ProductsCategoryMain::class, 'items_main_cate', 'id_pro_cate_main');
    }

    public function productParentCate()
    {
        return $this->belongsTo(ProductsSubCategoryParent::class, 'items_parent_cate', 'id_pro_sub_cat_parent');
    }

    public function productChildCate()
    {
        return $this->belongsTo(ProductsSubCategoryChild::class, 'items_child_cate', 'id_pro_sub_cat_child');
    }
    public function createdBy()
    {
        return $this->belongsTo(User::class,  'created_by');
    }

    public function customerBalance()
    {
        return self::where('customer_id', $this->customer_id)->sum('balance');
    }

    private function cleanDecimal($value)
    {
        $trim = rtrim(rtrim($value, '0'), '.');
        return $trim;
    }


    public function getPaidAttribute($value)
    {
        return $this->cleanDecimal($value);
    }
    public function getTotalAmountAttribute($value)
    {
        return $this->cleanDecimal($value);
    }

    public function getBalanceAttribute($value)
    {
        return $this->cleanDecimal($value);
    }
}
