<?php namespace App\Observers;

use App\Models\SaleInvoice;
use App\Models\VoucherType;

class SaleInvoiceObserver
{
    public function generateCode($id, $prefix, $postfix = '', $separator = '', $length = 5, $yearmonth = '')
    {
        $paddedId = str_pad($id, $length, '0', STR_PAD_LEFT);
        $yearmonth = $yearmonth != '' ? $yearmonth . $separator : '';
        $generatedCode = ($postfix == '') ? $prefix . $separator . $yearmonth . $paddedId : $prefix . $separator . $paddedId . $separator . $postfix;

        return $generatedCode;
    }

    public function creating(SaleInvoice $saleInvoice)
    {
        $company_id = \Auth::user()->company_id;

        $voucher_master = VoucherType::with('voucherSeries')->where('code', 'Sales')->first();
        if (!$voucher_master || !$voucher_master->voucherSeries) {
            throw new \Exception('Voucher Series not defined for Sales');
        }

        $voucherSeries = $voucher_master->voucherSeries;

        $branch_count = SaleInvoice::select('last_branch_count')
            ->where('company_id', $company_id)
            ->orderBy('created_at', 'DESC')
            ->first();
        $last_branch_count = $branch_count && $branch_count->last_branch_count ? $branch_count->last_branch_count + 1 : ($voucherSeries->start_from + 1 ?? 1);

        $branch_invoice_no = $this->generateCode(
            $last_branch_count,
            $voucherSeries->prefix ?? 'INV',
            $voucherSeries->postfix ?? '',
            $voucherSeries->separator ?? '-',
            $voucherSeries->length ?? 5
        );

        $voucher_count = SaleInvoice::select('last_voucher_count')
            ->orderBy('created_at', 'DESC')
            ->first();
        $last_voucher_count = $voucher_count && $voucher_count->last_voucher_count ? $voucher_count->last_voucher_count + 1 : ($voucherSeries->start_from + 1 ?? 1);

        $main_invoice_no = $this->generateCode(
            $last_voucher_count,
            $voucherSeries->prefix ?? 'INV',
            $voucherSeries->postfix ?? '',
            $voucherSeries->separator ?? '-',
            $voucherSeries->length ?? 5
        );

        while (SaleInvoice::where('main_invoice_no', $main_invoice_no)->exists()) {
            $last_voucher_count++;
            $main_invoice_no = $this->generateCode(
                $last_voucher_count,
                $voucherSeries->prefix ?? 'INV',
                $voucherSeries->postfix ?? '',
                $voucherSeries->separator ?? '-',
                $voucherSeries->length ?? 5
            );
        }

        $saleInvoice->main_invoice_no = $main_invoice_no;
        $saleInvoice->last_voucher_count = $last_voucher_count;
        $saleInvoice->branch_invoice_no = $branch_invoice_no;
        $saleInvoice->last_branch_count = $last_branch_count;
    }
}
