<?php

namespace App\Exports;

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

class AnalyticsExport implements WithMultipleSheets
{
    protected $analytics;
    protected $period;
    protected $sourceName;

    public function __construct($analytics, $period, $sourceName = 'All Sources')
    {
        $this->analytics = $analytics;
        $this->period = $period;
        $this->sourceName = $sourceName;
    }

    public function sheets(): array
    {
        return [
            new DeliveryByStateSheet($this->analytics['delivery_by_state'], $this->period, $this->sourceName),
            new TopProductsSheet($this->analytics['top_products'], $this->period, $this->sourceName),
            new UnitsOutSheet($this->analytics['units_out'], $this->period, $this->sourceName),
            new RepeatCustomersSheet($this->analytics['repeat_customers'], $this->period, $this->sourceName),
            new CustomerDatabaseSheet($this->analytics['customer_database'], $this->period, $this->sourceName),
        ];
    }
}

class DeliveryByStateSheet implements FromArray, WithHeadings, WithTitle, WithStyles
{
    protected $data;
    protected $period;
    protected $sourceName;

    public function __construct($data, $period, $sourceName)
    {
        $this->data = $data;
        $this->period = $period;
        $this->sourceName = $sourceName;
    }

    public function array(): array
    {
        $rows = [
            ['Report Period:', $this->period],
            ['Source:', $this->sourceName],
            ['Generated:', now()->format('Y-m-d H:i:s')],
            [],
        ];

        foreach ($this->data['data'] as $state) {
            $rows[] = [
                $state['state'],
                $state['count'],
                $state['percentage'] . '%'
            ];
        }

        $rows[] = [];
        $rows[] = ['Total Orders:', $this->data['total']];

        return $rows;
    }

    public function headings(): array
    {
        return [];
    }

    public function title(): string
    {
        return 'Delivery by State';
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true]],
            2 => ['font' => ['bold' => true]],
            3 => ['font' => ['bold' => true]],
            5 => ['font' => ['bold' => true, 'size' => 12]],
        ];
    }
}

class TopProductsSheet implements FromArray, WithHeadings, WithTitle, WithStyles
{
    protected $data;
    protected $period;
    protected $sourceName;

    public function __construct($data, $period, $sourceName)
    {
        $this->data = $data;
        $this->period = $period;
        $this->sourceName = $sourceName;
    }

    public function array(): array
    {
        $rows = [
            ['Report Period:', $this->period],
            ['Source:', $this->sourceName],
            ['Generated:', now()->format('Y-m-d H:i:s')],
            [],
            ['Rank', 'SKU', 'Product Name', 'Units Sold', 'Number of Orders'],
        ];

        foreach ($this->data as $index => $product) {
            $rows[] = [
                $index + 1,
                $product['sku'],
                $product['name'],
                $product['units'],
                $product['orders']
            ];
        }

        return $rows;
    }

    public function headings(): array
    {
        return [];
    }

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

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true]],
            2 => ['font' => ['bold' => true]],
            3 => ['font' => ['bold' => true]],
            5 => ['font' => ['bold' => true, 'size' => 12]],
        ];
    }
}

class UnitsOutSheet implements FromArray, WithHeadings, WithTitle, WithStyles
{
    protected $data;
    protected $period;
    protected $sourceName;

    public function __construct($data, $period, $sourceName)
    {
        $this->data = $data;
        $this->period = $period;
        $this->sourceName = $sourceName;
    }

    public function array(): array
    {
        $rows = [
            ['Report Period:', $this->period],
            ['Source:', $this->sourceName],
            ['Generated:', now()->format('Y-m-d H:i:s')],
            [],
            ['SKU', 'Units Out'],
        ];

        foreach ($this->data['data'] as $sku) {
            $rows[] = [
                $sku['sku'],
                $sku['units']
            ];
        }

        $rows[] = [];
        $rows[] = ['Total Units:', $this->data['total_units']];

        return $rows;
    }

    public function headings(): array
    {
        return [];
    }

    public function title(): string
    {
        return 'Units Out by SKU';
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true]],
            2 => ['font' => ['bold' => true]],
            3 => ['font' => ['bold' => true]],
            5 => ['font' => ['bold' => true, 'size' => 12]],
        ];
    }
}

class RepeatCustomersSheet implements FromArray, WithHeadings, WithTitle, WithStyles
{
    protected $data;
    protected $period;
    protected $sourceName;

    public function __construct($data, $period, $sourceName)
    {
        $this->data = $data;
        $this->period = $period;
        $this->sourceName = $sourceName;
    }

    public function array(): array
    {
        $rows = [
            ['Report Period:', $this->period],
            ['Source:', $this->sourceName],
            ['Generated:', now()->format('Y-m-d H:i:s')],
            [],
            ['Total Customers:', $this->data['total_customers']],
            ['Repeat Customers:', $this->data['total_repeat_customers']],
            ['Repeat Rate:', $this->data['repeat_rate'] . '%'],
            [],
            ['Customer Name', 'Email', 'Phone', 'Order Count', 'Total Spent'],
        ];

        foreach ($this->data['data'] as $customer) {
            $rows[] = [
                $customer['name'],
                $customer['email'] ?? '',
                $customer['phone'] ?? '',
                $customer['order_count'],
                $customer['total_spent']
            ];
        }

        return $rows;
    }

    public function headings(): array
    {
        return [];
    }

    public function title(): string
    {
        return 'Repeat Customers';
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true]],
            2 => ['font' => ['bold' => true]],
            3 => ['font' => ['bold' => true]],
            5 => ['font' => ['bold' => true]],
            6 => ['font' => ['bold' => true]],
            7 => ['font' => ['bold' => true]],
            9 => ['font' => ['bold' => true, 'size' => 12]],
        ];
    }
}

class CustomerDatabaseSheet implements FromArray, WithHeadings, WithTitle, WithStyles
{
    protected $data;
    protected $period;
    protected $sourceName;

    public function __construct($data, $period, $sourceName)
    {
        $this->data = $data;
        $this->period = $period;
        $this->sourceName = $sourceName;
    }

    public function array(): array
    {
        // Calculate total sales
        $totalSales = 0;
        $dataSource = $this->data['order_details'] ?? $this->data['customers'];

        if (isset($this->data['order_details'])) {
            // Sum from order_details (each order)
            foreach ($dataSource as $order) {
                $totalSales += (float)($order['order_total'] ?? 0);
            }
        } else {
            // Sum from customers (total_spent)
            foreach ($dataSource as $customer) {
                $totalSales += (float)($customer['total_spent'] ?? 0);
            }
        }

        $rows = [
            ['Report Period:', $this->period],
            ['Source:', $this->sourceName],
            ['Generated:', now()->format('Y-m-d H:i:s')],
            [],
            ['TOTAL SALE', number_format($totalSales, 2)],
            ['Total Customers:', $this->data['total_customers']],
            ['Customer Name', 'Email', 'Phone', 'Address', 'City', 'State', 'Postcode', 'First Order Date', 'Last Order Date', 'Product', 'SKU', 'Unit', 'Total Orders', 'Total'],
        ];

        if (isset($this->data['order_details'])) {
            // Detailed view: one row per order with products
            foreach ($dataSource as $order) {
                $rows[] = [
                    $order['customer_name'],
                    $order['email'] ?? '',
                    $order['phone'] ?? '',
                    $order['address'] ?? '',
                    $order['city'] ?? '',
                    $order['state'] ?? '',
                    $order['postcode'] ?? '',
                    $order['first_order_date'] ?? '',
                    $order['last_order_date'] ?? '',
                    $order['products'] ?? '', // Product
                    $order['skus'] ?? '', // SKU
                    $order['quantities'] ?? '', // Unit
                    $order['total_orders'] ?? 1,
                    $order['order_total'] ?? 0
                ];
            }
        } else {
            // Summary view: one row per customer
            foreach ($dataSource as $customer) {
                $rows[] = [
                    $customer['name'],
                    $customer['email'] ?? '',
                    $customer['phone'] ?? '',
                    $customer['address'] ?? '',
                    $customer['city'] ?? '',
                    $customer['state'] ?? '',
                    $customer['postcode'] ?? '',
                    $customer['first_order_date'] ?? '',
                    $customer['last_order_date'] ?? '',
                    '', // Product (not available in summary)
                    '', // SKU (not available in summary)
                    '', // Unit (not available in summary)
                    $customer['order_count'],
                    $customer['total_spent']
                ];
            }
        }

        return $rows;
    }

    public function headings(): array
    {
        return [];
    }

    public function title(): string
    {
        return 'Customer Database';
    }

    public function styles(Worksheet $sheet)
    {
        // Style SKU and Unit column headers (K6 and L6) in red
        $sheet->getStyle('K6')->getFont()->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color('FF0000'));
        $sheet->getStyle('L6')->getFont()->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color('FF0000'));

        return [
            1 => ['font' => ['bold' => true]],
            2 => ['font' => ['bold' => true]],
            3 => ['font' => ['bold' => true]],
            4 => ['font' => ['bold' => true, 'color' => ['rgb' => 'FF0000']]], // TOTAL SALE row
            5 => ['font' => ['bold' => true]],
            6 => ['font' => ['bold' => true, 'size' => 12]], // Header row
        ];
    }
}
