<?php

namespace App\Exports;

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;
use Illuminate\Http\Request;

class LabBillingStatementExport implements FromCollection
{

    protected $data;

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

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $request           = new Request(request()->all());
        $collection_status = $request->collection_status ?? '';
        $data              = $this->data;
        $records           = [];

        $records[] = [
            'INVOICE NO',
            'Created By',
            'Patient',
            'Doctor',
            'Referral',
            'Coll. Agent',
            'Bill To',
            'Total',
            'Received',
            'Due',
            'Status'
        ];

        $total_billing_amount = $total_received = $total_due_amount = 0;

        foreach ($data as $key => $sale_invoice) {
            $invoice_date = \Illuminate\Support\Carbon::parse($sale_invoice['invoice_date']);

            $total_amount    = $sale_invoice['get_sale_invoice_details_sum_total_amount'];
            $received_amount = getTotalReceiptAmount($sale_invoice['ac_receipt_details_ids']);
            $due             = $total_amount - $received_amount;
            $status          = $due > 0 ? 'Pending' : 'Collected';

            if (!empty($collection_status)) {
                if ($collection_status == 'due' && $due < 1) {
                    continue;
                }
                if ($collection_status == 'collected' && $due > 0) {
                    continue;
                }
            }

            $bill_no         = $this->formatBilling($invoice_date, $sale_invoice['main_invoice_no']);
            $operator        = $sale_invoice['operator'];
            $patient         = $this->formatPatientInfo($sale_invoice);
            $doctor          = $sale_invoice['doctor_title'] . ' ' . $sale_invoice['doctor'];
            $referral        = $sale_invoice['refferal_title'] . ' ' . $sale_invoice['referral'];
            $coll_agent      = $sale_invoice['coll_agent_title'] . ' ' . $sale_invoice['coll_agent'];
            $bill_to_account = $sale_invoice['bill_to_title'] . ' ' . $sale_invoice['bill_to_account'];
            $special_case    = $sale_invoice['special_case'];
            $total_amount    = convertDecimelPoint($total_amount);
            $received_amount = convertDecimelPoint($received_amount);
            $due             = convertDecimelPoint($due);

            $records[] =  [
                $bill_no,
                $operator,
                $patient,
                $doctor,
                $referral,
                $coll_agent,
                $bill_to_account,
                $total_amount,
                $received_amount,
                $due,
                $status
            ];

            $total_billing_amount += $total_amount;
            $total_received += $received_amount;
            $total_due_amount += $due;
        }

        $records[] =  [
            '',
            '',
            '',
            '',
            '',
            '',
            '',
            $total_billing_amount,
            $total_received,
            $total_due_amount,
            ''
        ];

        return collect($records);
    }

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

    private function formatPatientInfo($patient)
    {
         // dd($patient['name']);
		$title         = isset($patient['account_title'])?$patient['account_title']:'';
		$PatientName   = $patient['patent_name']??'';
		$PatientGender = isset($patient['gender'])?$patient['gender']:'';
		$PatientPhone  = isset($patient['phone_no'])?$patient['phone_no']:'';
		$PatientDOB    = isset($patient['date_of_birth'])?$this->calculateAge($patient['date_of_birth']):'';

        return $title . ' ' . $PatientName . " \n" .$PatientGender . ', ' .$PatientDOB. " Years \n" .
               'Ph:' . $PatientPhone;
    }

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