<?php

namespace App\Exports;

use App\Models\Inventory;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class ExportInventory implements FromCollection, WithHeadings, WithStyles, ShouldAutoSize{
    function __construct($slug) {
        $this->slug = $slug;
    }

    public function collection()
    {
        $user = new Inventory();
        $data = $user->export($this->slug);
    
        if ($data == null) {
            throw new \ErrorException('No Data Found!');
        }
    
        // Prevent Excel formula evaluation
        $data = $data->map(function ($row) {
            return collect($row)->map(function ($value) {
                if (is_string($value) && str_starts_with($value, '=')) {
                    return "'" . $value; // escape formula-like strings
                }
                return $value;
            });
        });
    
        return $data;
    }

    public function headings() :array{
        return ['Branch','Car Model','Car Varient','Exteriorcolor' ,'Interiorcolor','KIN Invoice Number','KIN Invoice Date', 'Manufacturing Year','Key number' ,'Engine number' , 'Vin number', 'EX Showroom price', 'Status','Purchase Price','KIN Margin','Fuel Type','Inventory Type','Offer Applicable','Remark','OEM Code'];
    }

    public function styles(Worksheet $sheet){
        return [1 => ['font' => ['bold' => true]]];
    }
}