<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use App\Models\Payment;
use Carbon\Carbon;

class FinancialReportExport implements FromCollection, WithHeadings, WithMapping, WithTitle, ShouldAutoSize, WithStyles
{
    protected $startDate;
    protected $endDate;
    protected $propertyId;

    public function __construct($startDate, $endDate, $propertyId = null)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
        $this->propertyId = $propertyId;
    }

    public function collection()
    {
        $query = Payment::with(['customer.unit.property'])
            ->whereBetween('PaymentDate', [$this->startDate, $this->endDate])
            ->where('TotalPayment', '>', 0);
            
        if ($this->propertyId) {
            $query->whereHas('customer.unit', function($q) {
                $q->where('PropID', $this->propertyId);
            });
        }
        
        return $query->get();
    }

    public function headings(): array
    {
        return [
            'Payment Date',
            'Receipt Number',
            'Customer Name',
            'Property',
            'Unit',
            'Payment Method',
            'Description',
            'Amount',
            'Status'
        ];
    }

    public function map($payment): array
    {
        return [
            Carbon::parse($payment->PaymentDate)->format('M d, Y'),
            $payment->ReceiptNumber ?? 'N/A',
            $payment->customer->CustomerName ?? 'N/A',
            $payment->customer->unit->property->PropName ?? 'N/A',
            $payment->customer->unit->UnitIdentity ?? 'N/A',
            $payment->PaymentMethod,
            $payment->Description,
            $payment->TotalPayment,
            'Processed' // You might want to add a status field to your payments table
        ];
    }

    public function title(): string
    {
        return 'Financial Report ' . Carbon::parse($this->startDate)->format('Y-m-d') . ' to ' . Carbon::parse($this->endDate)->format('Y-m-d');
    }

    public function styles(Worksheet $sheet)
    {
        return [
            // Style the first row as bold text
            1 => [
                'font' => ['bold' => true],
                'fill' => [
                    'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                    'startColor' => ['rgb' => 'D9EAD3']
                ]
            ],
            // Style the amount column
            'H' => [
                'numberFormat' => [
                    'formatCode' => 'K#,##0.00'
                ]
            ]
        ];
    }
}
