<?php

namespace App\Exports;

use Carbon\Carbon;
use App\Models\SaleInvoiceDetail;
use App\Models\IncentiveSlab;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;

class ReferralVoucherOverAllStatement implements FromCollection, WithHeadings
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function dataProcessing()
    {
        $request  = new Request(request()->all());
        $filter['start_date'] = $start_date = date('Y-m-1', strtotime($request->month_year));
        $filter['end_date']   = $end_date   = date('Y-m-t', strtotime($request->month_year));
        $filter['doctor']     = $doctor     = $request->doctor ?? '';

        $collection = SaleInvoiceDetail::getReferralVoucherStatement([], $filter);

        return $collection;
    }
    public function incentiveSlab()
    {
        return IncentiveSlab::select(
            'incentive_slabs.id',
            'incentive_slabs.calculation_type',
            'incentive_slabs.percentage',
            'incentive_slabs.price'
        )
        ->leftjoin('account_types','account_types.id','incentive_slabs.account_type_id')
        ->where('account_types.type_code', 'DOCTOR')
        ->orderBy('incentive_slabs.is_default', 'DESC')
        ->first();
    }

    public function collection()
    {
        $request          = new Request(request()->all());
        $data             = $this->dataProcessing();
        $incentive_slab   = $this->incentiveSlab();
        $rows             = [];
        $total_commission = 0;
        $statement_by = $request->statement_by ?? '';

        foreach ($data as $key => $record) {
            if ($statement_by == 'patient') {
                $rows[$key]['invoice']      = $record['sale_invoice_details']->voucher_type_invoice_no;
                $rows[$key]['invoice_date'] = formatedDate($record['sale_invoice_details']->invoice_date);
                $rows[$key]['patient']      = $record['sale_invoice_details']->patient_title . ' ' . $record['sale_invoice_details']->patient_name . ' (' . $record['sale_invoice_details']->patient_code .')';
            }

            $rows[$key]['item'] = $record['sale_invoice_details']->product;
            $rows[$key]['category']   = $record['sale_invoice_details']->brand;

            $amount     = $record['sale_invoice_details']->basic_amount ?? 0 ;
            $discount   = !empty($record['sale_invoice_details']->discount_amount) ? $record['sale_invoice_details']->discount_amount :
                (!empty($record['sale_invoice_details']->sale_discount_amount) ? $record['sale_invoice_details']->sale_discount_amount : '0');

            $amount     = $amount - $discount;
            $type = '';
            $price      = 0;

            if (isset($record['incentive_slab_details']) && !empty($record['incentive_slab_details']->calculation_type)) {
                $type       = isset($record['incentive_slab_details']) &&
                    isset($record['incentive_slab_details']->calculation_type) ? $record['incentive_slab_details']->calculation_type : 0 ;

                $percentage = isset($record['incentive_slab_details']) &&
                    isset($record['incentive_slab_details']->percentage) ? $record['incentive_slab_details']->percentage : 0 ;

                $price      = isset($record['incentive_slab_details']) &&
                    isset($record['incentive_slab_details']->price) ? $record['incentive_slab_details']->price : 0 ;
            } else if (!empty($incentive_slab) && !empty($incentive_slab->calculation_type)) {
                $type       = $incentive_slab->calculation_type ?? '' ;
                $percentage = $incentive_slab->percentage ?? 0 ;
                $price      = $incentive_slab->price ?? 0 ;
            }

            $commission = 0 ;
            $referral_count = $record['sale_invoice_details']->referral_count ?? 1 ;

            if ($type == 'quantity') {
                $commission = $referral_count * $price;
            } else if ($type == 'percentage') {
                $commission = ($percentage / 100) * $amount;
            }

            $rows[$key]['type']           = ucfirst($type);
            $rows[$key]['referral_count'] = $record['sale_invoice_details']->referral_count;
            $rows[$key]['percentage']     = !empty($percentage) ? $percentage.'%' : $price;
            $rows[$key]['basic_amount']   = $amount;
            $rows[$key]['total_amount']   = $commission;
            $total_commission += $commission;
        }
            $last_key = $key+1;

            if ($statement_by == 'patient') {
                $rows[$last_key]['invoice']      = 'Total';
                $rows[$last_key]['invoice_date'] = '';
                $rows[$last_key]['patient']      = '';
                $rows[$last_key]['item']         = '';
            } else {
                $rows[$last_key]['item'] = 'Total';
            }

            $rows[$last_key]['category']       = '';
            $rows[$last_key]['type']           = '';
            $rows[$last_key]['referral_count'] = '';
            $rows[$last_key]['percentage']     = '';
            $rows[$last_key]['basic_amount']   = '';
            $rows[$last_key]['total_amount']   = $total_commission;

        return collect($rows);
    }

    public function headings(): array
    {
        $request = new Request(request()->all());
        $statement_by = $request->statement_by ?? '';

        if ($statement_by == 'patient') {
            return [
                'Invoice No.',
                'Invoice Date',
                'Patient Name',
                'Item/Service',
                'Category',
                'Type',
                'Quantity',
                'Percentage',
                'Basic Amount',
                'Total Amount',
            ];
        } else {
            return [
                'Item/Service',
                'Category',
                'Type',
                'Quantity',
                'Percentage',
                'Basic Amount',
                'Total Amount',
            ];
        }
    }
}
