<?php

namespace App\Exports\Opd;

use App\Models\OpdBookings;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use Maatwebsite\Excel\Events\AfterSheet;

class OpdStatementExport implements FromCollection, WithMapping, WithHeadings, WithStyles,WithEvents
{
    use Exportable;

    protected $filteredData;

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

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return OpdBookings::select('*')->hydrate($this->filteredData);
    }


    public function map($booking): array
    {
        $Payments = TransactionCalculationReceiveAmount($booking['id'],'OPD_BOOKING');
        $bookingDateTime = \Carbon\Carbon::parse($booking['booking_date_time']);
        $appointmentDateTime = \Carbon\Carbon::parse($booking['appointment_date_time']);
        //dd($booking['getPatient']);
        // $doctor = $booking['getDoctorAccount'];

        return [
            $this->formatBooking($bookingDateTime, $booking['booking_no']),
            $booking['patient_title'].' '.$booking['patient']." \n".$booking['patient_genders']. ', ' .($booking['patient_date_of_birth']?$this->calculateAge($booking['patient_date_of_birth']).' Year`s ':'').' Ph:' .$booking['patient_phone_no'],
            $booking['doctor_title'] . ' ' . $booking['doctor'] . " \nShift- " . $booking['appointment_shift'],
            $this->formatAppointment($appointmentDateTime, $booking['appointment_serial_no']),
            convertDecimelPoint($Payments['totalBilling']),
            convertDecimelPoint($Payments['receivedAmount']),
            convertDecimelPoint($Payments['dueAmount']),
            'Walk In',
            $booking['appointment_status'] == 'Done' ? 'Confirm' : 'Pending',
        ];
        
    }

    public function headings(): array
    {
        return [
            'BOOKING',
            'PATIENT INFO.',
            'DOCTOR INFO.',
            'APPOINTMENT',
            'TOTAL',
            'RECEIVED',
            'DUE',
            'SOURCE',
            'STATUS'
        ];
    }
    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle(1)->getFont()->setBold(true);
        return [
            // Styling the first row (headings)
            'E' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], // "TOTAL"
            'F' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], // "RECEIVED"
            'G' => ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT]], // "DUE"
        ];
    }

    private function formatBooking($dateTime, $bookingNo)
    {
        return $bookingNo . " \r\n" . $dateTime->format('d-m-Y') . " \r\n" . $dateTime->format('h:i A');
    }


    private function formatAppointment($dateTime, $serialNo)
    {
        return $dateTime->format('d-m-Y') . "\n" . $dateTime->format('h:i A') . " \n#SL.NO. " . $serialNo;
    }

    private function calculateAge($dob)
    {
        return \Carbon\Carbon::parse($dob)->age;
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function(AfterSheet $event) {
                $sheet = $event->sheet->getDelegate();
                $highestRow = $sheet->getHighestRow();

                for ($row = 2; $row <= $highestRow; $row++) {
                    $statusCell = $sheet->getCell('I' . $row)->getValue();
                    if ($statusCell === 'Confirm') {
                        $sheet->getStyle('I' . $row)->applyFromArray([
                            'fill' => [
                                'fillType' => Fill::FILL_SOLID,
                                'startColor' => [
                                    'rgb' => '00FF00',
                                ],
                            ],
                        ]);
                    }
                    else{
                        $sheet->getStyle('I' . $row)->applyFromArray([
                            'fill' => [
                                'fillType' => Fill::FILL_SOLID,
                                'startColor' => [
                                    'rgb' => 'FFFF00',
                                ],
                            ],
                        ]);
                    }
                }
            },
        ];
    }
}
