<?php

namespace App\Models\Stocks;

use App\Models\Company;
use App\Models\PaymentTerm;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class StockOut extends Model
{
    use HasFactory,SoftDeletes;
    protected $fillable = [
        'main_invoice_no',
        'branch_invoice_no',
        'voucher_type_invoice_no',
        'invoice_date',
        'voucher_type_code',
        'voucher_type_id',
        'patient_id',
        'doctor_id',
        'collection_agent_id',
        'refferal_lab_id',
        'reff_no',
        'payment_term_id',
        'order_date',
        'remarks',
        'broker_id',
        'operator_id',
        'company_id',
        'status',
        'financial_year_id',
        'industry_type_id',
        'dispatch_from_id',
        'ship_to_id',
        'tracking_id',
        'special_case_id',
        'last_voucher_count',
        'bussiness_source_id',
        'payment_mode_id',
        'last_voucher_type_count',
        'invoice_type',
        'transaction_mode_id',
        'updated_by',
        'deleted_by',
        'bill_to_account_id',
        'tpa_corporate_id',
        'last_branch_count',
    ];

    public function getStockOutInvoiceDetail()
    {
        return $this->hasMany(StockOutDetail::class,'invoice_id','id');
    }

    public function getStockOutInvoiceBasicAmt()
    {
        return $this->hasOne(StockOutDetail::class,'invoice_id','id')->select(['invoice_id','id',DB::raw('SUM(customer_amount) as basic_amount')])->groupBy('invoice_id');;
    }
    public function getInvoiceDetails()
    {
        return $this->hasMany(StockOutDetail::class,'invoice_id','id');
    }

    public function getCreatedBy()
    {
        return $this->hasOne(User::class, 'id', 'operator_id');
    }
    public function getCompany()
    {
       return $this->belongsTo(Company::class,'company_id')->with('getCompanyAddress')->with('getCompanybank');
    }
    public function getPaymentTerm()
    {
       return $this->belongsTo(PaymentTerm::class,'payment_term_id');
    }

    public function getInvoiceDiscounts()
    {
        return $this->hasOne(StockOutDetail::class,'invoice_id','id')->select(['invoice_id','batch_id',\DB::raw('SUM(discount_amount) as discount_amount')])->groupBy('invoice_id');;
    }

    

}
