<?php

namespace App\Http\Controllers;
use App\Enums\DateFormatEnum;
use App\Enums\RecordStatusEnum;
use App\Exports\DoctorPhysicianExport;
use App\Exports\DoctorSampleSourceExport;
use App\Exports\SummaryReportExport;
use App\Exports\VillageCoverageExport;
use App\Exports\FinancialReportExport;
use App\Helpers\Helpers;
use App\Http\Controllers\Helper\GlobalController;
use App\Http\Requests\SampleCreateRequest;
use App\Http\Requests\UpdateRequests\SampleUpdateRequest;
use App\Http\Resources\SampleResource;
use App\Models\BaseModel;
use App\Models\Invoice;
use App\Models\InvoiceDetail;
use App\Models\Physician;
use App\Models\Sample;
use App\Models\SampleSource;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Maatwebsite\Excel\Facades\Excel;

class ReportController extends Controller
{
    protected $model;
    protected $sampleModel;
    protected $invoiceDetailModel;
    protected $baseLabId;
    protected $labs;
    protected $physicianModel;
    protected $sampleSourceModel;

    protected $base;

    public function __construct(Invoice $invoiceModel, InvoiceDetail $invoiceDetailModel, Sample $sampleModel,
                                Physician $physicianModel, SampleSource $sampleSourceModel
    ){
        $this->model = $invoiceModel;
        $this->sampleModel = $sampleModel;
        $this->invoiceDetailModel = $invoiceDetailModel;
        $this->physicianModel = $physicianModel;
        $this->sampleSourceModel = $sampleSourceModel;
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
        $this->labs = parent::getAccessAbleLabs();
    }

    /**
     * ======================================
     * INVOICE REPORTS STARTED
     */

    public function dailyInvoiceReport($date, $reportType = 'daily'){
        try{
            $reportPeriodCondition = $reportType != 'daily' ? ' DATE_FORMAT(inv.`invoice_date`, "%Y-%m")= "'.date('Y-m',strtotime($date)).'" ' : ' DATE(inv.`invoice_date`) = "'.$date.'"';
            $arrData = array();
            $arrData['report_period'] = $date;
            $invoices = DB::select('
                                            SELECT
                                                inv.id as invoice_id,
                                                ps.`id` AS physician_id,
	                                            ps.`name_en` AS physician_name,
                                                lb.`name_en` AS lab,
                                                p.`name_en` AS patient,
                                                inv.`discount`,
                                                inv.`total`,
                                                inv.`gross_total`,
                                                inv.`balance`,
                                                inv.`invoice_date`,
                                                req_test.req_tests
                                            FROM `invoices` inv
                                            INNER JOIN samples sp
                                            ON sp.id =inv.`sample_id` AND sp.`lab_id` = inv.`lab_id`
                                            INNER JOIN physicians ps
                                            ON ps.`id` = sp.`physician_id` AND ps.`lab_id` = sp.`lab_id`
                                            INNER JOIN `laboratories` lb
                                            ON lb.`id` = sp.`lab_id`
                                            INNER JOIN patients p
                                            ON p.`id` = sp.`patient_id` AND p.`lab_id` = sp.`lab_id`
                                            LEFT JOIN(
                                                SELECT
                                                    tr.sample_id,
                                                    GROUP_CONCAT(t.name_en SEPARATOR ", ") AS req_tests
                                                FROM `test_results` tr
                                                INNER JOIN test_samples ts
                                                ON ts.id = tr.test_sample_id
                                                AND ts.lab_id = tr.lab_id
                                                INNER JOIN tests t
                                                ON t.id = ts.test_id
                                                WHERE tr.lab_id = '.$this->baseLabId.'
                                                AND tr.record_status_id = 1
                                                GROUP BY tr.sample_id
                                            )req_test
                                            ON req_test.sample_id = sp.id
                                            WHERE '.$reportPeriodCondition.'
                                            AND inv.record_status_id = 1 AND sp.record_status_id = 1
                                            AND inv.lab_id = '.$this->baseLabId);
            $physicianArray = array();
            foreach ($invoices as $row) {
                $physicianArray[$row->physician_id]['physician_id'] = $row->physician_id;
                $physicianArray[$row->physician_id]['physician_name'] = $row->physician_name;

                $invoiceArray = array(
                    'id' => (string)$row->invoice_id,
                    'lab' => $row->lab,
                    'patient' => $row->patient,
                    'requested_tests' => (string) $row->req_tests,
                    'discount' => $row->discount,
                    'total_amount' => $row->total,
                    'net_amount' => $row->gross_total,
                    'owe_amount' => $row->balance
                );
                $physicianArray[$row->physician_id]['invoices'][] = $invoiceArray;
            }
            $arrData['report_data'] = $physicianArray;
            return response()->json(['success'=> true , 'data' => $arrData]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);

        }
    }

    public function yearlyInvoiceReport($year){
        try{
            $arrData = array();
            $arrData['report_period'] = $year;
            $yearlyData = DB::select('
                                        SELECT
                                            DATE_FORMAT(inv.`invoice_date`, "%m") AS month_id,
                                            DATE_FORMAT(inv.`invoice_date`, "%M") AS month_name,
                                            SUM(1) AS total_invoices,
                                            SUM(inv.`gross_total`) AS net_amount,
                                            SUM(inv.`deposit`) AS paid_amount,
                                            SUM(inv.`balance`) AS owe_amount
                                        FROM `invoices` inv
                                        INNER JOIN samples sp
                                        ON sp.id =inv.`sample_id` AND sp.`lab_id` = inv.`lab_id`
                                        INNER JOIN physicians ps
                                        ON ps.`id` = sp.`physician_id` AND ps.`lab_id` = sp.`lab_id`
                                        INNER JOIN `laboratories` lb
                                        ON lb.`id` = sp.`lab_id`
                                        INNER JOIN patients p
                                        ON p.`id` = sp.`patient_id` AND p.`lab_id` = sp.`lab_id`
                                        WHERE YEAR(inv.`invoice_date`) = '.$year.'
                                        GROUP BY DATE_FORMAT(inv.`invoice_date`, "%M"), DATE_FORMAT(inv.`invoice_date`, "%m")
            ');
            $yearlyInvoiceArray = array();
            foreach ($yearlyData as $row) {
                $invoiceArray = array(
                    'month_number' => (string)$row->month_id,
                    'month_name' => $row->month_name,
                    'total_invoice' => $row->total_invoices,
                    'total_net_amount' => $row->net_amount,
                    'total_paid_amount' => $row->paid_amount,
                    'total_owe_amount' => $row->owe_amount
                );
                $yearlyInvoiceArray[] = $invoiceArray;
            }
            $arrData['report_data'] = $yearlyInvoiceArray;
            return response()->json(['success'=> true , 'data' => $arrData]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    /**
     * ======================================
     * INVOICE REPORTS ENDED
     */


    /**
     * ======================================
     * SUMMARY REPORTS STARTED
     */

    public function summaryReport(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['generate_summary_report'])) return redirect(url('my-profile'));
            $startDate = $request->start_date;
            $endDate = $request->end_date;
            $arrData = array();
            $arrData['report_name'] = 'Summary Report';
            $arrData['report_period_from'] = $startDate;
            $arrData['report_period_to'] = $endDate;
            $reportData = DB::select('
                                SELECT
                                    st.`id` AS sample_type_id,
                                    st.`name_en` AS sample_type,
                                    -- ts.group_result as test_name,
                                    ts.group_result,
                                    -- t.`name_en` AS test_name,
                                    SUM(IF(p.`gender` =1, 1, 0)) AS total_male_patient,
                                    SUM(IF(p.`gender` =1, 0, 1)) AS total_female_patient,
                                    SUM(1) AS total_patient
                                FROM samples s
                                INNER JOIN test_results tr
                                ON tr.`sample_id` = s.`id`
                                AND s.`lab_id` = tr.`lab_id`
                                INNER JOIN test_samples ts
                                ON ts.id = tr.`test_sample_id`
                                INNER JOIN tests t
                                ON t.`id` = ts.`test_id`
                                INNER JOIN sample_types st
                                ON st.`id` = ts.`sample_type_id`
                                INNER JOIN patients p
                                ON p.id = s.patient_id
                                WHERE s.`lab_id`= '.$this->baseLabId.'
                                AND tr.`record_status_id` = 1
                                AND s.`record_status_id` = 1
                                AND p.`record_status_id` = 1
                                AND ts.group_result IS NOT NULL AND ts.group_result <> ""
                                AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).'"
                                GROUP BY st.`id`,
                                st.`name_en`,
                                ts.group_result,
                                t.`name_en`
				-- order by st.weight, ts.weight asc
            ');
            $summaryReportArray = array();
            $summary4Export = array();
            foreach ($reportData as $row) {
                $summaryReportArray[$row->sample_type_id]['sample_type'] = $row->sample_type;
                $arr = array(
                    'test_type' => $row->sample_type,
                    'group_result' => $row->group_result,
                    // 'test_name' => (string)$row->test_name,
                    'total_male_patient' => (int)$row->total_male_patient,
                    'total_female_patient' => (int)$row->total_female_patient,
                    'total_patient' => (int)$row->total_patient
                );
                $summaryReportArray[$row->sample_type_id]['test_name'][] = $arr;
                $summary4Export[] = $arr;
            }
            $arrData['report_data'] = collect($summaryReportArray)->flatten(1)->toArray();
            if($request->export) return $this->exportSummaryReport($summary4Export);
            $arrData['sample_source_data'] = $this->getSummaryReportBySampleSource($startDate, $endDate);
            $arrData['test_category_data'] = $this->getSummaryReportByTestCategory($startDate, $endDate);
            $arrData['test_date_data'] = $this->getSummaryReportByReceiveDate($startDate, $endDate);
			$arrData['performed_by'] = $this->getSummaryReportByPerformer($startDate, $endDate);

            return view('aggregate_report', ['report_data' => $arrData, 'labSettings' => (object) $this->location()]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }



    function getSummaryReportByTestCategory($startDate, $endDate){
        try{
             $reportData = DB::select('
                                SELECT
                                    ts.category,
                                    SUM(IF(p.`gender` =1, 1, 0)) AS total_male_patient,
                                    SUM(IF(p.`gender` =1, 0, 1)) AS total_female_patient,
                                    SUM(1) AS total_patient
                                FROM samples s
                                INNER JOIN test_results tr
                                ON tr.`sample_id` = s.`id`
                                AND s.`lab_id` = tr.`lab_id`
                                INNER JOIN test_samples ts
                                ON ts.id = tr.`test_sample_id`
                                INNER JOIN tests t
                                ON t.`id` = ts.`test_id`
                                INNER JOIN sample_types st
                                ON st.`id` = ts.`sample_type_id`
                                INNER JOIN patients p
                                ON p.id = s.patient_id
                                WHERE s.`lab_id`= '.$this->baseLabId.'
                                AND tr.`record_status_id` = 1
                                AND s.`record_status_id` = 1
                                AND p.`record_status_id` = 1
                                AND ts.category IS NOT NULL AND ts.category <> ""
                                AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).'"
                                GROUP BY
                                ts.category
            ');
            $sampleSourceReportArray = array();
            foreach ($reportData as $row) {
                $arr = array(
                    //'test_type' => $row->sample_type,
                    'category' => $row->category,
                    'total_male_patient' => (int)$row->total_male_patient,
                    'total_female_patient' => (int)$row->total_female_patient,
                    'total_patient' => (int)$row->total_patient
                );
                $sampleSourceReportArray[] = $arr;
            }
            return $sampleSourceReportArray;
        } catch (\Exception $e){
            return [];
        }
    }

    function getSummaryReportBySampleSource($startDate, $endDate){
        try{
            $sampleSourceData = DB::select('
                                    SELECT
                                        ss.`name_en` AS clinic_name,
                                        SUM(IF(p.`gender` =1, 1, 0)) AS total_male_patient,
                                        SUM(IF(p.`gender` =1, 0, 1)) AS total_female_patient,
                                        SUM(1) AS total_patient
                                    FROM samples s
                                    INNER JOIN patients p
                                    ON p.id = s.patient_id
                                    AND p.`lab_id` = s.`lab_id`
                                    INNER JOIN sample_sources ss
                                    ON ss.id = s.`sample_source_id`
                                    AND ss.`lab_id` = s.`lab_id`
                                    WHERE s.`lab_id`= '.$this->baseLabId.'
                                    AND s.`record_status_id` = 1
                                    AND p.`record_status_id` = 1
                                    AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).'"
                                    GROUP BY ss.`name_en`
            ');
            $sampleSourceReportArray = array();
            foreach ($sampleSourceData as $row) {
                $arr = array(
                    'clinic_name' => (string)$row->clinic_name,
                    'total_male_patient' => (int)$row->total_male_patient,
                    'total_female_patient' => (int)$row->total_female_patient,
                    'total_patient' => (int)$row->total_patient
                );
                $sampleSourceReportArray[] = $arr;
            }
            return $sampleSourceReportArray;
        } catch (\Exception $e){
            return [];
        }
    }

    function getSummaryReportByReceiveDate($startDate, $endDate){
        try{
            $sampleSourceData = DB::select('
                                    SELECT
                                        DATE_FORMAT(s.`received_date`, "%Y-%m-%d") AS received_date,
                                        SUM(IF(p.`gender` =1, 1, 0)) AS total_male_patient,
                                        SUM(IF(p.`gender` =1, 0, 1)) AS total_female_patient,
                                        SUM(1) AS total_patient
                                    FROM samples s
                                    INNER JOIN patients p
                                    ON p.id = s.patient_id
                                    AND p.`lab_id` = s.`lab_id`
                                    WHERE s.`lab_id`= '.$this->baseLabId.'
                                    AND s.`record_status_id` = 1
                                    AND p.`record_status_id` = 1
                                    AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).'"
                                    GROUP BY DATE_FORMAT(s.`received_date`, "%Y-%m-%d")
                                    ORDER BY s.`received_date`
            ');
            $sampleSourceReportArray = array();
            foreach ($sampleSourceData as $row) {
                $arr = array(
                    'received_date' => (string)$row->received_date,
                    'total_male_patient' => (int)$row->total_male_patient,
                    'total_female_patient' => (int)$row->total_female_patient,
                    'total_patient' => (int)$row->total_patient
                );
                $sampleSourceReportArray[] = $arr;
            }
            return $sampleSourceReportArray;
        } catch (\Exception $e){
            return [];
        }
    }

	function getSummaryReportByPerformer($startDate, $endDate){
        try{
            $sampleSourceData = DB::select('
                                    SELECT
                                        us.`name` AS performer_name,
                                        SUM(IF(p.`gender` =1, 1, 0)) AS total_male_patient,
                                        SUM(IF(p.`gender` =1, 0, 1)) AS total_female_patient,
                                        SUM(1) AS total_patient
                                    FROM samples s
                                    INNER JOIN patients p ON p.id = s.patient_id AND p.`lab_id` = s.`lab_id`
                                    INNER JOIN test_results AS tr ON s.id=tr.sample_id
									INNER JOIN users AS us ON tr.performed_by=us.id
                                    WHERE s.`lab_id`= '.$this->baseLabId.'
                                    AND s.`record_status_id` = 1
                                    AND p.`record_status_id` = 1
                                    AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).'"
                                    GROUP BY us.`name`
            ');
            $sampleSourceReportArray = array();
            foreach ($sampleSourceData as $row) {
                $arr = array(
                    'performer_name' => (string)$row->performer_name,
                    'total_male_patient' => (int)$row->total_male_patient,
                    'total_female_patient' => (int)$row->total_female_patient,
                    'total_patient' => (int)$row->total_patient
                );
                $sampleSourceReportArray[] = $arr;
            }
            return $sampleSourceReportArray;
        } catch (\Exception $e){
            return [];
        }
    }
    /**
     * ======================================
     * SUMMARY REPORTS ENDED
     */


    /**
     * ======================================
     * DOCTOR REPORTS STARTED
     */

    public function doctorReport(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['generate_doctor_report'])) return redirect(url('my-profile'));
            $startDate = $request->start_date;
            $endDate = $request->end_date;
            $sampleSourceId = (isset($request->sample_source) && !empty($request->sample_source)) ? $request->sample_source : NULL;
            $physicianId = (isset($request->physician) && !empty($request->physician)) ? $request->physician : NULL;
            $arrData = array();
            $arrData['report_name'] = 'Doctor Report';
            $arrData['report_period_from'] = $startDate;
            $arrData['report_period_to'] = $endDate;
            $reportData = DB::select('
                                SELECT
                                    ss.`name_en` AS sample_source_name,
                                    SUM(1) AS total_exam,
                                    SUM(tp.`total_price`) AS total_net_amount
                                FROM samples s
                                INNER JOIN patients p
                                ON p.id = s.patient_id
                                AND p.`lab_id` = s.`lab_id`
                                INNER JOIN sample_sources ss
                                ON ss.id = s.`sample_source_id`
                                AND ss.`lab_id` = s.`lab_id`

                                LEFT JOIN(
                                    SELECT
                                        s.id AS sample_id,
                                        s.`lab_id`,
                                        SUM(ts.`usd_price`) AS total_price
                                    FROM samples s
                                    INNER JOIN test_results r
                                    ON r.`sample_id` = s.`id`
                                    AND r.`lab_id` = s.`lab_id`
                                    INNER JOIN test_samples ts
                                    ON ts.`id` = r.`test_sample_id`
                                    WHERE s.`record_status_id`=1
                                    AND r.`record_status_id` =1
                                    AND ts.`record_status_id` =1
                                    GROUP BY s.`id`, s.`lab_id`

                                ) tp ON tp.sample_id = s.id AND s.`lab_id` = tp.lab_id
                                WHERE s.`lab_id`= '.$this->baseLabId.'
                                AND s.`record_status_id` = 1
                                AND p.`record_status_id` = 1
                                AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).'"
                                GROUP BY ss.`name_en`');
            $doctorReportArray = array();
            foreach ($reportData as $k=>$row) {
                $arr = array(
                    'no' => $k+1,
                    'sample_source_name' => (string)$row->sample_source_name,
                    'total_exam' => (int)$row->total_exam,
                    'total_net_amount' => (float)$row->total_net_amount
                );
                $doctorReportArray[] = $arr;
            }

            if(empty($sampleSourceId) && empty($physicianId)){
                $arrData['report_data'] = $doctorReportArray;
                $arrData['report_id'] = 1;
                if($request->export){
                    return $this->exportDoctorSampleBase($arrData['report_data']);
                }
            } elseif (!empty($sampleSourceId) && empty($physicianId)){
                $arrData['report_data'] = $this->getDoctorReportGroupByPhysician($startDate, $endDate, $sampleSourceId);
                $arrData['report_id'] = 2;
                if($request->export){
                    return $this->exportDoctorPhysicianBase($arrData['report_data']);
                }
            }else{
                $arrData['report_data'] = $this->getDoctorReportRawByPhysician($startDate, $endDate,$sampleSourceId, $physicianId);
                $arrData['report_id'] = 3;
                if($request->export){
                    return $this->exportDoctorRawBase($arrData['report_data']);
                }
            }

            $printDoctorData = $this->getDoctorReportRawBySampleSource($startDate, $endDate, !empty($sampleSourceId) ? $sampleSourceId : 0 );
            $printRawByPhysician = $this->getDoctorReportRawByPhysician($startDate, $endDate,$sampleSourceId, $physicianId);

            //$printDoctorReportDetail = $this->getDoctorReportDetail($startDate, $endDate,$sampleSourceId, $physicianId);

            $sampleSources = $this->sampleSourceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->get();
            $physicians = $this->physicianModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->get();

            return view('doctor_report', ['report_data' => $arrData , 'sampleSources' => $sampleSources, 'physicians' => $physicians, 'labSettings' => (object) $this->location(), 'printDoctorData' => $printDoctorData, 'printRawByPhysician' => $printRawByPhysician]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }

    function getDoctorReportGroupByPhysician($startDate, $endDate, $sampleSourceId = null){
        try{
            $sampleSourceCondition = !is_null($sampleSourceId) ? ' AND s.sample_source_id='.$sampleSourceId :'';
            $sampleSourceData = DB::select('
                                    SELECT
                                        ps.`name_en` AS physician_name,
                                        SUM(1) AS total_exam,
                                        SUM(tp.`total_price`) AS total_net_amount
                                    FROM samples s

                                    INNER JOIN patients p
                                    ON p.id = s.patient_id
                                    AND p.`lab_id` = s.`lab_id`
                                    INNER JOIN sample_sources ss
                                    ON ss.id = s.`sample_source_id`
                                    AND ss.`lab_id` = s.`lab_id`
                                    INNER JOIN physicians ps
                                    ON ps.`id` = s.`physician_id`

                                    LEFT JOIN(
                                        SELECT
                                            s.id AS sample_id,
                                            s.`lab_id`,
                                            SUM(ts.`usd_price`) AS total_price
                                        FROM samples s
                                        INNER JOIN test_results r
                                        ON r.`sample_id` = s.`id`
                                        AND r.`lab_id` = s.`lab_id`
                                        INNER JOIN test_samples ts
                                        ON ts.`id` = r.`test_sample_id`
                                        WHERE s.`record_status_id`=1
                                        AND r.`record_status_id` =1
                                        AND ts.`record_status_id` =1
                                        GROUP BY s.`id`, s.`lab_id`

                                    ) tp ON tp.sample_id = s.id AND s.`lab_id` = tp.lab_id

                                    WHERE s.`lab_id`= '.$this->baseLabId.'
                                    '.$sampleSourceCondition.'

                                    AND s.`record_status_id` = 1
                                    AND p.`record_status_id` = 1
                                    AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).'"
                                    GROUP BY ps.`name_en`;
            ');
            $physicianReportArray = array();
            foreach ($sampleSourceData as $k=>$row) {
                $arr = array(
                    'no' => $k+1,
                    'physician_name' => (string)$row->physician_name,
                    'total_exam' => (int)$row->total_exam,
                    'total_net_amount' => (float)$row->total_net_amount
                );
                $physicianReportArray[] = $arr;
            }
            return $physicianReportArray;
        } catch (\Exception $e){
            return [];
        }
    }

    public function getDoctorReportRawByPhysician($startDate, $endDate, $sample_source='', $physicianId = null){
        try{
            $physicianCondition = !empty($physicianId) && $physicianId!='All' ? ' AND s.physician_id='.$physicianId :'';
            $sample_sourceCondition = !empty($sample_source) ? ' AND ss.id='.$sample_source :'';
            $rawTestByPhysician = DB::select('
                                                SELECT
                                                    s.received_date as `invoice_date`,
                                                    ss.name_en as sample_source,
                                                    p.`name_en` AS patient,
                                                    s.`sample_number`,
                                                    -- req_test.req_tests AS test_name,
                                                    req_test.group_result as test_name,
                                                    ps.`name_en` AS physician_name,
                                                    tp.total_price AS total_amount,
                                                    tp.total_price AS total_net_amount
                                                FROM samples s
                                                INNER JOIN patients p
                                                ON p.id = s.patient_id
                                                AND p.`lab_id` = s.`lab_id`
                                                INNER JOIN sample_sources ss
                                                ON ss.id = s.`sample_source_id`
                                                AND ss.`lab_id` = s.`lab_id`
                                                INNER JOIN physicians ps
                                                ON ps.`id` = s.`physician_id`
                                                LEFT JOIN(
                                                    SELECT
                                                        s.id AS sample_id,
                                                        s.`lab_id`,
                                                        SUM(ts.`usd_price`) AS total_price
                                                    FROM samples s
                                                    INNER JOIN test_results r
                                                    ON r.`sample_id` = s.`id`
                                                    AND r.`lab_id` = s.`lab_id`
                                                    INNER JOIN test_samples ts
                                                    ON ts.`id` = r.`test_sample_id`
                                                    WHERE s.`record_status_id`=1
                                                    AND r.`record_status_id` =1
                                                    AND ts.`record_status_id` =1
                                                    GROUP BY s.`id`, s.`lab_id`

                                                ) tp ON tp.sample_id = s.id AND s.`lab_id` = tp.lab_id
                                                LEFT JOIN(
                                                    SELECT
                                                        tr.sample_id,
                                                        GROUP_CONCAT(t.name_en SEPARATOR ", ") AS req_tests,
														GROUP_CONCAT(DISTINCT CASE WHEN ts.lab_id = 22 THEN SUBSTR(ts.`group_result`, 1, 4) ELSE ts.`group_result` END SEPARATOR ", ") AS group_result

                                                FROM `test_results` tr
                                                    INNER JOIN test_samples ts
                                                    ON ts.id = tr.test_sample_id
                                                    AND ts.lab_id = tr.lab_id
                                                    INNER JOIN tests t
                                                    ON t.id = ts.test_id
                                                    WHERE tr.lab_id = '.$this->baseLabId.'
                                                    AND tr.record_status_id = 1
                                                    AND ts.`record_status_id` =1
                                                    AND LENGTH(ts.`group_result`)>=1
                                                    GROUP BY tr.sample_id
                                                )req_test
                                                ON req_test.sample_id = s.id
                                                WHERE s.`lab_id`= '.$this->baseLabId.'
                                                '.$physicianCondition.'
                                                AND s.`record_status_id` = 1
                                                AND p.`record_status_id` = 1
                                                and req_test.group_result is not null
                                                '.$sample_sourceCondition.'
                                                AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).' order by s.received_date ASC "
            ');
            $physicianReportArray = array();
            foreach ($rawTestByPhysician as $row) {
                $arr = array(
                    'date' => (string)date('d-M-Y',strtotime($row->invoice_date)),
                    'sample_source' => (string) $row->sample_source,
                    'patient' => (string)$row->patient,
                    'sample_number' => (string)$row->sample_number,
                    'test_name' => (string)$row->test_name,
                    'physician' => (string)$row->physician_name,
                    'total_amount' => (float)$row->total_amount,
                    'total_net_amount' => (float)$row->total_net_amount,
                );
                $physicianReportArray[] = $arr;
            }
            asort($physicianReportArray);
            return $physicianReportArray;
        } catch (\Exception $e){
            return [];
        }
    }

    public function getDoctorReportRawBySampleSource($startDate, $endDate, $sampleSourceId){
        try{
            $rawDoctorReportPrint = DB::select('
                                                SELECT
                                                    s.received_date as `register_date`,
                                                    s.`sample_number`,
                                                    p.`name_en` AS patient,
                                                    ss.id sample_source_id,
                                                    ss.name_en as sample_source,
                                                    IF(p.gender=1, "M","F") as gender,
                                                    p.dob,
                                                    req_test.total_tests,
                                                    req_test.total_price AS total_price
                                                FROM samples s
                                                INNER JOIN patients p
                                                ON p.id = s.patient_id
                                                AND p.`lab_id` = s.`lab_id`
                                                INNER JOIN sample_sources ss
                                                ON ss.id = s.`sample_source_id`
                                                AND ss.`lab_id` = s.`lab_id`
                                                LEFT JOIN(
                                                    SELECT
                                                        tr.sample_id,
                                                        count(*) as total_tests,
                                                        SUM(ts.`usd_price`) AS total_price
                                                    FROM `test_results` tr
                                                    INNER JOIN test_samples ts
                                                    ON ts.id = tr.test_sample_id
                                                    AND ts.lab_id = tr.lab_id
                                                    INNER JOIN tests t
                                                    ON t.id = ts.test_id
                                                    WHERE tr.lab_id = '.$this->baseLabId.'
                                                    AND tr.record_status_id = 1
                                                    AND ts.`record_status_id` =1
                                                    AND LENGTH(ts.`group_result`)>=1
                                                    GROUP BY tr.sample_id
                                                )req_test
                                                ON req_test.sample_id = s.id
                                                WHERE s.`lab_id`= '.$this->baseLabId.'
                                                '.(!empty($sampleSourceId) ? 'AND s.sample_source_id='.$sampleSourceId:'').'
                                                AND s.`record_status_id` = 1
                                                AND p.`record_status_id` = 1
                                                AND DATE(s.received_date) BETWEEN "'.date('Y-m-d', strtotime($startDate)).'" AND "'.date('Y-m-d', strtotime($endDate)).'"
            ');
            $departmentArray = array();
            foreach ($rawDoctorReportPrint as $row){
                $departmentArray[$row->sample_source_id]['sample_source_id'] = $row->sample_source_id;
                $departmentArray[$row->sample_source_id]['sample_source'] = $row->sample_source;
                $testItemArray = array(
                    'register_date' => date('d/m/Y',strtotime($row->register_date)),
                    'sample_number' => $row->sample_number,
                    'patient' => $row->patient,
                    'gender' => $row->gender,
                    'age' => (string) Helpers::getAge($row->dob, $row->register_date),
                    'total_tests' => (integer) $row->total_tests,
                    'total_price' =>(float) $row->total_price
                );
                //dd($testItemArray);
                $departmentArray[$row->sample_source_id]['data'][] = $testItemArray;
            }

            //dd($departmentArray);
            return collect($departmentArray)->values();

            return $rawDoctorReportPrint;
        } catch (\Exception $e){
            return [];
        }
    }


    /**
     * ======================================
     * DOCTOR REPORTS ENDED
     */


         /**
     * ======================================
     * FINANCIAL REPORTS ENDED
     */

     public function financialReport(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['generate_financial_report'])) return redirect(url('my-profile'));
            $startDate = $request->start_date;
            $endDate = $request->end_date;
            $sampleSourceId = (isset($request->sample_source) && !empty($request->sample_source)) ? $request->sample_source : NULL;
            $physicianId = (isset($request->physician) && !empty($request->physician)) ? $request->physician : NULL;
            $arrData = array();
            $arrData['report_name'] = 'Financial Report';
            $arrData['report_period_from'] = $startDate;
            $arrData['report_period_to'] = $endDate;

            $financialReport = $this->getFinancialReport($startDate, $endDate,$sampleSourceId, $physicianId);

            if($request->export){
                return $this->exportFinancialReport($financialReport);
            }



            $sampleSources = $this->sampleSourceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->get();
            $physicians = $this->physicianModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->get();

            return view('financial_report', ['report_data' => $arrData , 'sampleSources' => $sampleSources, 'physicians' => $physicians, 'labSettings' => (object) $this->location(), 'financialReport' => $financialReport]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'errors' => $e->getMessage()]);
        }
    }


    public function getFinancialReport($startDate, $endDate, $sample_source='', $physicianId = null){
        try{
            //\DB::enableQueryLog();
            $physicianCondition = !empty($physicianId) && $physicianId!='All' ? ' AND s.physician_id='.$physicianId :'';
            $sample_sourceCondition = !empty($sample_source) ? ' AND ss.id='.$sample_source :'';
            $rawTestByPhysician = DB::select("
            select
            	inv.`invoice_date`,
                    ss.`name_en` as sample_source,
            	    p.`name_en` AS patient,
            	    s.`sample_number`,
            	   invd.test_name,
            	   inv.exchange_rate,
            	    ps.`name_en` AS physician_name,
            	   sum(inv.total) AS total_amount,
            	   sum(inv.gross_total) AS total_net_amount,
            	   sum(inv.total) - SUM(inv.gross_total) as discount,
            	   sum(ifnull(inv.deposit, 0)) as total_paid,
            	   sum(ifnull(inv.bank_deposit,0)) as total_bank_paid,
            	   -- sum(inv.gross_total) - SUM(inv.deposit) as total_owe,
            	   sum(inv.balance) as total_owe
            from invoices inv
            inner join samples s on s.`id` = inv.`sample_id` and s.`lab_id` = inv.`lab_id` and s.`record_status_id` = 1
            inner join patients p on p.`id` = s.`patient_id` and p.`lab_id` = s.`lab_id`
            INNER JOIN sample_sources ss ON ss.id = s.`sample_source_id` AND ss.`lab_id` = s.`lab_id`
            INNER JOIN physicians ps ON ps.`id` = s.`physician_id`
            inner join (
            	select
            		inv.id,
            		group_concat(distinct invd.test_name SEPARATOR ', ') as test_name
            	from invoice_details invd
            	inner join invoices inv ON inv.id = invd.invoice_id
            	WHERE inv.`record_status_id` = 1
            	AND DATE(inv.invoice_date) BETWEEN '".date('Y-m-d', strtotime($startDate))."' AND '".date('Y-m-d', strtotime($endDate))."'
            	AND inv.lab_id=  ".$this->baseLabId."
            	group by inv.id
            )invd
            on invd.id = inv.id
            where inv.`record_status_id` = 1
            ".$physicianCondition."
            ".$sample_sourceCondition."
            AND DATE(inv.invoice_date) BETWEEN '".date('Y-m-d', strtotime($startDate))."' AND '".date('Y-m-d', strtotime($endDate))."'
            and inv.lab_id= ".$this->baseLabId."
            group by inv.`invoice_date`,
            	ss.`name_en`,
            	p.`name_en`,
            	s.`sample_number`,
            	ps.`name_en`,
            	invd.test_name,
            	inv.exchange_rate
            	order by sample_number asc
            ");
            //dd(\DB::getQueryLog());
            $physicianReportArray = array();
            $i = 1;
            foreach ($rawTestByPhysician as $row) {
                $arr = array(
                    'no' => strtotime($row->invoice_date),
                    'date' => (string)date('d-M-Y',strtotime($row->invoice_date)),
                    'sample_number' => (string)$row->sample_number,
                    'patient' => (string)$row->patient,
                    'test_name' => (string)$row->test_name,
                    'physician' => (string)$row->physician_name,
                    'exchange_rate' => @$row->exchange_rate,
                    'total_amount' => (float)$row->total_amount,
                    'total_discount' => (float)$row->discount,
                    'total_net_amount' => (float)$row->total_net_amount,
                    'total_paid' => (float)$row->total_paid,
                    'total_bank_paid' => (float)$row->total_bank_paid,
                    'total_owe' => (float)$row->total_owe,
                );
                $physicianReportArray[] = $arr;
                $i++;
            }

            if(($sample_source=='-1' || empty($sample_source)) && empty($physicianId)){
                $vaccinationReports = $this->getVaccinationReport($startDate, $endDate);
                foreach ($vaccinationReports as $vaccinationReport) {
                    $arrVac = array(
                        'no' => strtotime($vaccinationReport->invoice_date),
                        'date' => (string)date('d-M-Y',strtotime($vaccinationReport->invoice_date)),
                        'sample_number' => (string)$vaccinationReport->sample_number,
                        'patient' => (string)$vaccinationReport->patient,
                        'test_name' => (string)$vaccinationReport->test_name,
                        'physician' => (string)$vaccinationReport->physician_name,
                        'exchange_rate' =>@$vaccinationReport->exchange_rate,
                        'total_amount' => (float)$vaccinationReport->total_amount,
                        'total_discount' => (float)$vaccinationReport->discount,
                        'total_net_amount' => (float)$vaccinationReport->total_net_amount,
                        'total_paid' => (float)$vaccinationReport->total_paid,
                        'total_bank_paid' => (float)$vaccinationReport->total_bank_paid,
                        'total_owe' => (float)$vaccinationReport->total_owe,
                    );
                    $physicianReportArray[] = $arrVac;
                    $i++;
                }
            }
            if(($sample_source=='-2' || empty($sample_source)) && empty($physicianId)){
                //$dialyReports = $this->getDailyReport($startDate, $endDate, $physicianId);
               // if(Auth::id()==1){
                     $dialyReports = $this->getDailyReportV2($startDate, $endDate, $physicianId);
               // }

                $j=1;
                foreach ($dialyReports as $vaccinationReport) {
                    $arrVac = array(
                        'no' => strtotime($vaccinationReport->invoice_date),
                        'date' => (string)date('d-M-Y',strtotime($vaccinationReport->invoice_date)),
                        'sample_number' => (string)$vaccinationReport->sample_number,
                        'patient' => (string)$vaccinationReport->patient,
                        'test_name' => (string)$vaccinationReport->test_name,
                        'physician' => (string)$vaccinationReport->physician_name,
                        'exchange_rate' => @$vaccinationReport->exchange_rate,
                        'total_amount' => (float)$vaccinationReport->total_amount,
                        'total_discount' => (float)$vaccinationReport->discount,
                        'total_net_amount' => (float)$vaccinationReport->total_net_amount,
                        'total_paid' => (float)$vaccinationReport->total_paid,
                        'total_bank_paid' => (float)$vaccinationReport->total_bank_paid,
                        'total_owe' => (float)$vaccinationReport->total_owe,
                    );
                    $physicianReportArray[] = $arrVac;
                    $j++;
                }
            }



// Sort the array
//usort($physicianReportArray, 'date_compare');

sort($physicianReportArray);
           // dd($physicianReportArray);
            return $physicianReportArray;
        } catch (\Exception $e){
            return [];
        }
    }

    public function getDailyReport($startDate, $endDate, $physicianId = null){
        try{
            //\DB::enableQueryLog();
            $physicianCondition = !empty($physicianId) && $physicianId!='All' ? ' AND s.physician_id='.$physicianId :'';
            $rawTestByPhysician = DB::select("
            select
            	inv.first_paid_date as `invoice_date`,
                    ss.`name_en` as sample_source,
            	    p.`name_en` AS patient,
            	    s.`sample_number`,
            	   invd.test_name,
            	   inv.exchange_rate,
            	    ps.`name_en` AS physician_name,
            	   sum(inv.total) AS total_amount,
            	   sum(inv.gross_total) AS total_net_amount,
            	   sum(inv.total) - SUM(inv.gross_total) as discount,
            	   sum(ifnull(inv.deposit, 0)) as total_paid,
            	   sum(ifnull(inv.bank_deposit,0)) as total_bank_paid,
            	   -- sum(inv.gross_total) - SUM(inv.deposit) as total_owe,
            	   sum(inv.balance) as total_owe
            from invoices inv
            inner join samples s on s.`id` = inv.`sample_id` and s.`lab_id` = inv.`lab_id` and s.`record_status_id` = 1
            inner join patients p on p.`id` = s.`patient_id` and p.`lab_id` = s.`lab_id`
            INNER JOIN sample_sources ss ON ss.id = s.`sample_source_id` AND ss.`lab_id` = s.`lab_id`
            INNER JOIN physicians ps ON ps.`id` = s.`physician_id`
            inner join (
            	select
            		inv.id,
            		group_concat(distinct invd.test_name SEPARATOR ', ') as test_name
            	from invoice_details invd
            	inner join invoices inv ON inv.id = invd.invoice_id
            	WHERE inv.`record_status_id` = 1
            	AND DATE(inv.first_paid_date) BETWEEN '".date('Y-m-d', strtotime($startDate))."' AND '".date('Y-m-d', strtotime($endDate))."'
            	AND inv.lab_id=  ".$this->baseLabId."
            	group by inv.id
            )invd
            on invd.id = inv.id
            where inv.`record_status_id` = 1
            ".$physicianCondition."
            AND DATE(inv.first_paid_date) BETWEEN '".date('Y-m-d', strtotime($startDate))."' AND '".date('Y-m-d', strtotime($endDate))."'
            and inv.lab_id= ".$this->baseLabId."
            group by inv.`first_paid_date`,
            	ss.`name_en`,
            	p.`name_en`,
            	s.`sample_number`,
            	ps.`name_en`,
            	invd.test_name,
            	inv.exchange_rate
            	order by sample_number asc
            ");

            return $rawTestByPhysician;
        } catch (\Exception $e){
            return [];
        }
    }

    public function getDailyReportV2($startDate, $endDate, $physicianId = null){
        try{
            //\DB::enableQueryLog();
            $physicianCondition = !empty($physicianId) && $physicianId!='All' ? ' AND s.physician_id='.$physicianId :'';
            $rawTestByPhysician = DB::select("
            select
            	r.repayment_date as `invoice_date`,
                    ss.`name_en` as sample_source,
            	    p.`name_en` AS patient,
            	    s.`sample_number`,
            	    concat('Repayment for invoice ',inv.invoice_code) as test_name,
            	   r.exchange_rate,
            	    ps.`name_en` AS physician_name,
            	   sum(r.cash_repayment_amount + r.bank_repayment_amount) AS total_amount,
            	   sum(r.cash_repayment_amount + r.bank_repayment_amount) AS total_net_amount,
            	   0 as discount,
            	   sum(r.cash_repayment_amount) as total_paid,
            	   sum(r.bank_repayment_amount) as total_bank_paid,
            	   0 as total_owe
            from repayments r
            inner join invoices inv on inv.id = r.invoice_id and r.lab_id = inv.lab_id and inv.record_status_id = 1
            inner join samples s on s.`id` = inv.`sample_id` and s.`lab_id` = inv.`lab_id` and s.`record_status_id` = 1
            inner join patients p on p.`id` = s.`patient_id` and p.`lab_id` = s.`lab_id`
            INNER JOIN sample_sources ss ON ss.id = s.`sample_source_id` AND ss.`lab_id` = s.`lab_id`
            INNER JOIN physicians ps ON ps.`id` = s.`physician_id`
            where r.`record_status_id` = 1
            ".$physicianCondition."
            AND DATE(r.repayment_date) BETWEEN '".date('Y-m-d', strtotime($startDate))."' AND '".date('Y-m-d', strtotime($endDate))."'
            and r.lab_id= ".$this->baseLabId."
            group by r.`repayment_date`,
            	ss.`name_en`,
            	p.`name_en`,
            	s.`sample_number`,
            	ps.`name_en`,
            	r.exchange_rate,
            	inv.invoice_code
            	order by sample_number asc
            ");

            return $rawTestByPhysician;
        } catch (\Exception $e){
    dd($e);
            return [];
        }
    }

    public function getVaccinationReport($startDate, $endDate){
        try{
            //\DB::enableQueryLog();
            $rawTestByPhysician = DB::select("
            SELECT
               inv.vaccination_date AS `invoice_date`,
                'Vaccination' AS sample_source,
                p.`name_en` AS patient,
                inv.invoice_code AS `sample_number`,
                invd.test_name,
                '' AS physician_name,
                inv.exchange_rate,
               SUM(inv.total) AS total_amount,
               SUM(inv.gross_total) AS total_net_amount,
               SUM(inv.total) - SUM(inv.gross_total) AS discount,
               SUM(IFNULL(inv.deposit, 0)) AS total_paid,
               SUM(IFNULL(inv.bank_deposit,0)) AS total_bank_paid,
               SUM(inv.balance) AS total_owe
            FROM vaccination_invoices inv
            INNER JOIN patients p ON p.`id` = inv.`patient_id` AND p.`lab_id` = inv.`lab_id`
            INNER JOIN (
            SELECT
            	inv.id,
            	GROUP_CONCAT(DISTINCT m.name SEPARATOR ', ') AS test_name
            FROM vaccination_invoice_details invd
            INNER JOIN vaccination_invoices inv ON inv.id = invd.vac_invoice_id
            INNER JOIN `medicine_items` mi ON mi.id = invd.medicine_item_id
            INNER JOIN medicines m ON m.id = mi.medicine_id
            WHERE inv.`record_status_id` = 1
            AND DATE(inv.vaccination_date) BETWEEN '".date('Y-m-d', strtotime($startDate))."' AND '".date('Y-m-d', strtotime($endDate))."'
            AND inv.lab_id= ".$this->baseLabId."
            GROUP BY inv.id
            )invd
            ON invd.id = inv.id

            WHERE inv.`record_status_id` = 1

                      AND DATE(inv.vaccination_date) BETWEEN '".date('Y-m-d', strtotime($startDate))."' AND '".date('Y-m-d', strtotime($endDate))."'
                        AND inv.lab_id= ".$this->baseLabId."
                        GROUP BY inv.`vaccination_date`,
                        	p.`name_en`,
                        	inv.invoice_code,
                        	invd.test_name,
                        	 inv.exchange_rate
                        	ORDER BY inv.invoice_code ASC
            ");
            //dd(\DB::getQueryLog());
            return $rawTestByPhysician;
        } catch (\Exception $e){
            return [];
        }
    }


    /**
     * =====================================
     * EXPORT FUNCTION STARTED
     */

    function exportDoctorSampleBase($arrData){
        $data = $arrData;
        $titleHeading = [
            __('No'),
            __('Sample Source'),
            __('Exam'),
            __('Net Amount'),
        ];
        $export = new DoctorSampleSourceExport($data);
        $export->setTitle(__('Doctor Report'));
        $export->setTitleHeadingTable($titleHeading);
        $dateTime = Carbon::now()->toDateTime()->format(DateFormatEnum::YmdHis);
        $fileName = 'doctor_report_by_sample'.$dateTime.'.xlsx';
        return Excel::download($export, $fileName);
    }

    function exportDoctorPhysicianBase($arrData){
        $data = $arrData;
        $titleHeading = [
            __('No'),
            __('Physician'),
            __('Exam'),
            __('Net Amount'),
        ];
        $export = new DoctorPhysicianExport($data);
        $export->setTitle(__('Doctor Report'));
        $export->setTitleHeadingTable($titleHeading);
        $dateTime = Carbon::now()->toDateTime()->format(DateFormatEnum::YmdHis);
        $fileName = 'doctor_report_by_physician'.$dateTime.'.xlsx';
        return Excel::download($export, $fileName);
    }

    function exportDoctorRawBase($arrData){
        $data = $arrData;
        $titleHeading = [
            __('Date'),
            __('Sample Source'),
            __('Patient'),
            __('Sample Number'),
            __('Test Name'),
            __('Physician'),
            __('Total Amount'),
            __('Net Amount'),
        ];
        $export = new DoctorPhysicianExport($data);
        $export->setTitle(__('Doctor Report'));
        $export->setTitleHeadingTable($titleHeading);
        $dateTime = Carbon::now()->toDateTime()->format(DateFormatEnum::YmdHis);
        $fileName = 'doctor_report'.$dateTime.'.xlsx';
        return Excel::download($export, $fileName);
    }

    function exportSummaryReport($arrData){
        $data = $arrData;
        $titleHeading = [
            __('Sample Type'),
            __('Test Type'),
            __('Male Patient'),
            __('Female Patient'),
            __('Total Patient')
        ];
        $export = new SummaryReportExport($data);
        $export->setTitle(__('Summary Report by Test Type'));
        $export->setTitleHeadingTable($titleHeading);
        $dateTime = Carbon::now()->toDateTime()->format(DateFormatEnum::YmdHis);
        $fileName = 'summary_report'.$dateTime.'.xlsx';
        return Excel::download($export, $fileName);
    }

    function exportFinancialReport($arrData){
        $data = $arrData;
        $titleHeading = [
            __('No'),
            __('Invoice Date'),
            __('Sample Number'),
            __('Patient Name'),
            __('Test Name'),
            __('Physician'),
            __('Exchange Rate'),
            __('Total'),
            __('Discount'),
            __('Net Amount'),
            __('Cash Pay'),
            __('Bank Pay'),
            __('Owe'),
        ];
        $export = new FinancialReportExport($data);
        $export->setTitle(__('Financial Report'));
        $export->setTitleHeadingTable($titleHeading);
        $dateTime = Carbon::now()->toDateTime()->format(DateFormatEnum::YmdHis);
        $fileName = 'financial_report'.$dateTime.'.xlsx';
        return Excel::download($export, $fileName);
    }



}
