<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class AcReceipt extends Model
{
    use HasFactory, SoftDeletes;


    protected $fillable =[
        'receipt_no',
        'overall_receipt_no',
        'receipt_date',
        'remarks',
        'company_id',
        'created_by',
        'updated_by',
        'deleted_by',
        'voucher_status',
        'last_voucher_count',
        'last_voucher_type_count',
        'voucher_id',
        'financial_year_id',
        'module_code',
        'receipt_time',
        'advance_received',
        'settlement_status',
        'settlement_module_code',
        'settlement_voucher_id',
    ];

    public function accountReceiptDetail(){
        return $this->hasOne(AcReceiptDetail::class,'voucher_id','id')->with('account','voucherType');
    }

    public function opdBooking(){
        return $this->hasOne(OpdBookings::class,'id','voucher_id');
    }

    public function salesVoucher(){
        return $this->hasOne(SaleInvoice::class,'id','voucher_id');
    }


    public function accountReceiptTransaction(){
        return $this->hasMany(AcReceiptDetail::class,'voucher_id','id');
    }

    public function accountReceiptReceivedAmount(){
        return $this->hasMany(AcReceiptDetail::class,'voucher_id','id')
        ->select(['amount','id','voucher_id'])
        ->where('transaction_type','CREDIT');
    }


    public function company(){
        return $this->hasOne(Company::class,'id','company_id');
    }

    public function user(){
        return $this->hasOne(User::class,'id','created_by');
    }

    static public function createAcReceipt($values = [])
    {
        $receipt = AcReceipt::create([
            'receipt_no'              => ($values['receipt_no'] ?? ''),
            'overall_receipt_no'      => ($values['overall_receipt_no'] ?? ''),
            'receipt_date'            => date('Y-m-d'),
            'remarks'                 => ($values['remarks'] ?? ''),
            'company_id'              => \Auth::user()->company_id ?? '',
            'created_by'              => \Auth::id() ?? '',
            'voucher_id'              => $values['voucher_id'], // voucher_id LIKE sale_invoice_id, Or receipt_id etc
            'voucher_status'          => true,
            'last_voucher_count'      => ($values['last_voucher_count'] ?? ''),
            'last_voucher_type_count' => ($values['last_voucher_type_count'] ?? ''),
            'financial_year_id'       => ($values['financial_year_id'] ?? ''),
            'module_code'             => $values['module_code']
        ]);

        $voucher_collection = VoucherCollection::create([
            'collection_date'   => date('Y-m-d'),
            'module_code'       => 'RECEIPT',
            'voucher_master_id' => ($values['voucher_master_id'] ?? ''),
            'voucher_id'        => $values['receipt_no'], // voucher_id LIKE sale_invoice_id, Or receipt_id etc
            'voucher_type'      => 'SALE', // SALE, PURCHASE, PAYMENT
            'money_receipt_id'  => $receipt->id,
            'created_by'        => \Auth::user()->id,
        ]);

        if ($receipt) {
            $receipt_details = AcReceiptDetail::create([
                'payment_mode_id'     => ($values['payment_mode_id'] ?? ''),
                'voucher_master_id'   => ($values['voucher_master_id'] ?? ''),
                'voucher_id'          => ($receipt->id ?? ''),
                'voucher_type'        => ($values['voucher_type'] ?? ''),
                'module_id'           => ($values['module_id'] ?? ''),
                'account_id'          => ($values['account_id'] ?? ''),
                'transaction_type'    => 'CREDIT',
                'details_narration'   => "",
                'amount'              => ($values['amount'] ?? ''),
                'created_by'          => \Auth::id() ?? '',
                'company_id'          => \Auth::user()->company_id ?? '',
                'transactions_status' => true,
            ]);
            $receipt_details = AcReceiptDetail::create([
                'payment_mode_id'     => ($values['payment_mode_id'] ?? ''),
                'voucher_master_id'   => ($values['voucher_master_id'] ?? ''),
                'voucher_id'          => ($receipt->id ?? ''),
                'voucher_type'        => ($values['voucher_type'] ?? ''),
                'module_id'           => ($values['module_id'] ?? ''),
                'account_id'          => ($values['payment_mode_id'] ?? ''),
                'transaction_type'    => 'DEBIT',
                'details_narration'   => "",
                'amount'              => ($values['amount'] ?? ''),
                'created_by'          => \Auth::id() ?? '',
                'company_id'          => \Auth::user()->company_id ?? '',
                'transactions_status' => true,
            ]);

            $voucher_collection_detail = VoucherCollectionDetail::create([
                'voucher_collection_id' => $voucher_collection->id,
                'transaction_id'        => ($values['transaction_id'] ?? ''),
            ]);

            return true;
        }
    }

    static public function updateAcReceipt($values = [])
    {

        $receipt = AcReceipt::where([
                'voucher_id' => $values['voucher_id'],
                'module_code'  => $values['module_code']
            ])->first();

        if (!$receipt) {
            return AcReceipt::createAcReceipt($values);
        }

        $voucher_collection = VoucherCollection::where(['money_receipt_id' => $receipt->id])->first();

        $voucher_collection->update([
                'updated_by' => \Auth::user()->id,
            ]);

        if ($receipt) {
            $receipt_details = AcReceiptDetail::where([
                'voucher_id'       => ($receipt->id ?? ''),
                'account_id'       => ($values['account_id'] ?? ''),
                'transaction_type' => 'CREDIT',
            ])->first();

            $amount = $receipt_details->amount ?? 0;
            $received = $values['amount'] ?? 0;

            $receipt_details = $receipt_details->update([
                'amount' => ($amount + $received),
            ]);

            $receipt_details = AcReceiptDetail::create([
                'payment_mode_id'     => ($values['payment_mode_id'] ?? ''),
                'voucher_master_id'   => ($values['voucher_master_id'] ?? ''),
                'voucher_id'          => ($receipt->id ?? ''),
                'voucher_type'        => ($values['voucher_type'] ?? ''),
                'module_id'           => ($values['module_id'] ?? ''),
                'account_id'          => ($values['payment_mode_id'] ?? ''),
                'transaction_type'    => 'DEBIT',
                'details_narration'   => "",
                'amount'              => ($values['amount'] ?? ''),
                'created_by'          => \Auth::id() ?? '',
                'company_id'          => \Auth::user()->company_id ?? '',
                'transactions_status' => true,
            ]);

            $voucher_collection_detail = VoucherCollectionDetail::create([
                'voucher_collection_id' => $voucher_collection->id,
                'transaction_id'        => ($values['transaction_id'] ?? ''),
            ]);

            return true;
        }
    }

    static public function getReceiptVouchers($filters = [])
    {
        $from_date           = $filters['from_date'] ?? '';
        $to_date             = $filters['to_date'] ?? '';
        $branch              = $filters['branch'] ?? '';
        $account             = $filters['account'] ?? '';
        $paymentMode         = $filters['paymentMode'] ?? '';
        $accountingGroup     = $filters['accountingGroup'] ?? '';
        $created_by          = $filters['created_by'] ?? '';
        $voucher_type_search = $filters['voucher_type_search'] ?? '';
        $date_before         = $filters['date_before'] ?? '';

        $accountReceipt  = self::
            select(['ac_receipts.receipt_no',
                    'ac_receipts.receipt_date',
                    'ac_receipts.company_id',
                    'ac_receipts.voucher_id',
                    'ac_receipts.module_code',
                    'ac_receipts.receipt_time',
                    'ac_receipts.id',
                    'U.prepared_by',
                    'voucher_types.name as voucher_type',
                    'accounts.name as account_name',
                    'credit_account.name as credit_account_name',
                    'account_titles.name as account_title',
                    'opd_bookings.booking_no',
                    'opd_bookings.booking_date_time',
                    'sale_invoices.main_invoice_no',
                    'sale_invoices.created_at as invoice_created_at',
                    // 'ac_receipt_details.id',
                    'ac_receipt_credit.id as ac_receipt_details_id',
                    // 'ac_receipt_details.id as ac_receipt_details_id',
                    'ac_receipt_details.transaction_type',
                    'ac_receipt_details.amount',
                    'payment_modes.mode as payment_mode',
            ])
            ->leftJoin('users as U','U.id','=','ac_receipts.created_by')
            ->leftJoin('ac_receipt_details','ac_receipt_details.ac_receipt_id','=','ac_receipts.id')
            ->leftJoin('voucher_types','ac_receipt_details.voucher_type','=','voucher_types.code')
            ->leftJoin('accounts','ac_receipt_details.account_id','=','accounts.id')
            ->leftJoin('opd_bookings', 'opd_bookings.id', '=', 'ac_receipts.voucher_id')
            ->leftJoin('sale_invoices', 'sale_invoices.id', '=', 'ac_receipts.voucher_id')
            ->leftJoin('payment_modes', 'payment_modes.id', '=', 'ac_receipt_details.transaction_mode_id')

            ->leftJoin('ac_receipt_details as ac_receipt_credit',function($join) {
                $join->on('ac_receipt_credit.voucher_id','=','ac_receipts.id')->where('ac_receipt_credit.transaction_type','CREDIT');
            })
            ->leftJoin('accounts as credit_account','ac_receipt_credit.account_id','=','credit_account.id')
            ->leftJoin('account_titles', 'account_titles.id', '=', 'credit_account.account_title_id')
            // ->with('accountReceiptTransaction')
            ->when($from_date != '' && $to_date != '', function($query) use($from_date, $to_date) {
                $query->whereBetween('ac_receipts.receipt_date', [
                    date('Y-m-d', strtotime($from_date)),
                    date('Y-m-d', strtotime($to_date))
                ]);
            })
            ->when($from_date != '' && $to_date == '', function ($query) use ($from_date) {
                $query->whereDate('ac_receipts.receipt_date', 
                    date('Y-m-d', strtotime($from_date)));  
            })
            ->when($date_before != '' , function ($query) use ($date_before) {
                $query->whereDate('ac_receipts.receipt_date', '<',
                    date('Y-m-d', strtotime($date_before)));
            })
            ->when($branch != '', function($query) use($branch) {
                $query->where('ac_receipts.company_id', $branch);
            })
            ->when($account != '', function($query) use($account) {
                $query->where('ac_receipt_details.account_id', $account);
            })

            ->when($created_by != '', function($query) use($created_by) {
                $query->where('ac_receipts.created_by', $created_by);
            })

            ->when($voucher_type_search != '', function($query) use($voucher_type_search) {
                $query->where('ac_receipt_details.voucher_type', $voucher_type_search);
            })

            ->when($paymentMode != '', function($query) use($paymentMode) {
                $query->where('ac_receipt_details.transaction_mode_id', $paymentMode);
            })
            ->groupBy('ac_receipt_details.id')
            ->orderBy('ac_receipt_details.id', 'ASC')
            ->get()
            /*->groupBy('id')
            ->map(function ($accountReceipt, $id) {
                $details = AcReceiptDetail::select([
                        'ac_receipt_details.id',
                        'ac_receipt_details.transaction_type',
                        'ac_receipt_details.amount',
                        'payment_modes.mode as payment_mode',
                    ])
                    ->leftJoin('payment_modes', 'payment_modes.id', '=', 'ac_receipt_details.transaction_mode_id')
                    ->where([
                        'ac_receipt_details.ac_receipt_id' => $id
                    ])
                    // ->whereNot([
                    //     'ac_receipt_details.transaction_type' => 'CREDIT',
                    // ])
                    ->get();

                return [
                    'accountReceipt' => $accountReceipt,
                    'details'        => $details
                ];
            })*/;

        return $accountReceipt;

    }
}
