<?php

namespace App\Http\Controllers\LabBilling;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TestDeptPermission;
use App\Models\SaleInvoice;
use App\Models\SaleInvoiceSubDetails;
use App\Models\SaleInvoiceTaskTracking;
use App\Models\TaskStatus;
use App\Models\StyleType;
use App\Models\TestPackage;
use App\Models\Department;
use App\Models\SaleInvoiceDetail;
use App\Models\LabBillingReport;
use App\Models\TestItem;
use App\Models\LabReportResultBigText;
use App\Models\TestItemOption;
use Illuminate\Support\Collection;
use Illuminate\Pagination\Paginator;

class LabBillingReportsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function dashboard(Request $request)
    {
        if ($request->ajax()) {
            $filter['start_date']  = $request->start_date != '' ? date('Y-m-d', strtotime($request->start_date)) : '';
            $filter['end_date']    = $request->end_date != '' ? date('Y-m-d', strtotime($request->end_date)) : '';
            $filter['hide_status'] = true;

            $data = SaleInvoice::getSaleInvoices([], $filter)->get();
            $response['total_reports']   = $data->count();
            $response['doneReports']     = $data->where('all_tests_reviewed', '=', 1)->count();
            $response['sampleCollected'] = $data->where('sample_collection_status', '=', 1)->count();
            $response['updatedReports']  = $data->where('all_tests_updated', '1')->where('all_tests_recheck', '0')->count();

            return response()->json($response);
        } else {
            $filter['hide_status'] = true;
            $data            = SaleInvoice::getSaleInvoices([],$filter)->get();
            $total_reports   = $data->count();
            $doneReports     = $data->where('all_tests_reviewed', '=', 1)->count();
            $sampleCollected = $data->where('sample_collection_status', '=', 1)->count();
            $updatedReports  = $data->where('all_tests_updated', '1')->where('all_tests_recheck', '0')->count();

            return view('lab-reporting.dashboard', compact(
                'total_reports',
                'doneReports',
                'sampleCollected',
                'updatedReports'
            ));
        }
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function labReporting(Request $request)
    {
        $data =  SaleInvoice::select([
            'sale_invoices.id',
            'sale_invoices.main_invoice_no',
            'sale_invoices.voucher_type_invoice_no',
            'sale_invoice_batches.invoice_batch_no',
            'sale_invoice_batches.id as batch_id',
            'sale_invoice_batches.invoice_batch_date',
            'sale_invoices.invoice_date',
            'sale_invoices.patient_id',
            'sale_invoices.created_at',
            'accounts.name AS patent_name',
            'account_contacts.date_of_birth',
            'genders.name as gender',
            'account_titles.name as account_title',
            'voucher_types.name as voucher_type',
        ])
            ->leftjoin('accounts','accounts.id','sale_invoices.patient_id')
            ->leftjoin('account_contacts','accounts.id','account_contacts.account_id')
            ->leftjoin('genders','genders.id','account_contacts.account_gender_id')
            ->leftjoin('account_titles','account_titles.id','accounts.account_title_id')
            ->leftjoin('sale_invoice_details', 'sale_invoice_details.sale_invoice_id','sale_invoices.id')
            ->leftjoin('sale_invoice_sub_details','sale_invoice_sub_details.sale_invoice_detail_id','sale_invoice_sub_details.id')
            ->leftjoin('sale_invoice_batches', 'sale_invoice_batches.id', 'sale_invoice_details.batch_id')
            ->leftjoin('voucher_types','voucher_types.code','sale_invoices.voucher_type_code')
            ->whereNull('sale_invoices.deleted_at')
            ->whereIn('sale_invoices.voucher_type_code', ['IPD_ADMISSION', 'PATHOLOGY'])
            ->when(!in_array('Admin',\Auth()->user()->roles->pluck('name')->all()), function($query) {
                $query->where('sale_invoices.operator_id', \Auth()->id())
                    ->where('sale_invoices.company_id', \Auth()->user()->company_id);
            })
            ->when(in_array('Admin',\Auth()->user()->roles->pluck('name')->all()), function($query) {
                $query->where('sale_invoices.company_id', \Auth()->user()->company_id);
            });

            $data = $data->latest()->groupBy('sale_invoices.id')->groupBy('sale_invoice_batches.id');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');

            $filter['search_query']  = $request->get('query');
            $filter['search_type']   = $request->get('search_type');

            $data = $data->when(!empty($filter['search_query']) && !empty($filter['search_type']), function ($query) use ($filter) {
                    if ($filter['search_type'] == 'invoice_no') {
                        $query->where('voucher_type_invoice_no', 'LIKE', '%'.$filter['search_query'] .'%');
                    } else if ($filter['search_type'] == 'pat_name') {
                        $query->where('accounts.name', 'LIKE', '%'.$filter['search_query'] .'%');
                    } else if ($filter['search_type'] == 'phone') {
                        $query->where('account_contacts.phone_no', 'LIKE', '%'.$filter['search_query'] .'%');
                    } else if ($filter['search_type'] == 'abha_no') {
                        $query->where('accounts.unique_register_no', 'LIKE', '%'.$filter['search_query'] .'%');
                    } else if ($filter['search_type'] == 'test') {
                        $query->where('test_packages.name', 'LIKE', '%'.$filter['search_query'] .'%');
                    } else if ($filter['search_type'] == 'department') {
                        $query->where('test_departments.name', 'LIKE', '%'.$filter['search_query'] .'%');
                    } else if ($filter['search_type'] == 'batch_no') {
                        $query->where('sale_invoice_batches.invoice_batch_no', 'LIKE', '%'.$filter['search_query'] .'%');
                    }
                })
                ->paginate($sort_by);

            return view('lab-reporting.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());

            return view('lab-reporting.index',compact('data','companyDateFormate'));
        }
    }

    public function sampleCollection(Request $request)
    {
        if ($request->ajax()) {
            $perPage                     = $request->get('sortby') ?? 20;
            $sort_type                   = $request->get('sorttype');
            $filter['from_date']         = date('Y-m-d', strtotime($request->get('from_date')));
            $filter['search_query']      = $request->get('query');
            $filter['search_type']       = $request->get('search_type');
            $filter['sample_collection'] = $request->get('status') == 'all' ? '' : $request->get('status');
            \Session::put('report_date', $filter['from_date']);

            $saleInvoices = SaleInvoice::getSaleInvoices([], $filter)->paginate($perPage);

            return view('lab-reporting.sample-collections.table', compact('saleInvoices'));
        } else {
            $filter['sample_collection'] = 'pending';
            $filter['from_date']         = $from_date = \Session::get('report_date') ?? date('Y-m-d');

            $companyDateFormate          = phpToJsDateFormat($this->companyDateFormate());
            $saleInvoices                = SaleInvoice::getSaleInvoices([], $filter)->paginate(20);

            $from_date = date($this->companyDateFormate(), strtotime($from_date));

            return view('lab-reporting.sample-collections.index',compact('saleInvoices','companyDateFormate','from_date'));
        }
    }

    public function sampleCollectionStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array(
                'sample_collection_status' => $request->status,
                'sample_collection_datetime' => date('Y-m-d H:i:s')
            );
            $batch = $request->batch;
            $department = $request->department;

            $sub_details = SaleInvoiceSubDetails::select('sale_invoice_sub_details.id')->where('sale_invoice_sub_details.sale_invoice_id', '=', $request->id)
                ->join('sale_invoice_details', 'sale_invoice_details.id','sale_invoice_sub_details.sale_invoice_detail_id')
                /*->where(function ($query) use ($department) {
                    $query->whereHas('getTestPackage', function ($accounting_group) use ($department) {
                        $accounting_group->where('department_id', $department);
                    });
                })*/
                ->when(!empty($batch), function($query) use ($batch) {
                    $query->where('sale_invoice_details.batch_id', $batch);
                })
                ->get()->pluck('id');

            if ($request->status == 1) {
                $task_status = TaskStatus::where('code', 'SAMPLE_COLLECTED')->first();

                foreach($sub_details as $value) {
                    SaleInvoiceSubDetails::where('id', $value)->update(['task_status_id' => ($task_status->id ?? '')]);
                    $Update = SaleInvoiceTaskTracking::firstOrCreate([
                        'user_id'                     => \Auth()->id(),
                        'tracking_type'               => 'SAMPLE_COLLECTED',
                        'sale_invoice_sub_details_id' => $value
                    ]);
                }
            } else {
                $task_status = TaskStatus::where('code', 'PENDING')->first();

                foreach($sub_details as $value) {
                    SaleInvoiceSubDetails::where('id', $value)->update(['task_status_id' => ($task_status->id ?? '')]);
                }

                $Update = SaleInvoiceTaskTracking::whereIn('sale_invoice_sub_details_id', $sub_details)
                    ->where([
                        'tracking_type' => 'SAMPLE_COLLECTED',
                    ])->delete();
            }

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Sample Collection status successfully updated'],
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                ]);
            }
        }
    }

    public function resultUpdate(Request $request)
    {
        $batch_id = $request->batch_id ?? '';
        $roles = \Auth::user()->roles->pluck('id')->all();
        $filter['auth_roles'] = \Auth::id();

        if ($request->ajax()) {
            $perPage                     = $request->get('sortby') ?? 20;
            $sort_type                   = $request->get('sorttype');
            $filter['from_date']         = date('Y-m-d', strtotime($request->get('from_date')));
            $filter['search_query']      = $request->get('query');
            $filter['search_type']       = $request->get('search_type');
            $filter['result_update']     = $request->get('type') == 'all' ? '' : $request->get('type');
            $filter['sample_collection'] = 'collected';
            $filter['batch_id']          = $batch_id;
            \Session::put('report_date', $filter['from_date']);

            $saleInvoices = SaleInvoice::getSaleInvoices([], $filter, 1)->paginate($perPage);

            return view('lab-reporting.result-update.table', compact('saleInvoices'));
        } else {
            $filter['result_update']     = 'pending';
            $filter['sample_collection'] = 'collected';
            $filter['from_date']         = $from_date = \Session::get('report_date') ?? date('Y-m-d');
            $filter['batch_id']          = $batch_id;
            $saleInvoices                = SaleInvoice::getSaleInvoices([], $filter, 1)->paginate(20);
            $companyDateFormate          = phpToJsDateFormat($this->companyDateFormate());
            $from_date                   = date($this->companyDateFormate(), strtotime($from_date));

            return view('lab-reporting.result-update.index', compact('saleInvoices','companyDateFormate','from_date'));
        }
    }

    public function doctorReview(Request $request)
    {
        $roles = \Auth::user()->roles->pluck('id')->all();
        $filter['auth_roles'] = \Auth::id();
        $batch_id = $request->batch_id ?? '';

        if ($request->ajax()) {
            $perPage                     = $request->get('sortby') ?? 20;
            $page                        = $request->get('page') ?? 1;
            $sort_type                   = $request->get('sorttype');
            $filter['search_query']      = $request->get('query');
            $filter['search_type']       = $request->get('search_type');
            $filter['doctor_review']     = $request->get('type') == 'all' ? '' : $request->get('type');
            $filter['from_date']         = date('Y-m-d', strtotime($request->get('from_date')));
            $filter['recheck']           = 'done';
            $filter['sample_collection'] = 'collected';
            $filter['result_update']     = 'done';
            $filter['batch_id']          = $batch_id;
            \Session::put('report_date', $filter['from_date']);

            $saleInvoices = SaleInvoice::getSaleInvoices([], $filter, 1)->paginate(20);

            return view('lab-reporting.doctor-reviews.table', compact('saleInvoices'));
        }
        else
        {
            $filter['result_update']     = 'done';
            $filter['doctor_review']     = 'pending';
            $filter['recheck']           = 'done';
            $filter['sample_collection'] = 'collected';
            $filter['batch_id']          = $batch_id;
            $filter['from_date']         = $from_date = \Session::get('report_date') ?? date('Y-m-d');

            $saleInvoices       = SaleInvoice::getSaleInvoices([], $filter, 1)->paginate(20);
            $companyDateFormate = phpToJsDateFormat($this->companyDateFormate());
            $from_date          = date($this->companyDateFormate(), strtotime($from_date));

            return view('lab-reporting.doctor-reviews.index', compact('saleInvoices','companyDateFormate','from_date'));
        }
    }

    public function review(Request $request, $invoice_id, $test_package = '')
    {
        /*\DB::table('lab_billing_reports as lbr')
        ->join('sale_invoice_sub_details as ssd', function ($join) {
            $join->on('lbr.sale_invoice_id', '=', 'ssd.sale_invoice_id')
                 ->on('lbr.test_package_id', '=', 'ssd.data_referrence_id');
        })
        ->whereNull('lbr.sale_invoice_detail_id')
        ->update([
            'lbr.sale_invoice_detail_id' => \DB::raw('ssd.sale_invoice_detail_id')
        ]);*/

        $batch_id = $request->batch_id ?? '';

        $style = StyleType::all();
        $sale_invoice = SaleInvoice::select([
                'sale_invoices.id',
                'sale_invoices.main_invoice_no',
                'sale_invoices.invoice_date',
                'sale_invoices.patient_id',
                'sale_invoices.created_at',
                'sale_invoice_batches.remarks_for_technician',
                'special_cases.name as special_case',
                'accounts.name AS patent_name',
                'account_contacts.date_of_birth',
                'account_contacts.account_gender_id',
                'account_contacts.phone_no',
                'genders.name as gender',
                'account_titles.name as account_title',
                'account_addresses.address_line1',
                'states.name as state'
            ])
            ->leftjoin('accounts','accounts.id','sale_invoices.patient_id')
            ->leftjoin('sale_invoice_batches','sale_invoice_batches.invoice_id','sale_invoices.id')
            ->leftjoin('special_cases','special_cases.id','sale_invoices.special_case_id')
            ->leftjoin('account_contacts','accounts.id','account_contacts.account_id')
            ->leftjoin('genders','genders.id','account_contacts.account_gender_id')
            ->leftjoin('account_titles','account_titles.id','accounts.account_title_id')
            ->leftjoin('account_addresses','account_addresses.account_id','accounts.id')
            ->leftjoin('states','account_addresses.state_id','states.id')
            ->where(function($where) {
                $where->where('sale_invoices.voucher_type_code', 'IPD_ADMISSION')
                    ->orWhere('sale_invoices.voucher_type_code', 'PATHOLOGY');
            })
            ->find($invoice_id);

        if (!$sale_invoice) {
            return redirect()->route('lab-billings.index')->with('error', 'Invoice not found');
        }
        $productIds = SaleInvoiceDetail::select('product_id')->where('sale_invoice_id',$invoice_id)->get()->pluck('product_id');

        $testPackages = TestPackage::select('test_packages.*','sale_invoice_sub_details.id as sale_invoice_sub_detail_id','sale_invoice_details.batch_id','sale_invoice_details.id as sale_invoice_detail_id')
            ->whereIn('product_test_packages.product_id', $productIds)
            ->leftjoin('product_test_packages','product_test_packages.test_package_id','test_packages.id')
            ->leftjoin('sale_invoice_sub_details','test_packages.id','sale_invoice_sub_details.data_referrence_id')
            ->leftjoin('sale_invoice_details','sale_invoice_sub_details.sale_invoice_detail_id','sale_invoice_details.id')
            ->with('department', 'testPackageGroups.test_package_group_test_items')
            ->where('sale_invoice_details.sale_invoice_id', $invoice_id)
            ->when(!empty($batch_id), function($query) use ($batch_id) {
                $query->where('sale_invoice_details.batch_id', $batch_id);
            })
            // ->where('test_packages.id', $test_package)
            ->groupBy('test_packages.id','sale_invoice_details.batch_id')
            ->get()
            ->groupBy(function ($testPackage) {
                return $testPackage->department->id;
            })
            ->map(function ($testPackages, $departmentId) {
                $departmentName = Department::find($departmentId)->name;

                return [
                    'department_name' => $departmentName,
                    'test_packages' => $testPackages,
                ];
            });

        $billing_report = LabBillingReport::select([
                'lab_billing_reports.*',
                'lab_report_result_big_texts.result as long_result'
            ])
            ->leftjoin('lab_report_result_big_texts', 'lab_report_result_big_texts.lab_billing_report_id','lab_billing_reports.id')
            ->where(['lab_billing_reports.sale_invoice_id' => $invoice_id])
            ->get()
            ->mapWithKeys(function($item) {
                return [$item->test_item_id . '_' . $item->sale_invoice_detail_id => $item];
            });

        return view('lab-reporting.doctor-reviews.review', compact(
            'sale_invoice',
            'billing_report',
            'testPackages',
            'style',
            'test_package'
        ));
    }

    public function reviewReportStore(Request $request, $invoice_id)
    {
        if ($request->submit_type == 'ready_to_print') {
            $sale_invoice = SaleInvoice::find($invoice_id);

            if (!$sale_invoice) {
                return redirect()->route('lab-billings.index')->with('error', 'Invoice not found');
            }

            $sale_invoice_detail     = $request->test_results ?? [];
            $test_flags       = $request->test_flags ?? [];
            $select_test_flat = $request->select_test_flag ?? [];
            $task_status = TaskStatus::where('code', 'RESULT_REVIEWED')->first();

            foreach ($sale_invoice_detail as $sale_invoice_detail_id => $test_results) {
                foreach($test_results as $test_package_id => $test_package) {

                    foreach($test_package as $test_package_group_id => $test_package_group) {
                        $created = 1;

                        foreach($test_package_group as $key => $value) {
                            $result = $value;
                            $is_file = 0;

                            if (!is_string($value) && is_file($value)) {
                                $ext = $value->getClientOriginalExtension() ?? '';
                                $allowed_ext = [
                                    'pdf',
                                    'jpeg',
                                    'jpg',
                                    'png'
                                ];

                                if (in_array($ext, $allowed_ext)) {
                                    $path     = "lab-test-result";
                                    $response = uploadImage($path,$value);

                                    if ($response['status'] == true) {
                                        $result = $response['file_name'];
                                        $is_file = 1;
                                    } else {
                                        $result = '';
                                    }
                                }
                            }
                            $test_item = TestItem::find($key);
                            $test_item_type = $test_item->input_type ?? '';

                            $billing_report = LabBillingReport::where([
                                'sale_invoice_detail_id' => $sale_invoice_detail_id,
                                'sale_invoice_id'       => $invoice_id,
                                'test_package_id'       => $test_package_id,
                                'test_package_group_id' => $test_package_group_id,
                                'test_item_id'          => $key,
                            ])->first();

                            if (!$billing_report && $result != '') {
                                $testPackage = SaleInvoiceSubDetails::where([
                                    'sale_invoice_detail_id' => $sale_invoice_detail_id,
                                    'sale_invoice_id'        => $invoice_id,
                                    'data_referrence_id'     => $test_package_id,
                                ])->first();

                                if ($testPackage) {
                                    $testPackage->update([
                                            'task_created_by_id' => \Auth::ID(),
                                            'task_created_at'    => date('Y-m-d H:i:s'),
                                            'task_status_id'     => $task_status->id ?? '',
                                    ]);
                                    $created = 0;
                                } else {
                                    $testPackage = SaleInvoiceSubDetails::create([
                                        'sale_invoice_detail_id' => $sale_invoice_detail_id,
                                        'sale_invoice_id'        => $invoice_id,
                                        'data_referrence_id'     => $test_package_id,
                                        'subdetails_remarks'     => '',
                                        'referrence_type'        => 'LAB',
                                        'status'                 => 'SAMPLE_COLLECTION',
                                        'task_created_by_id' => \Auth::ID(),
                                        'task_created_at'    => date('Y-m-d H:i:s'),
                                        'task_status_id'     => $task_status->id ?? '',
                                    ]);
                                    $created = 1;
                                }

                                $flags_exist = $select_test_flat[$test_package_id][$test_package_group_id][$key] ?? '0';
                                $flat_check = '';

                                if ($flags_exist == 1)
                                {
                                    $test_flag_selected =  TestItemOption::select('*')->with('styleType')->where('code',$result)->first();
                                    $flat_check = $test_flag_selected->styleType->code;

                                }

                                $billing_report = LabBillingReport::Create([
                                    'sale_invoice_detail_id' => $sale_invoice_detail_id,
                                    'sale_invoice_id'       => $invoice_id,
                                    'test_package_id'       => $test_package_id,
                                    'test_package_group_id' => $test_package_group_id,
                                    'test_item_id'          => $key,
                                    'is_file'               => $is_file,
                                    'result'                => ($test_item_type == 'SUMMER_NOTE' ? '' : $result),
                                    'flag'                  => $test_flags[$test_package_id][$test_package_group_id][$key] ?? $flat_check,
                                ]);

                                if ($test_item_type == 'SUMMER_NOTE') {
                                    LabReportResultBigText::create([
                                        'result'                => $result,
                                        'lab_billing_report_id' => $billing_report->id
                                    ]);
                                }

                                SaleInvoiceTaskTracking::firstOrCreate([
                                    'user_id'                     => \Auth::ID(),
                                    'tracking_type'               => 'RESULT_REVIEWED',
                                    'sale_invoice_sub_details_id' => $testPackage->id,
                                ]);
                                SaleInvoiceTaskTracking::where([
                                    'tracking_type'               => 'RESULT_RECHECK',
                                    'sale_invoice_sub_details_id' => $testPackage->id,
                                ])->delete();

                            } else if ((isset($billing_report)/* && $billing_report->result != $result*/)) {
                                $testPackage = SaleInvoiceSubDetails::where([
                                    'sale_invoice_detail_id' => $sale_invoice_detail_id,
                                    'sale_invoice_id'        => $invoice_id,
                                    'data_referrence_id'     => $test_package_id,
                                ])->first();

                                if ($testPackage) {
                                    $testPackage->update([
                                        'task_created_by_id' => \Auth::ID(),
                                        'task_created_at'    => date('Y-m-d H:i:s'),
                                        'task_status_id'     => $task_status->id ?? '',
                                    ]);
                                    $created = 0;
                                } else {
                                    $testPackage = SaleInvoiceSubDetails::create([
                                        'sale_invoice_detail_id' => $sale_invoice_detail_id,
                                        'sale_invoice_id'        => $invoice_id,
                                        'data_referrence_id'     => $test_package_id,
                                        'subdetails_remarks'     => '',
                                        'referrence_type'        => 'LAB',
                                        'status'                 => 'SAMPLE_COLLECTION',
                                        'task_created_by_id' => \Auth::ID(),
                                        'task_created_at'    => date('Y-m-d H:i:s'),
                                        'task_status_id'     => $task_status->id ?? '',
                                    ]);
                                    $created = 1;
                                }

                                $flags_exist = $select_test_flat[$test_package_id][$test_package_group_id][$key] ?? '0';
                                $flat_check = '';

                                if($flags_exist  == 1) {
                                    $test_flag_selected =  TestItemOption::select('style_type_id')->with('styleType')->where('code',$result)->first();
                                    $flat_check= $test_flag_selected->styleType->code ?? '';
                                }

                                if ($test_item_type == 'SUMMER_NOTE') {
                                    LabReportResultBigText::updateOrCreate([
                                        'lab_billing_report_id' => $billing_report->id
                                    ],[
                                        'result' => $result
                                    ]);
                                }

                                $billing_report = LabBillingReport::where([
                                    'sale_invoice_detail_id' => $sale_invoice_detail_id,
                                    'sale_invoice_id'       => $invoice_id,
                                    'test_package_id'       => $test_package_id,
                                    'test_package_group_id' => $test_package_group_id,
                                    'test_item_id'          => $key,
                                ])->update([
                                    'result'  => ($test_item_type == 'SUMMER_NOTE' ? '' : $result),
                                    'is_file' => $is_file,
                                    'flag'    => $test_flags[$test_package_id][$test_package_group_id][$key] ?? $flat_check,
                                ]);

                                SaleInvoiceTaskTracking::firstOrCreate([
                                    'user_id'                     => \Auth::ID(),
                                    'tracking_type'               => 'RESULT_REVIEWED',
                                    'sale_invoice_sub_details_id' => $testPackage->id,
                                ]);
                                SaleInvoiceTaskTracking::where([
                                    'tracking_type'               => 'RESULT_RECHECK',
                                    'sale_invoice_sub_details_id' => $testPackage->id,
                                ])->delete();
                            }
                        }
                    }
                }
            }
        } else if ($request->submit_type == 'recheck') {
            $sale_invoice = SaleInvoice::find($invoice_id);

            if (!$sale_invoice) {
                return redirect()->route('lab-billings.index')->with('error', 'Invoice not found');
            }

            $sale_invoice_detail     = $request->test_results ?? [];
            $test_flags       = $request->test_flags ?? [];
            $select_test_flat = $request->select_test_flag ?? [];
            $task_status      = TaskStatus::where('code', 'RESULT_RECHECK')->first();

            foreach ($sale_invoice_detail as $sale_invoice_detail_id => $test_results) {
                foreach($test_results as $test_package_id => $test_package) {

                    foreach($test_package as $test_package_group_id => $test_package_group) {
                        $created = 1;

                        foreach($test_package_group as $key => $value) {
                            $result = $value;
                            $is_file = 0;

                            $testPackage = SaleInvoiceSubDetails::where([
                                'sale_invoice_detail_id' => $sale_invoice_detail_id,
                                'sale_invoice_id'        => $invoice_id,
                                'data_referrence_id'     => $test_package_id,
                            ])->first();

                            if ($testPackage) {
                                SaleInvoiceTaskTracking::updateOrCreate([
                                    'tracking_type'               => 'RESULT_RECHECK',
                                    'sale_invoice_sub_details_id' => $testPackage->id,
                                ], [
                                    'user_id' => \Auth::ID(),
                                    'remarks' => $request->review
                                ]);
                                SaleInvoiceTaskTracking::where([
                                    'tracking_type'               => 'RESULT_REVIEWED',
                                    'sale_invoice_sub_details_id' => $testPackage->id,
                                ])->delete();
                            }
                        }
                    }
                }
            }
        }

        return redirect()->route('doctor-reviews')->with('success', 'Report updated successfully.');
    }

    public function reportReupdate($invoice_id, $test_package = '')
    {
        $sale_invoices = SaleInvoiceSubDetails::where([
                'sale_invoice_id'    => $invoice_id,
                // 'data_referrence_id' => $test_package
            ])
            ->select('id')
            ->get()
            ->pluck('id');

        $Update = SaleInvoiceTaskTracking::whereIn('sale_invoice_sub_details_id', $sale_invoices)
            ->where([
                'tracking_type' => 'RESULT_UPDATED',
            ])
            ->delete();

        $task_status = TaskStatus::where('code', 'SAMPLE_COLLECTED')->first();

        $sale_invoices = SaleInvoiceSubDetails::where([
                'sale_invoice_id'    => $invoice_id,
                // 'data_referrence_id' => $test_package
            ])->update([
                'task_status_id' => ($task_status->id ?? '')
            ]);

        return response()->json([
            'success'=> true,
            'message'=> 'Report status successfully updated.',
        ]);
    }

    public function oldLabReport()
    {
        \DB::table('lab_billing_reports as lbr')
        ->join('sale_invoice_sub_details as ssd', function ($join) {
            $join->on('lbr.sale_invoice_id', '=', 'ssd.sale_invoice_id')
                 ->on('lbr.test_package_id', '=', 'ssd.data_referrence_id');
        })
        ->whereNull('lbr.sale_invoice_detail_id')
        ->update([
            'lbr.sale_invoice_detail_id' => \DB::raw('ssd.sale_invoice_detail_id')
        ]);
        echo '<pre>';
        print_r('Done');
        echo '</pre>';
        die();
    }
}
