<?php

namespace App\Exports\Stocks;

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

class InventoryAndStockExport implements FromCollection,WithHeadings,WithStyles
{
    protected $data;

    public function __construct($data)
    {
        $this->data = collect($data);
    }
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $data = $this->data;
        $records = [];
        $i = 1;
        $stockData = [];

        foreach ($data as $key => $invoice) {
            $exp_date = $invoice['exp_date'];
            $stockData = getProductStock($invoice['product_id']);

            $records[] =  [
                $i,
                ($invoice['product_name'] ?? ''),
                ($invoice['primary_unit'] ?? ''),
                ($invoice['batch'] ?? ''),
                formatedDateTimeForBill($exp_date),
                number_format($stockData['stock_in'], 2, '.', ''),
                number_format($stockData['stock_out'], 2, '.', ''),
                number_format(($stockData['current_stock']), 2, '.', ''),
                number_format($invoice['taxable_unit_price'], 2, '.', '')
            ];

            $i++;
        }

        return collect($records);
    }

    public function headings(): array
    {
        $headings = [
            'Sl No',
            'Product Name',
            'UOM',
            'Batch',
            'Expiry Date',
            'STOCK IN',
            'STOCK Out',
            'CURRENT STOCK',
            'STOCK Value',
        ];

        return $headings;
    }

    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle(1)->getFont()->setBold(true);

        // Get the last row number
        $lastRow = $sheet->getHighestRow();

        // Apply bold font style to the last row
        $sheet->getStyle($lastRow)->getFont()->setBold(true);
        
        return [
            // Styling the first row (headings)
            'F' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], // "STOCK IN"
            'G' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], // "STOCK Out"
            'H' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], // "CURRENT STOCK"
            'I' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], // "STOCK Value"
        ];
    }
}
