<?php

namespace App\Exports\SaleReturn;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class ItemWiseStatement implements FromCollection,WithStyles
{
    protected $data;
    protected $company;

    public function __construct($data,$company)
    {
        $this->data = collect($data);
        $this->company = $company;
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $data = $this->data;
        $company  = $this->company;
        $records = [];
        $companyState = $company->getCompanyAddress->getComapnyState->name??null;
        $IgstAmount = $CgstAmount = $SgstAmount = $CessAmount = 0;
        $totalIgstAmount = $totalCgstAmount = $totalSgstAmount = $totalCessAmount = 0;
        $totalValue = 0;
        $totalValueAmount = 0;
        $discountAmount = 0;
        $totalAmount = 0;
        $productPriceAfterDiscount = 0;
        $totalMrp = 0;

        $records[] = [
            'Invoice No',
            'Date',
            'Bill To',
            'Consultant',
            'Invoice Type',
            'Item Name',
            'HSN',
            'QTY (Pack)',
            'QTY (Loose)',
            'Batch',
            'Tax (%)',
           'IGST (%)',
           'IGST (Amt)',
           'CGST (%)',
           'CGST (Amt)',
           'SGST (%)',
           'SGST (Amt)',
           'CESS (%)',
           'CESS (Amt)',
           'Basic Amt.',
            'Total Tax',
            'Total Amt.',
        ];

        foreach ($data as $key => $invoice) {


			$account = '';
			$tax     = '0';
            $discountAmount   = $invoice['price'] * ($invoice['discount_percentage'] / 100);
            $totalMrp +=$invoice['price'];
            $productPriceAfterDiscount = $invoice['price'] - $discountAmount;
            $totalValueAmount = $productPriceAfterDiscount*$invoice['main_qty'];
            $patientState = getAccountState($invoice['patient_id']);


            if(!empty($invoice['bill_to_name'])) {
            	$account = $invoice['bill_to_name'] .' '.$invoice['bill_to_code'];
            } else {
            	$account = $invoice['account_name'] .' '.$invoice['account_code'];
            }

            if(!empty($invoice['doctor_name'])) {
                $doctor = 'Dr '.$invoice['doctor_name'];
            } else {
                $doctor = 'Self';
            }

         	$tax_per = $invoice->tax != 'Tax Free' ? preg_replace('/[^0-9]/', '', $invoice->tax ?? 0,) : 0;
			$quantity = !empty($invoice['main_qty']) ? $invoice['main_qty'] : $invoice['alt_qty'];

            if (
                isset(
                $invoice['getProduct']
                ->getTaxMaster
                ->getTaxMasterSub,
                )
                ) {
                    foreach ($invoice['getProduct']->getTaxMaster->getTaxMasterSub as $tax) {
                        if ($tax->name == 'IGST') {
                          
                            $IGST = $tax->percentage ??0;
                            $IgstAmount = taxAmountCalculate($tax->percentage,$totalValueAmount);
            
                           
                        } elseif (
                            $tax->name == 'CGST'
                        ) {
                         
                            $CGST = $tax->percentage ??0;
                            $CgstAmount = taxAmountCalculate($tax->percentage,$totalValueAmount);
                           
                          
                           
                        } elseif (
                            $tax->name == 'SGST'
                        ) {
                         
                            $SGST = $tax->percentage ?? 0;
                            $SgstAmount = taxAmountCalculate($tax->percentage,$totalValueAmount);
                            
                          
                  
                        }elseif($tax->name == 'CESS')
                        {
                            $CESS = $tax->percentage ??0;
                            $CessAmount = taxAmountCalculate($tax->percentage,$totalValueAmount);
                            
                        }
                    }
                }


         	if ($invoice['tax_calculation'] == 'EXCLUSIVE') {
                $basic_amount = $quantity * $invoice->basic_amount;
	            $tax = $basic_amount - $invoice['total_amount'];
         	} else {
                $basic_amount = $invoice['total_amount'];
                $tax = $basic_amount - $invoice['basic_amount'];
         	}

             if($companyState != $patientState){
                $IGST = $IGST;
                $IgstAmount = convertDecimelPoint($IgstAmount);
             }else{
                $IGST = '0';
                $IgstAmount = '0';
             }     
             
            if($companyState == $patientState){
                $CGST = $CGST;
                $CgstAmount = convertDecimelPoint($CgstAmount);
                $SGST = $SGST;
                $SgstAmount = convertDecimelPoint($SgstAmount);
            }else{
                $CGST = '0';
                $CgstAmount = '0';
                $SGST = '0';
                $SgstAmount = '0';
            } 
            

            $invoice_date = \Illuminate\Support\Carbon::parse($invoice['invoice_date']);
            $records[] =  [
                ($invoice['main_invoice_no'] ?? ''),
                $this->formatedDate($invoice_date),
                $account,
                $doctor,
                ($invoice['voucher_type_name'] ?? ''),
                ($invoice['product_name'] ?? ''),
                ($invoice['hsncode'] ?? ''),
                ($invoice['main_qty'] ?? ''),
                ($invoice['alt_qty'] ?? ''),
                ($invoice['invoice_batch_no'] ?? ''),
                $tax_per ?? '',
                ($IGST??'0'),
                ($IgstAmount??'0'),
                ($CGST??'0'),
                ($CgstAmount??'0'),
                ($SGST??'0'),
                ($SgstAmount??'0'),
                ($CESS??'0'),
                ($CessAmount??'0'),
				$invoice['basic_amount'],
				$tax,
				$invoice['total_amount'],
            ];
        }

        return collect($records);
    }

    private function formatedDate($dateTime)
    {
        return $dateTime->format('d-m-Y') . " " . $dateTime->format('h:i A');
    }

    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle(1)->getFont()->setBold(true);
        return [
            // Styling the first row (headings)
            'H' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'I' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'K' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'L' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'M' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'N' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'O' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'P' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'Q' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'R' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'S' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'T' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'U' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
            'V' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], 
        ];
    }
}
