<?php

namespace App\Exports\Stocks;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class SingleProductStockExport implements FromCollection,WithHeadings
{
    protected $data;

    public function __construct($data)
    {
        $this->data = collect($data);
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $data = $this->data;
        $records = [];
        $stockIn = 0;
        $stockOut = 0;
        $currentStock = 0;
        $invoiceNumber = '';
        $stockType = '';
        foreach ($data as $key => $invoice) {
            $date = $invoice['entry_date'];
            $stockIn+=($invoice['pack_qty_in']);
            $stockOut+=$invoice['pack_qty_out'];

            $currentStock = $stockIn - $stockOut + $invoice['free_qty'];

            if($invoice['voucher_type']=='SALES' || $invoice['voucher_type']=='IPD_INVOICE'){
                $invoiceNumber =$invoice['voucher_sale_type']['voucher_type_invoice_no']??'';
            }elseif($invoice['voucher_type']=='PURCHASE'){
                $invoiceNumber =$invoice['voucher_purchase_type']['voucher_type_invoice_no']??'';
            }elseif($invoice['voucher_type']=='SALE_RETURN'){
                $invoiceNumber =$invoice['voucher_return_type']['voucher_type_invoice_no']??'';
            }elseif($invoice['voucher_type']=='STOCK_IN'){
                $invoiceNumber =$invoice['voucherStockIn']['voucher_type_invoice_no']??'';
            }elseif($invoice['voucher_type']=='STOCK_OUT'){
                $invoiceNumber =$invoice['voucherStockOut']['voucher_type_invoice_no']??'';
            }

            if(isset($invoice['get_movement_type'])){
                $stockType = $invoice['get_movement_type']['name']??'';
            }else{
                $stockType = $invoice['stock_type']??'';
            }



            $records[] =  [
                formatedDateTimeForBill($date),
                ($invoiceNumber??''),
                ($invoice['get_product']['name'] ?? ''),
                ($stockType ?? ''),
                ($invoice['get_created_by']['prepared_by'] ?? ''),
                (convertDecimelPoint($invoice['pack_qty_in'] + $invoice['free_qty']) ?? '0'),
                (convertDecimelPoint($invoice['pack_qty_out']) ?? '0'),
                (convertDecimelPoint($currentStock)??'0'),
                (convertDecimelPoint($invoice['taxable_unit_price'])??'0'),
            ];

        }

        return collect($records);
    }

    public function headings(): array
    {
        $headings = [
            'Date Time',
            'Voucher Number',
            'Product Name',
            'Stock Type',
            'Added By',
            'STOCK IN',
            'STOCK Out',
            'CURRENT STOCK',
            'STOCK Value',
        ];

        return $headings;
    }
}
