<?php

namespace App\Exports;

use App\Models\PosOrder;
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;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use Illuminate\Http\Request;

class PosOrdersExport implements FromCollection, WithHeadings, WithMapping, WithStyles, WithColumnWidths
{
    protected $request;

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

    public function collection()
    {
        $query = PosOrder::with(['table', 'waiter', 'items.menuItem']);

        // Apply same filters as index
        if ($this->request->has('start_date') && $this->request->start_date) {
            $query->whereDate('created_at', '>=', $this->request->start_date);
        }
        if ($this->request->has('end_date') && $this->request->end_date) {
            $query->whereDate('created_at', '<=', $this->request->end_date);
        }
        if ($this->request->has('table_id') && $this->request->table_id) {
            $query->where('table_id', $this->request->table_id);
        }
        if ($this->request->has('waiter_id') && $this->request->waiter_id) {
            $query->where('waiter_id', $this->request->waiter_id);
        }
        if ($this->request->has('status') && $this->request->status !== '') {
            $query->where('status', $this->request->status);
        }
        if ($this->request->has('payment_status') && $this->request->payment_status !== '') {
            if ($this->request->payment_status === 'paid') {
                $query->where('status', 'paid');
            } else {
                $query->where('status', '!=', 'paid');
            }
        }
        if ($this->request->has('order_type') && $this->request->order_type) {
            $query->where('order_type', $this->request->order_type);
        }
        if ($this->request->has('search') && $this->request->search) {
            $search = $this->request->search;
            $query->where(function($q) use ($search) {
                $q->where('order_number', 'like', '%' . $search . '%')
                  ->orWhere('customer_name', 'like', '%' . $search . '%')
                  ->orWhere('customer_phone', 'like', '%' . $search . '%');
            });
        }

        return $query->orderBy('created_at', 'desc')->get();
    }

    public function headings(): array
    {
        return [
            'Order Number',
            'Order Type',
            'Table',
            'Customer Name',
            'Customer Phone',
            'Waiter',
            'Guests',
            'Subtotal',
            'Service Charge %',
            'Service Charge',
            'Tax %',
            'Tax',
            'Discount %',
            'Discount',
            'Grand Total',
            'Payment Mode',
            'Payment Amount',
            'Status',
            'Payment Status',
            'Created At',
            'Items Count',
        ];
    }

    public function map($order): array
    {
        return [
            $order->order_number,
            ucfirst(str_replace('_', ' ', $order->order_type)),
            $order->table ? $order->table->name : '-',
            $order->customer_name ?? '-',
            $order->customer_phone ?? '-',
            $order->waiter ? $order->waiter->name : '-',
            $order->guests,
            number_format($order->subtotal, 2),
            number_format($order->service_charge_percent, 2),
            number_format($order->service_charge, 2),
            number_format($order->tax_percent, 2),
            number_format($order->tax, 2),
            number_format($order->discount_percent, 2),
            number_format($order->discount, 2),
            number_format($order->grand_total, 2),
            ucfirst($order->payment_mode ?? '-'),
            number_format($order->payment_amount ?? 0, 2),
            ucfirst($order->status),
            $order->status === 'paid' ? 'Paid' : 'Unpaid',
            $order->created_at->format('Y-m-d H:i:s'),
            $order->items->count(),
        ];
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => [
                'font' => ['bold' => true, 'size' => 12],
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => ['rgb' => '4472C4']
                ],
                'font' => ['color' => ['rgb' => 'FFFFFF']],
                'alignment' => ['horizontal' => Alignment::HORIZONTAL_CENTER],
            ],
        ];
    }

    public function columnWidths(): array
    {
        return [
            'A' => 15,
            'B' => 12,
            'C' => 12,
            'D' => 20,
            'E' => 15,
            'F' => 15,
            'G' => 10,
            'H' => 12,
            'I' => 15,
            'J' => 15,
            'K' => 10,
            'L' => 12,
            'M' => 12,
            'N' => 12,
            'O' => 12,
            'P' => 12,
            'Q' => 15,
            'R' => 12,
            'S' => 15,
            'T' => 20,
            'U' => 12,
        ];
    }
}

