<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class SalesPerformanceExport implements WithMultipleSheets
{
    protected $salesSummary;

    protected $salesTrends;

    protected $revenueByPaymentMethod;

    protected $topProducts;

    protected $salesByUser;

    protected $salesByType;

    protected $dateFrom;

    protected $dateTo;

    public function __construct($salesSummary, $salesTrends, $revenueByPaymentMethod, $topProducts, $salesByUser, $salesByType, $dateFrom, $dateTo)
    {
        $this->salesSummary = $salesSummary;
        $this->salesTrends = $salesTrends;
        $this->revenueByPaymentMethod = $revenueByPaymentMethod;
        $this->topProducts = $topProducts;
        $this->salesByUser = $salesByUser;
        $this->salesByType = $salesByType;
        $this->dateFrom = $dateFrom;
        $this->dateTo = $dateTo;
    }

    public function sheets(): array
    {
        return [
            new SalesSummarySheet($this->salesSummary, $this->dateFrom, $this->dateTo),
            new TopProductsSheet($this->topProducts),
            new SalesByUserSheet($this->salesByUser),
            new RevenueByPaymentMethodSheet($this->revenueByPaymentMethod),
            new SalesByTypeSheet($this->salesByType),
        ];
    }
}

// Sales Summary Sheet
class SalesSummarySheet implements FromArray, WithHeadings, WithStyles, WithTitle
{
    protected $salesSummary;

    protected $dateFrom;

    protected $dateTo;

    public function __construct($salesSummary, $dateFrom, $dateTo)
    {
        $this->salesSummary = $salesSummary;
        $this->dateFrom = $dateFrom;
        $this->dateTo = $dateTo;
    }

    public function array(): array
    {
        return [
            ['Chiffre d\'affaires total', number_format($this->salesSummary['total_revenue'], 0, ',', ' ').' FC'],
            ['Nombre total de ventes', number_format($this->salesSummary['total_sales'])],
            ['Vente moyenne', number_format($this->salesSummary['average_sale'], 0, ',', ' ').' FC'],
            ['Croissance des revenus', $this->salesSummary['revenue_growth'].'%'],
            ['Croissance des ventes', $this->salesSummary['sales_growth'].'%'],
        ];
    }

    public function headings(): array
    {
        return [
            ['RAPPORT DE PERFORMANCE DES VENTES'],
            ['Période: '.$this->dateFrom->format('d/m/Y').' - '.$this->dateTo->format('d/m/Y')],
            ['Généré le: '.now()->format('d/m/Y H:i')],
            [],
            ['Métrique', 'Valeur'],
        ];
    }

    public function title(): string
    {
        return 'Résumé des Ventes';
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true, 'size' => 14]],
            5 => ['font' => ['bold' => true], 'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '3B82F6']], 'font' => ['color' => ['rgb' => 'FFFFFF']]],
        ];
    }
}

// Top Products Sheet
class TopProductsSheet implements FromArray, WithHeadings, WithStyles, WithTitle
{
    protected $topProducts;

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

    public function array(): array
    {
        return $this->topProducts->map(function ($product) {
            return [
                $product['product']->name,
                $product['product']->category->name ?? 'N/A',
                number_format($product['total_quantity']),
                number_format($product['total_revenue'], 0, ',', ' ').' FC',
            ];
        })->toArray();
    }

    public function headings(): array
    {
        return [
            ['Produit', 'Catégorie', 'Quantité vendue', 'Revenus (FC)'],
        ];
    }

    public function title(): string
    {
        return 'Top 10 Produits';
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true], 'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '3B82F6']], 'font' => ['color' => ['rgb' => 'FFFFFF']]],
        ];
    }
}

// Sales by User Sheet
class SalesByUserSheet implements FromArray, WithHeadings, WithStyles, WithTitle
{
    protected $salesByUser;

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

    public function array(): array
    {
        return $this->salesByUser->map(function ($user) {
            return [
                $user['user']->firstname.' '.$user['user']->lastname,
                ucfirst($user['user']->role),
                number_format($user['sales_count']),
                number_format($user['total_revenue'], 0, ',', ' ').' FC',
            ];
        })->toArray();
    }

    public function headings(): array
    {
        return [
            ['Utilisateur', 'Rôle', 'Nombre de ventes', 'Revenus (FC)'],
        ];
    }

    public function title(): string
    {
        return 'Performance par Utilisateur';
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true], 'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '3B82F6']], 'font' => ['color' => ['rgb' => 'FFFFFF']]],
        ];
    }
}

// Revenue by Payment Method Sheet
class RevenueByPaymentMethodSheet implements FromArray, WithHeadings, WithStyles, WithTitle
{
    protected $revenueByPaymentMethod;

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

    public function array(): array
    {
        return $this->revenueByPaymentMethod->map(function ($method) {
            return [
                $method['method'],
                number_format($method['amount'], 0, ',', ' ').' FC',
                number_format($method['percentage'], 1).'%',
            ];
        })->toArray();
    }

    public function headings(): array
    {
        return [
            ['Méthode de paiement', 'Revenus (FC)', 'Pourcentage'],
        ];
    }

    public function title(): string
    {
        return 'Revenus par Méthode';
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true], 'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '3B82F6']], 'font' => ['color' => ['rgb' => 'FFFFFF']]],
        ];
    }
}

// Sales by Type Sheet
class SalesByTypeSheet implements FromArray, WithHeadings, WithStyles, WithTitle
{
    protected $salesByType;

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

    public function array(): array
    {
        return $this->salesByType->map(function ($type) {
            return [
                $type['type'],
                number_format($type['count']),
                number_format($type['amount'], 0, ',', ' ').' FC',
                number_format($type['percentage'], 1).'%',
            ];
        })->toArray();
    }

    public function headings(): array
    {
        return [
            ['Type de vente', 'Nombre', 'Revenus (FC)', 'Pourcentage'],
        ];
    }

    public function title(): string
    {
        return 'Ventes par Type';
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true], 'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '3B82F6']], 'font' => ['color' => ['rgb' => 'FFFFFF']]],
        ];
    }
}
