<?php

namespace App\Exports;

use App\Models\Exchange;
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 ExportUsedCarReport implements FromCollection, WithHeadings, WithStyles, ShouldAutoSize{
    function __construct($slug) {
        $this->slug = $slug;
    }

    public function collection()
    {
        $user = new Exchange();
        $data = $user->getUsedCarReport($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 ['Seller Name','Model','Varient','Manufacturing Year','Registration Number','Chassis Number','Engine Number','Color','Date of Registration','Purchase Date','Purchase Amount','HPA','Remark'];
    }

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