<?php

namespace App\Exports;

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

class ProductPerformanceExport implements FromCollection, WithHeadings, WithMapping, WithStyles, WithColumnWidths
{
    protected $products;
    protected $rankCounter = 1;

    public function __construct($products)
    {
        $this->products = $products;
    }

    public function collection()
    {
        return collect($this->products);
    }

    public function headings(): array
    {
        return [
            'Rank',
            'Product Name',
            'SKU',
            'Category',
            'Views (in Period)',
            'Units Sold',
            'Revenue Generated (LKR)',
            'Status'
        ];
    }

    public function map($item): array
    {
        return [
            $this->rankCounter++,
            $item->product_name ?? 'N/A',
            $item->sku ?? 'N/A',
            $item->category->category_name ?? 'Uncategorized',
            $item->view_count ?? 0,
            $item->total_sold ?? 0,
            number_format($item->revenue ?? 0, 2, '.', ''),
            $item->status ? 'Active' : 'Inactive'
        ];
    }

    public function columnWidths(): array
    {
        return [
            'A' => 10,  // Rank
            'B' => 35,  // Product Name
            'C' => 15,  // SKU
            'D' => 20,  // Category
            'E' => 18,  // Views
            'F' => 15,  // Units Sold
            'G' => 25,  // Revenue
            'H' => 12   // Status
        ];
    }

    public function styles(Worksheet $sheet)
    {
        return [
            // Bold the header row
            1 => ['font' => ['bold' => true]],

            // Format views and sold columns as numbers
            'E' => ['numberFormat' => ['formatCode' => '#,##0']],
            'F' => ['numberFormat' => ['formatCode' => '#,##0']],

            // Format revenue as LKR currency
            'G' => ['numberFormat' => ['formatCode' => '"LKR "#,##0.00']],

            // Add thin borders to the whole dataset
            'A1:H'.$sheet->getHighestRow() => [
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN
                    ]
                ]
            ]
        ];
    }
}
