<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Models\BaseModel;
use App\Models\Invoice;
use App\Models\Sample;

use App\Http\Controllers\Helper\GlobalController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class DashboardController extends Controller
{
    protected $sampleModel;
    protected $invoiceModel;
    private $baseLabId;
    protected $base;

    public function __construct(Sample $sampleModel, Invoice $invoiceModel){
        $this->sampleModel = $sampleModel;
        $this->invoiceModel = $invoiceModel;
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');

    }

    function index(Request $q){
        return redirect(url('my-profile'));
        $growthSample = 0;
        $displaySample = '';
        $displaySampleResult = 0;
        $growthIncome = 0;
        $displayIncome = '';
        $displayIncomeResult = 0;
        $growthPatient = 0;
        $displayPatient = '';
        $displayPatientResult = 0;
        $totalRejectedSample = $this->getTotalRejectedSampleCount();

        $growthRejectedSample = 0;

        $todaySamples = $this->getTodaySamples();
        $yesterdaySample = $this->getYesterdaySampleCount();
        if($yesterdaySample>0){
            $growthIncome = (($todaySamples->count() - $yesterdaySample) / $yesterdaySample) * 100;
        }
        $displaySample=__('general.chart_filter_today');
        $displaySampleResult = $todaySamples->count();

         //income
        $todayIncome = $this->getTodayIncome();
        $todayIncome+=$this->getDailyReportV2(date('Y-m-d'), date('Y-m-d'));
        $yesterdayIncome = $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereDate('invoice_date', date('Y-m-d', strtotime('-1 day')))->sum('gross_total');
        $yesterdayIncome+=$this->getDailyReportV2(date('Y-m-d', strtotime('-1 day')), date('Y-m-d', strtotime('-1 day')));
        if($yesterdayIncome>0){
            $growthIncome = (($todayIncome - $yesterdayIncome) / $yesterdayIncome) * 100;
        }
        $displayIncome=__('general.chart_filter_today');
        $displayIncomeResult = number_format($todayIncome);

        //disaplay patient
        $todayPatient = $this->getTodayPatient();
        $yesterdayPatient = $this->getYesterdayPatient();
        if($yesterdayPatient>0){
            $growthPatient = (($todayPatient - $yesterdayPatient) / $yesterdayPatient) * 100;
        }
        $displayPatient=__('general.chart_filter_today');
        $displayPatientResult = $todayPatient;

         $todayRejectedSample = $this->getTodayRejectedSamples()->count();
        $yesterdayRejectedSample = $this->getYesterdayRejectedSamples()->count();
        if($yesterdayRejectedSample>0){
            $growthRejectedSample = (($todayRejectedSample - $yesterdayRejectedSample) / $yesterdayRejectedSample) * 100;
        }
        $displayRejectedSample=__('general.chart_filter_today');
        $displayRejectedSampleResult = $todayRejectedSample;

        return view('dashboard',[
            'growthSample' => number_format($growthSample, 2),
            'totalSample' => $displaySampleResult,
            'displaySample' => $displaySample,
            'displaySampleResult' => $displaySampleResult,
            'growthIncome' => number_format($growthIncome, 2),
            'displayIncome' => $displayIncome,
            'displayIncomeResult' => $displayIncomeResult,
            'totalIncome' => $displayIncomeResult,
            'totalPatient' => $displayPatientResult,
            'growthPatient' => number_format($growthPatient, 2),
            'displayPatient' => $displayPatient,
            'displayPatientResult' => $displayPatientResult,
            'totalRejectedSample' => $totalRejectedSample,
            'growthRejectedSample' => number_format($growthRejectedSample, 2),
            'displayRejectedSample' => $displayRejectedSample,
            'displayRejectedSampleResult' => $displayRejectedSampleResult,

            'labSettings' => (object) $this->base
        ]);
    }

    function filter_sample(Request $q)
    {
        $growthSample = 0;
        if ($q->dt == 'this_month'){
            $monlthlySample= $this->getThisMonthSamples()->count();
            $last_monthSample = $this->getPreviousMonthSamples()->count();
            if($last_monthSample>0){
                $growthSample = (($monlthlySample - $last_monthSample) / $last_monthSample) * 100;
            }
            $displaySample=__('general.chart_filter_this_month');
            $displaySampleResult = $monlthlySample;

        } elseif ($q->dt == 'this_year'){
            $yearSamples = $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                ->whereYear('admission_date', date('Y'))->count();
            $last_yearSample = $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                ->whereYear('admission_date', (date('Y')-1))->count();
            if($last_yearSample>0){
                $growthSample = (($yearSamples - $last_yearSample) / $last_yearSample);
            }
            $displaySample=__('general.chart_filter_this_year');
            $displaySampleResult = $yearSamples;
        }
        else{
            $todaySamples = $this->getTodaySamples();
            $yesterdaySample = $this->getYesterdaySampleCount();
            if($yesterdaySample>0){
                $growthSample = (($todaySamples->count() - $yesterdaySample) / $yesterdaySample) * 100;
            }
            $displaySample=__('general.chart_filter_today');
            $displaySampleResult = $todaySamples->count();
        }
        return response()->json([
            'growthSample' => number_format($growthSample, 2),
            'displaySample' => $displaySample,
            'displaySampleResult' => $displaySampleResult
        ]);
    }

    function filter_income(Request $q){
        $growthIncome = 0;
        if ($q->dt == 'this_month'){
                $monlthlyIncome= $this->getThisMonthIncome();
                $monlthlyIncome+=$this->getDailyReportV2(date('Y-m-01'), date('Y-m-t'));
                $last_monthIncome = $this->getPreviousMonthIncome();
                $last_monthIncome+=$this->getDailyReportV2(date("Y-m-d", mktime(0, 0, 0, date("m")-1, 1)), date("Y-m-d", mktime(0, 0, 0, date("m"), 0)));
                if($last_monthIncome>0){
                    $growthIncome = (($monlthlyIncome - $last_monthIncome) / $last_monthIncome) * 100;
                }
                $displayIncome=__('general.chart_filter_this_month');
                $displayIncomeResult = number_format($monlthlyIncome);

            } elseif ($q->dt == 'this_year'){
                $yearIncome = $this->getLastYearIncome();
                $yearIncome+=$this->getDailyReportV2(date("Y-m-d",strtotime("last year January 1st")), date("Y-m-d",strtotime("last year December 31st")));
                $last_yearIncome = $this->getLastYearIncome();
                $last_yearIncome+=$this->getDailyReportV2(date("Y-m-d",strtotime("-2 year January 1st")), date("Y-m-d",strtotime("-2 year December 31st")));
                if($last_yearIncome>0){
                    $growthIncome = (($yearIncome - $last_yearIncome) / $last_yearIncome) * 100;
                }
                $displayIncome=__('general.chart_filter_this_year');
                $displayIncomeResult = number_format($yearIncome);
            }
            else{
                    $todayIncome = $this->getTodayIncome();
                    $todayIncome+=$this->getDailyReportV2(date('Y-m-d'), date('Y-m-d'));
                    $yesterdayIncome = $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                        ->whereDate('invoice_date', date('Y-m-d', strtotime('-1 day')))->sum('gross_total');
                    $yesterdayIncome+=$this->getDailyReportV2(date('Y-m-d', strtotime('-1 day')), date('Y-m-d', strtotime('-1 day')));
                    if($yesterdayIncome>0){
                        $growthIncome = (($todayIncome - $yesterdayIncome) / $yesterdayIncome) * 100;
                    }
                    $displayIncome=__('general.chart_filter_today');
                    $displayIncomeResult = number_format($todayIncome);
            }
            return response()->json([
                'growthIncome' => number_format($growthIncome, 2),
                'displayIncome' => $displayIncome,
                'displayIncomeResult' => $displayIncomeResult
            ]);
    }

    function filter_patient(Request $q)
    {
        $growthPatient = 0;
        if ($q->dt == 'this_month'){
                $monthlyPatient= $this->getThisMonthPatient();
                $last_monthPatient = $this->getPreviousMonthPatient();
                if($last_monthPatient>0){
                    $growthPatient = (($monthlyPatient - $last_monthPatient) / $last_monthPatient) * 100;
                }
                $displayPatient=__('general.chart_filter_this_month');
                $displayPatientResult = $monthlyPatient;

            } elseif ($q->dt == 'this_year'){
                $yearPatient = $this->getThisYearPatient();
                $last_yearPatient = $this->getLastYearPatient();
                if($last_yearPatient>0){
                    $growthPatient = (($yearPatient - $last_yearPatient) / $last_yearPatient) * 100;
                }
                $displayPatient=__('general.chart_filter_this_year');
                $displayPatientResult = $yearPatient;
            }
            else{
                $todayPatient = $this->getTodayPatient();
                $yesterdayPatient = $this->getYesterdayPatient();
                if($yesterdayPatient>0){
                    $growthPatient = (($todayPatient - $yesterdayPatient) / $yesterdayPatient) * 100;
                }
                $displayPatient=__('general.chart_filter_today');
                $displayPatientResult = $todayPatient;
            }

            return response()->json([
                'growthPatient' => number_format($growthPatient, 2),
                'displayPatient' => $displayPatient,
                'displayPatientResult' => $displayPatientResult
            ]);
    }

    function filter_rejected_sample(Request $q)
    {
        $growthRejectedSample = 0;
        if ($q->dt == 'this_month'){
                $monthlyRejectedSample= $this->getThisMonthRejectedSamples()->count();
                $last_monthRejectedSample = $this->getPreviousMonthRejectedSamples()->count();
                if($last_monthRejectedSample>0){
                    $growthRejectedSample = (($monthlyRejectedSample - $last_monthRejectedSample) / $last_monthRejectedSample) * 100;
                }
                $displayRejectedSample=__('general.chart_filter_this_month');
                $displayRejectedSampleResult = $monthlyRejectedSample;

            } elseif ($q->dt == 'this_year'){
                $yearRejectedSample = $this->getThisYearRejectedSamples()->count();
                $last_yearRejectedSample = $this->getLastYearRejectedSamples()->count();
                if($last_yearRejectedSample>0){
                    $growthRejectedSample = (($yearRejectedSample - $last_yearRejectedSample) / $last_yearRejectedSample) * 100;
                }
                $displayRejectedSample=__('general.chart_filter_this_year');
                $displayRejectedSampleResult = $yearRejectedSample;
            }
            else{
                $todayRejectedSample = $this->getTodayRejectedSamples()->count();
                $yesterdayRejectedSample = $this->getYesterdayRejectedSamples()->count();
                if($yesterdayRejectedSample>0){
                    $growthRejectedSample = (($todayRejectedSample - $yesterdayRejectedSample) / $yesterdayRejectedSample) * 100;
                }
                $displayRejectedSample=__('general.chart_filter_today');
                $displayRejectedSampleResult = $todayRejectedSample;
            }
            return response()->json([
                'growthRejectedSample' => number_format($growthRejectedSample, 2),
                'displayRejectedSample' => $displayRejectedSample,
                'displayRejectedSampleResult' => $displayRejectedSampleResult
            ]);
    }

    //get total sample count for dashboard by lab id

    function getTotalRejectedSampleCount(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('sample_condition', 0)->count();
    }

    function getTodayRejectedSamples(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('sample_condition', 0)
                ->whereDate('admission_date', date('Y-m-d'))->get();
    }

    function getYesterdayRejectedSamples(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('sample_condition', 0)
                ->whereDate('admission_date', date('Y-m-d', strtotime('-1 day')))->get();
    }

    function getThisMonthRejectedSamples(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('sample_condition', 0)
            ->whereBetween('admission_date', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])->get();
    }

    function getPreviousMonthRejectedSamples(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('sample_condition', 0)
            ->whereBetween('admission_date', [date("Y-m-d 00:00:00", strtotime("first day of previous month")), date("Y-m-d 23:59:59", strtotime("last day of previous month"))])->get();
    }

    function getThisYearRejectedSamples(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('sample_condition', 0)
            ->whereYear('admission_date', date('Y'))->get();
    }

    function getLastYearRejectedSamples(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('sample_condition', 0)
            ->whereYear('admission_date', (date('Y')-1))->get();
    }





    function getTotalSampleCount(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->count();
    }

    //get yesterday sample count for dashboard by lab id

    function getYesterdaySampleCount(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                ->whereDate('admission_date', date('Y-m-d', strtotime('-1 day')))->count();
    }

    function getTodaySamples(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                ->whereDate('admission_date', date('Y-m-d'))->get();
    }

    function getThisMonthSamples(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('admission_date', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])->get();
    }

    function getPreviousMonthSamples(){
        return $this->sampleModel::with(['patient'])->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('admission_date', [date("Y-m-d 00:00:00", strtotime("first day of previous month")), date("Y-m-d 23:59:59", strtotime("last day of previous month"))])->get();
    }

    function getLastYearAverage(){
        return $this->sampleModel::with(['patient'])->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('admission_date', [date('Y-01-01 00:00:00', strtotime('-1 year')), date('Y-12-31 23:59:59', strtotime('-1 year'))])->count();
    }

    function getTodayIncome(){
        return $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereDate('invoice_date', date('Y-m-d'))->sum('gross_total');
    }

    function getThisMonthIncome(){
        return $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('invoice_date', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])->sum('gross_total');
    }

    function getPreviousMonthIncome(){
        return $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('invoice_date', [date("Y-m-d 00:00:00", strtotime("first day of previous month")), date("Y-m-d 23:59:59", strtotime("last day of previous month"))])->sum('gross_total');
    }

    function getLastYearIncome(){
        return $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('invoice_date', [date('Y-01-01 00:00:00', strtotime('-1 year')), date('Y-12-31 23:59:59', strtotime('-1 year'))])->sum('gross_total');
    }

    function getTotalIncome(){
        return $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->sum('gross_total');
    }

    function getTotalPatient(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->distinct('patient_id')->count('patient_id');
    }

    function getTodayPatient(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                ->whereDate('admission_date', date('Y-m-d'))->distinct('patient_id')->count('patient_id');
    }

    function getYesterdayPatient(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
                ->whereDate('admission_date', date('Y-m-d', strtotime('-1 day')))->distinct('patient_id')->count('patient_id');
    }

    function getThisMonthPatient(){
        return $this->sampleModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('admission_date', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])->distinct('patient_id')->count('patient_id');
    }

    function getPreviousMonthPatient(){
        return $this->sampleModel::with(['patient'])->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('admission_date', [date("Y-m-d 00:00:00", strtotime("first day of previous month")), date("Y-m-d 23:59:59", strtotime("last day of previous month"))])->distinct('patient_id')->count('patient_id');
    }

    function getLastYearPatient(){
        return $this->sampleModel::with(['patient'])->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('admission_date', [date('Y-01-01 00:00:00', strtotime('-1 year')), date('Y-12-31 23:59:59', strtotime('-1 year'))])->distinct('patient_id')->count('patient_id');
    }

    function getThisYearPatient(){
        return $this->sampleModel::with(['patient'])->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])
            ->whereBetween('admission_date', [date('Y-01-01 00:00:00'), date('Y-12-31 23:59:59')])->distinct('patient_id')->count('patient_id');
    }

    function getTotalInvoice(){
        return $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->count();
    }

    function getTotalPaidInvoice(){
        return $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('balance', 0)->count();
    }

    function getTotalUnpaidInvoice(){
        return $this->invoiceModel::query()->where(['lab_id' => $this->baseLabId, BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE])->where('balance', '>', 0)->count();
    }


    function getSampleSourceChart($period = 2){
        $samplePeriodCondition = " and s.lab_id = ".$this->baseLabId;
        if($period == 1) $samplePeriodCondition.= " and date(s.admission_date)='".date('Y-m-d')."'"; // today
        if($period == 2) $samplePeriodCondition.= " and s.admission_date BETWEEN '".date('Y-m-01 00:00:00')."' AND '".date('Y-m-t 23:59:59')."'"; // this month
        if($period == 3) $samplePeriodCondition.= " and s.admission_date BETWEEN '".date('Y-01-01 23:59:59')."' AND '".date('Y-12-31 23:59:59')."'"; // this year
        $sampleSourceData  = DB::select("
                                        SELECT
                                            ss.`name_en` as sample_source,
                                            ".$period." as period_type,
                                            ifnull(sample.total_samples, 0) as total_samples
                                        FROM `sample_sources` ss
                                        LEFT JOIN(
                                            SELECT
                                                s.`sample_source_id`,
                                                SUM(1) AS total_samples
                                            FROM samples s
                                            WHERE s.`record_status_id` = 1
                                            " . $samplePeriodCondition . "
                                            GROUP BY s.`sample_source_id`
                                        ) sample
                                        ON sample.sample_source_id = ss.`id`
                                        WHERE ss.`record_status_id` = 1
                                        AND ss.`lab_id` = ".$this->baseLabId."
        ");
        $sampleSourceDataArray = [];
        foreach ($sampleSourceData as $data){
            $sampleSourceDataArray['sample_source'][] = $data->sample_source;
            $sampleSourceDataArray['period_type'][] = ($data->period_type==1 ? date('d-m-Y') : ($data->period_type==3 ? date('Y') : date('M-Y')));
            $sampleSourceDataArray['total_samples'][] = $data->total_samples;
        }
        return $sampleSourceDataArray;
    }

    function getSampleByYearChart(){
        $yearSamples = $this->getAggregationSampleByYear((date('Y')-1), date('Y'));
        $yearData = array();
        for ($year = date('Y'); $year>=(date('Y')-1); $year--){
            for($month = 12; $month>0; $month--){
                $yearData[$year]['month'][$month] = date('M', strtotime($year.'-'. $month.'-01'));
                $yearData[$year]['data'][$month] = 0;
                $yearData[$year]['year'][$month] = $year;
            }
        }
        foreach ($yearSamples as $data){
            $yearData[$data->year_sample]['data'][$data->month_sample] = $data->total_samples;
        }
        return $yearData;
    }

    function getAggregationSampleByYear($fromYear, $toYear)
    {
        $sampleByYear = DB::select("SELECT
                    MONTH(s.`admission_date`) AS month_sample,
                    YEAR(s.`admission_date`) AS year_sample,
                    SUM(1) AS total_samples
                FROM samples s
                WHERE YEAR(s.`admission_date`) between ".$fromYear." and ".$toYear."
                AND s.`record_status_id` = 1
                AND s.`lab_id` = ".$this->baseLabId."
                GROUP BY MONTH(s.`admission_date`), YEAR(s.`admission_date`) ");
        return $sampleByYear;
    }


    public function getDailyReportV2($startDate, $endDate){
        try{
            $rawTestByPhysician = DB::select("
            select
            	r.repayment_date as `invoice_date`,
                    ss.`name_en` as sample_source,
            	    p.`name_en` AS patient,
            	    s.`sample_number`,
            	    '' as test_name,
            	   r.exchange_rate,
            	    ps.`name_en` AS physician_name,
            	   sum(r.cash_repayment_amount + r.bank_repayment_amount) AS total_amount,
            	   0 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
            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
            	order by sample_number asc
            ");

            //return $rawTestByPhysician;
            $total = collect($rawTestByPhysician)->sum('total_paid') + collect($rawTestByPhysician)->sum('total_bank_paid');
            return $total;
        } catch (\Exception $e){
            return [];
        }
    }

    public function samplesYearComparison()
    {
        $thisYear = now()->year;
        $lastYear = now()->subYear()->year;

        $current = DB::table('samples')
            ->selectRaw('MONTH(admission_date) as month, COUNT(*) as total')
            ->whereYear('admission_date', $thisYear)
            ->where('lab_id', $this->baseLabId)
            ->groupBy('month')
            ->pluck('total', 'month');

        $previous = DB::table('samples')
            ->selectRaw('MONTH(admission_date) as month, COUNT(*) as total')
            ->whereYear('admission_date', $lastYear)
            ->where('lab_id', $this->baseLabId)
            ->groupBy('month')
            ->pluck('total', 'month');

        $trend = [];

        for ($m = 1; $m <= 12; $m++) {
            $trend[] = [
                'month' => date('M', mktime(0, 0, 0, $m, 1)),
                'this_year' => $current[$m] ?? 0,
                'last_year' => $previous[$m] ?? 0,
            ];
        }

        return response()->json($trend);
    }

    public function revenueYearComparison()
    {
        $thisYear = now()->year;
        $lastYear = now()->subYear()->year;

        $current = DB::table('invoices')
            ->selectRaw('MONTH(invoice_date) as month, SUM(gross_total) as total')
            ->whereYear('invoice_date', $thisYear)
            ->where('lab_id', $this->baseLabId)
            ->groupBy('month')
            ->pluck('total', 'month');

        $previous = DB::table('invoices')
            ->selectRaw('MONTH(invoice_date) as month, SUM(gross_total) as total')
            ->whereYear('invoice_date', $lastYear)
            ->where('lab_id', $this->baseLabId)
            ->groupBy('month')
            ->pluck('total', 'month');

        $trend = [];

        for ($m = 1; $m <= 12; $m++) {
            $trend[] = [
                'month' => date('M', mktime(0, 0, 0, $m, 1)),
                'this_year' => $current[$m] ?? 0,
                'last_year' => $previous[$m] ?? 0,
            ];
        }

        return response()->json($trend);
    }

    function getSampleSourceByDistributor(){
        $thisYear = now()->year;
        $sampleSourceData  = DB::select("
            SELECT
                ss.`name_en` as sample_source,
                ifnull(sample.total_samples, 0) as total_samples
            FROM `sample_sources` ss
            LEFT JOIN(
                SELECT
                    s.`sample_source_id`,
                    SUM(1) AS total_samples
                FROM samples s
                WHERE s.`record_status_id` = 1
                and year(s.admission_date) = ".$thisYear."
                AND s.lab_id = ".$this->baseLabId."
                GROUP BY s.`sample_source_id`

            ) sample
            ON sample.sample_source_id = ss.`id`
            WHERE ss.`record_status_id` = 1
            AND ss.`lab_id` = ".$this->baseLabId."
            ORDER BY total_samples DESC
            LIMIT 10
        ");
        return response()->json($sampleSourceData);
    }

    function getPanelDistributor(){
        $thisYear = now()->year;
        $samplePanelData  = DB::select("SELECT
                        d.`name_en` AS panel,
                        IFNULL(sample.total_samples, 0) AS total_samples
                        FROM `departments` d
                        LEFT JOIN(
                        SELECT
                            st.department_id,
                            SUM(1) AS total_samples
                        FROM samples s
                        INNER JOIN test_results tr ON tr.`sample_id` = s.`id` AND tr.`record_status_id`= 1
                        INNER JOIN test_samples ts ON ts.id = tr.`test_sample_id`
                        INNER JOIN sample_types st ON st.id = ts.`sample_type_id`
                        INNER JOIN departments sd ON sd.id = st.`department_id`
                        WHERE s.`record_status_id` = 1
                        and year(s.admission_date) = ".$thisYear."
                        AND s.lab_id = ".$this->baseLabId."
                        GROUP BY st.`department_id`

                        ) sample
                        ON sample.department_id = d.`id`
                        WHERE d.`record_status_id` = 1
                        AND d.`lab_id` = ".$this->baseLabId."
                        ORDER BY d.`name_en`
        ");
        return response()->json($samplePanelData);
    }

}
