<?php

namespace App\Http\Controllers\IncentiveSlab;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\SaleInvoiceDetail;
use App\Models\IncentiveSlabDetail;
use App\Models\Account;

class DrCommissionsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function generate(Request $request, $id = '')
    {
        if ($request->ajax()) {
	        $data = SaleInvoiceDetail::select([
	            'sale_invoice_details.id',
	            'sale_invoice_details.basic_amount',
	            'sale_invoice_details.product_id',
	            'sale_invoice_details.created_at',
	            'sale_invoices.main_invoice_no',
	            'products.name as product',
	            'accounts.name as doctor',
	            'accounts.code as doctor_code',
	            'incentive_settings.date_upto',
	            'incentive_slabs.slab_name',
	            'patient.name as patient_name',
	            'patient.code as patient_code',
	            'product_brands.name as brand',
	            'sale_others_transactions.price as discount_amount',
	        ])
	        	->leftjoin('sale_invoice_batches','sale_invoice_details.sale_invoice_id', '=', 'sale_invoice_batches.invoice_id')
	        	->leftjoin('accounts','sale_invoice_batches.consultant_id', '=', 'accounts.id')
	        	->leftjoin('sale_invoices','sale_invoice_details.sale_invoice_id', '=', 'sale_invoices.id')
	        	->leftjoin('incentive_settings','incentive_settings.account_id', '=', 'accounts.id')
	        	->leftjoin('products','sale_invoice_details.product_id', '=', 'products.id')
	        	->leftjoin('product_brands','product_brands.id', '=', 'products.brand_id')
	        	->leftjoin('incentive_slabs','incentive_slabs.id', '=', 'incentive_settings.slab_id')
	        	->leftjoin('accounts as patient','sale_invoices.patient_id', '=', 'patient.id')
	        	->leftjoin('sale_others_transactions', function($join) {
	        		$join->on('sale_others_transactions.sale_invoice_batch_id', '=', 'sale_invoice_batches.id')
	        			->where('transaction_type', 'DEBIT');
	        	})
	        	->when(!empty($id), function($query) use ($id) {
	        		$query->where('sale_invoice_batches.consultant_id', $id);
	        	});

			$sort_by      = $request->get('sortby') ?? 10;
			$sort_type    = $request->get('sorttype');
			$search_query = $request->get('query');
			$start_date   = $request->get('start_date');
			$end_date     = $request->get('end_date');
			$doctor       = $request->get('doctor');
			$collection   = $request->get('collection') == '1' ? '1' : '0';

            $data = $data->where('sale_invoice_batches.incentive', $collection)
	        	->when(!empty($doctor), function($query) use ($doctor) {
	        		$query->where('sale_invoice_batches.consultant_id', $doctor);
	        	})
	        	->when(!empty($search_query), function($query) use ($search_query) {
            		$query->where('accounts.name', 'LIKE', '%' . $search_query . '%')
            			->orWhere('patient.name', 'LIKE', '%' . $search_query . '%')
            			->orWhere('sale_invoices.main_invoice_no', 'LIKE', '%' . $search_query . '%')
            			->orWhere('product_brands.name', 'LIKE', '%' . $search_query . '%')
            			->orWhere('products.name', 'LIKE', '%' . $search_query . '%');
	            })
	            ->when(!empty($start_date) && empty($end_date), function($query) use ($start_date) {
	            	$query->whereDate('sale_invoice_details.created_at', '>', date('Y-m-d', strtotime($start_date)));
	            })
	            ->when(empty($start_date) && !empty($end_date), function($query) use ($end_date) {
	            	$query->whereDate('sale_invoice_details.created_at', '<', date('Y-m-d', strtotime($end_date)));
	            })
	            ->when(!empty($start_date) && !empty($end_date), function($query) use ($start_date, $end_date) {
	            	$query->whereBetween('sale_invoice_details.created_at', [
	            		date('Y-m-d', strtotime($start_date)),
	            		date('Y-m-d', strtotime($end_date))
	            	]);
	            })
	            ->groupBy('products.id')
                ->whereNotNull('products.id')
            	->get()
	            ->map(function ($saleInvoiceDetails, $productId) {
	            	$productId = $saleInvoiceDetails->product_id ?? '';
	            	$id = $saleInvoiceDetails->id ?? '';

	                $details = IncentiveSlabDetail::select([
				            'calculation_type',
				            'percentage',
				            'price',
		                ])
		                ->where(['product_id' => $productId, 'slab_id' => $id])->first();

	                return [
						'incentive_slab_details' => $details,
						'sale_invoice_details'   => $saleInvoiceDetails
	                ];
	            });

            return view('incentive-dr-commission.table', compact('data', 'id'));
        }
        else
        {
			$data   = [];
			$doctor = Account::select([
	                'accounts.id',
	                'accounts.name',
	                'accounts.code'
	            ])
            	->leftjoin('account_types', 'account_types.id', 'accounts.account_type_id')
				->where('account_types.type_code', 'DOCTOR')
	        	->get();

            return view('incentive-dr-commission.index', compact('data', 'id', 'doctor'));
        }
    }
}
