VaKeR CYBER ARMY
Logo of a company Server : Apache
System : Linux host44.registrar-servers.com 4.18.0-513.18.1.lve.2.el8.x86_64 #1 SMP Sat Mar 30 15:36:11 UTC 2024 x86_64
User : vapecompany ( 2719)
PHP Version : 7.4.33
Disable Function : NONE
Directory :  /home/vapecompany/demo.vapecompany.com.bd/app/Http/Controllers/Backend/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //home/vapecompany/demo.vapecompany.com.bd/app/Http/Controllers/Backend/RequisitionController.php
<?php

namespace App\Http\Controllers\Backend;

use App\Models\Requisition;
use App\Models\Customer;
use App\Models\Product;
use App\Models\MCode;
use App\Models\Color;
use App\Models\Notification;
use App\Models\RequisitionDetails;
use App\Models\Bank;
use App\Models\BankBranch;
use App\Models\Brand;
use App\Models\Barcode;
use App\Models\Emplyoee;
use App\Models\SalesTarget;
use App\Models\SaleTargetDetail;
use Illuminate\Http\Request;
use DB;
use Carbon\Carbon;
use Barryvdh\DomPDF\Facade as PDF;
use Meneses\LaravelMpdf\Facades\LaravelMpdf as mPDF;

use Maatwebsite\Excel\Facades\Excel;
use App\Exports\Requisition_List;
use App\Http\Controllers\Controller;

class RequisitionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    // public function __construct()
    // {
    //     $this->middleware('auth');
       
    // }
    public function index()
    {
       if(!auth()->user()->canEvent('all_requisition'))
        {
            return redirect('/');
        }
        return view('requisition.list');
    }
    function GetOrderByDivision(Request $request){
        //return $request;
        $start_date_month=Carbon::now('Asia/dhaka')->firstOfMonth()->format('Y-m-d');
        $end_date_month=Carbon::now('Asia/dhaka')->endOfMonth()->format('Y-m-d');
        $con=array();
        if($request->division_id){
            $con['division_id']=$request->division_id;
        }

        $total_pending=Requisition::leftJoin('customers', 'requisitions.customer_id', '=', 'customers.customer_id')
        ->where('requistion_status',1)->orWhere('requistion_status',2)->orWhere('requistion_status',3)->whereBetween('requisition_date', [$start_date_month, $end_date_month])->where($con)->count();

        $total_requisition=Requisition::leftJoin('customers', 'requisitions.customer_id', '=', 'customers.customer_id')->whereBetween('requisition_date', [$start_date_month, $end_date_month])->where('requistion_status','!=',0)->where($con)->count();

        $total_chalan=Requisition::leftJoin('customers', 'requisitions.customer_id', '=', 'customers.customer_id')->where('requistion_status',4)->whereBetween('requisition_date', [$start_date_month, $end_date_month])->where($con)->count();

        return view('order_status_division',['total_requisition'=>$total_requisition,'total_chalan'=>$total_chalan,'total_pending'=>$total_pending]);
    }
    function RequisitonPdf(Request $request){
       // dd($request);
      $s_date=$request->start_date;
         $e_date=$request->end_date;
         $columnName=$request->columnName;
         $columnSortOrder=$request->columnSortOrder;
         $start=$request->start;
         $rowperpage=$request->rowperpage;
         if(auth()->user()->employee->user_type == 3){
             $requisitions =Requisition::orderBy($columnName,$columnSortOrder)
             ->leftJoin('emplyoees','emplyoees.employee_id','requisitions.sales_by')
            ->leftJoin('customers','customers.customer_id','requisitions.customer_id')
            ->leftJoin('customer_types','customer_types.customer_type_id','customers.customer_type_id');
             if($request->id){
                $requisitions=$requisitions->Where('requisition_id', $request->id);
            }
            if($request->requision_code){
                $requisitions=$requisitions->Where('Requsition_code', 'like', $request->requision_code . '%');
            }
            if($request->start_date){

                $s_arr=explode('-',$request->start_date);
                $start_date=$s_arr[2].'-'.$s_arr[1].'-'.$s_arr[0];
                if($request->end_date){
                    $s_arr1=explode('-',$request->end_date);
                    $end_date=$s_arr1[2].'-'.$s_arr1[1].'-'.$s_arr1[0];
                }else{
                    $end_date=$end_date=Carbon::now()->format('Y-m-d');
                }
             
                $damageStocks=$damageStocks->whereBetween('requisition_date', [$start_date, $end_date]);
                          
            }
             if($request->customer_type){
                $requisitions=$requisitions->Where('customer_type_name', 'like', $request->customer_type. '%');
            }
            if($request->customer_name){
                $requisitions=$requisitions->Where('customer_name', 'like',$request->customer_name. '%');
            }
            if($request->customer_address){
                $requisitions=$requisitions->Where('customer_address', 'like', '%'.$request->customer_address. '%');
            }
             if($request->employee_name){
                $requisitions=$requisitions->Where('employee_name', 'like', $request->employee_name . '%');
            }
            if($request->payment_mode){
                $requisitions=$requisitions->Where('payment_mode', $request->payment_mode);
            }
            if($request->status){
                $requisitions=$requisitions->Where('requistion_status', $request->status);
            }
            $requisitions=$requisitions->where('sales_by' , auth()->user()->user_id);
            // ->where(function($query) use ($searchValue){
            //     $query->where('requisition_id', 'like', $searchValue . '%')
            //           ->orWhere('Requsition_code', 'like',$searchValue . '%')
            //           ->orWhere('requisition_date', 'like',$searchValue . '%');
            // });
           
            //return $requisitions;
            $totalRecords = $requisitions->count();
        }else{
             $requisitions =Requisition::orderBy($columnName,$columnSortOrder)
             ->leftJoin('emplyoees','emplyoees.employee_id','requisitions.sales_by')
            ->leftJoin('customers','customers.customer_id','requisitions.customer_id')
            ->leftJoin('customer_types','customer_types.customer_type_id','customers.customer_type_id');
             if($request->id){
                $requisitions=$requisitions->Where('requisition_id', $request->id);
            }
            if($request->requision_code){
                $requisitions=$requisitions->Where('Requsition_code', 'like', $request->requision_code . '%');
            }
            if($request->start_date){

                $s_arr=explode('-',$request->start_date);
                $start_date=$s_arr[2].'-'.$s_arr[1].'-'.$s_arr[0];
                if($request->end_date){
                    $s_arr1=explode('-',$request->end_date);
                    $end_date=$s_arr1[2].'-'.$s_arr1[1].'-'.$s_arr1[0];
                }else{
                    $end_date=$end_date=Carbon::now()->format('Y-m-d');
                }
             
                $damageStocks=$damageStocks->whereBetween('requisition_date', [$start_date, $end_date]);
                      
            }
             if($request->id){
                $requisitions=$requisitions->Where('customer_type_name', 'like', $request->id. '%');
            }
            if($request->customer_name){
                $requisitions=$requisitions->Where('customer_name', 'like',$request->customer_name. '%');
            }
            if($request->customer_address){
                $requisitions=$requisitions->Where('customer_address', 'like',$request->customer_address. '%');
            }
             if($request->employee_name){
                $requisitions=$requisitions->Where('employee_name', 'like',$request->employee_name. '%');
            }
            if($request->payment_mode){
                $requisitions=$requisitions->Where('payment_mode',$request->payment_mode);
            }
            if($request->status){
                $requisitions=$requisitions->Where('requistion_status',$request->status);
            }
            // ->where('requisition_id', 'like',$searchValue . '%')
            // ->orWhere('Requsition_code', 'like',$searchValue . '%')
            // ->orWhere('requisition_date', 'like',$searchValue . '%');
            
           
            $totalRecords = $requisitions->count();
            //return $requisitions;
        }
        
        
        
         
            
        if($rowperpage < 0) {
            $rowperpage = 8999999999999999999;
        }
        $requisitions=$requisitions->skip($start)
            ->take($rowperpage)
            ->get();
           // dd($damageStocks);
        $data = [
            'chalans' => $requisitions,
            'request' => $request,
            'e_date' => $e_date,
            's_date' => $s_date,
        ];
        $pdf = mPDF::loadView('pdf.list.requisition', $data,[],[
          'orientation' => 'L',
          'format' => 'Legal'
        ]);

        if ($request->action_type == 'pdf'){
            //->save($pdfFilePath);
            return $pdf->download('Requisition-List-' . Carbon::now()->format('yyyy-mm-dd'). '.pdf');
        }elseif($request->action_type == 'print'){
            
            return $pdf->stream('Requisition-List.pdf');
        }
        else{

            return Excel::download(new Requisition_List($s_date, $e_date,$requisitions), 'Requisition-List.xlsx');

        }
    }
    function get_all_requisition(Request $request){
        $draw = $request->get('draw');
        $start = $request->get("start");
        $rowperpage = $request->get("length"); // Rows display per page

        $columnIndex_arr = $request->get('order');
        $columnName_arr = $request->get('columns');
        $order_arr = $request->get('order');
        $search_arr = $request->get('search');

        $columnIndex = $columnIndex_arr[0]['column']; // Column index
        $columnName = $columnName_arr[$columnIndex]['data']; // Column name
        $columnSortOrder = $order_arr[0]['dir']; // asc or desc
        $searchValue = $search_arr['value']; // Search value

        
        $totalRecords=0;
        $requisitions="";
        if($searchValue == null){
            $searchValue="";
        }
        if(auth()->user()->employee->user_type == 3){
             $requisitions =Requisition::orderBy($columnName,$columnSortOrder)
             ->leftJoin('emplyoees','emplyoees.employee_id','requisitions.sales_by')
            ->leftJoin('customers','customers.customer_id','requisitions.customer_id')
            ->leftJoin('customer_types','customer_types.customer_type_id','customers.customer_type_id');
             if($columnName_arr[0]['search']['value'] != null){
                $requisitions=$requisitions->Where('requisition_id', $columnName_arr[0]['search']['value']);
            }
            if($columnName_arr[1]['search']['value'] != null){
                $requisitions=$requisitions->Where('Requsition_code', 'like', $columnName_arr[1]['search']['value'] . '%');
            }
            if($columnName_arr[2]['search']['value'] != null){
                $s_arr=explode('-',$columnName_arr[2]['search']['value']);
                $start_date=$s_arr[2].'-'.$s_arr[1].'-'.$s_arr[0];
                if($columnName_arr[3]['search']['value']){
                    $s_arr1=explode('-',$columnName_arr[3]['search']['value']);
                    $end_date=$s_arr1[2].'-'.$s_arr1[1].'-'.$s_arr1[0];
                }else{
                    $end_date=$end_date=Carbon::now()->format('Y-m-d');
                }
             
                $requisitions=$requisitions->whereBetween('requisition_date', [$start_date, $end_date]);
                //$requisitions=$requisitions->Where('requisition_date', 'like', $columnName_arr[2]['search']['value'] . '%');
            }
             if($columnName_arr[4]['search']['value'] != null){
                $requisitions=$requisitions->Where('customer_type_name', 'like', $columnName_arr[4]['search']['value'] . '%');
            }
            if($columnName_arr[5]['search']['value'] != null){
                $requisitions=$requisitions->Where('customer_name', 'like', $columnName_arr[5]['search']['value'] . '%');
            }
            if($columnName_arr[6]['search']['value'] != null){
                $requisitions=$requisitions->Where('customer_address', 'like', '%'.$columnName_arr[6]['search']['value'] . '%');
            }
             if($columnName_arr[7]['search']['value'] != null){
                $requisitions=$requisitions->Where('employee_name', 'like', $columnName_arr[7]['search']['value'] . '%');
            }
            if($columnName_arr[8]['search']['value'] != null){
                $requisitions=$requisitions->Where('payment_mode', $columnName_arr[8]['search']['value']);
            }
            if($columnName_arr[9]['search']['value'] != null){
                $requisitions=$requisitions->Where('requistion_status', $columnName_arr[9]['search']['value']);
            }
            $requisitions=$requisitions->where('sales_by' , auth()->user()->user_id);
            // ->where(function($query) use ($searchValue){
            //     $query->where('requisition_id', 'like', $searchValue . '%')
            //           ->orWhere('Requsition_code', 'like',$searchValue . '%')
            //           ->orWhere('requisition_date', 'like',$searchValue . '%');
            // });
           
            //return $requisitions;
            $totalRecords = $requisitions->count();
        }else{
             $requisitions =Requisition::orderBy($columnName,$columnSortOrder)
             ->leftJoin('emplyoees','emplyoees.employee_id','requisitions.sales_by')
            ->leftJoin('customers','customers.customer_id','requisitions.customer_id')
            ->leftJoin('customer_types','customer_types.customer_type_id','customers.customer_type_id');
             if($columnName_arr[0]['search']['value'] != null){
                $requisitions=$requisitions->Where('requisition_id', $columnName_arr[0]['search']['value']);
            }
            if($columnName_arr[1]['search']['value'] != null){
                $requisitions=$requisitions->Where('Requsition_code', 'like', $columnName_arr[1]['search']['value'] . '%');
            }
            if($columnName_arr[2]['search']['value'] != null){
                $s_arr=explode('-',$columnName_arr[2]['search']['value']);
                $start_date=$s_arr[2].'-'.$s_arr[1].'-'.$s_arr[0];
                if($columnName_arr[3]['search']['value']){
                    $s_arr1=explode('-',$columnName_arr[3]['search']['value']);
                    $end_date=$s_arr1[2].'-'.$s_arr1[1].'-'.$s_arr1[0];
                }else{
                    $end_date=$end_date=Carbon::now()->format('Y-m-d');
                }
             
                $requisitions=$requisitions->whereBetween('requisition_date', [$start_date, $end_date]);
            }
             if($columnName_arr[4]['search']['value'] != null){
                $requisitions=$requisitions->Where('customer_type_name', 'like', $columnName_arr[4]['search']['value'] . '%');
            }
            if($columnName_arr[5]['search']['value'] != null){
                $requisitions=$requisitions->Where('customer_name', 'like', $columnName_arr[5]['search']['value'] . '%');
            }
            if($columnName_arr[6]['search']['value'] != null){
                $requisitions=$requisitions->Where('customer_address', 'like', $columnName_arr[6]['search']['value'] . '%');
            }
             if($columnName_arr[7]['search']['value'] != null){
                $requisitions=$requisitions->Where('employee_name', 'like', $columnName_arr[7]['search']['value'] . '%');
            }
            if($columnName_arr[8]['search']['value'] != null){
                $requisitions=$requisitions->Where('payment_mode', $columnName_arr[8]['search']['value']);
            }
            if($columnName_arr[9]['search']['value'] != null){
                $requisitions=$requisitions->Where('requistion_status', $columnName_arr[9]['search']['value']);
            }
            // ->where('requisition_id', 'like',$searchValue . '%')
            // ->orWhere('Requsition_code', 'like',$searchValue . '%')
            // ->orWhere('requisition_date', 'like',$searchValue . '%');
            
           
            $totalRecords = $requisitions->count();
            //return $requisitions;
        }
        if($rowperpage < 0) {
            $rowperpage = 8999999999999999999;
        }
        $grand_q = $requisitions->sum('total_quantity');
        $grand_ta = $requisitions->sum('total_amount');
        $grand_tpa = $requisitions->sum('paid_amount');
        $requisitions= $requisitions->skip($start)
            ->take($rowperpage)
            ->get();
       
        $data_arr = array();
        foreach($requisitions as $requisition){

            $action ='<div role="group" aria-label="Basic example" class="btn-group btn-group-sm">';
            if(auth()->user()->is_admin == 0)
            {
                if($requisition->requistion_status == 0 || $requisition->requistion_status == 1){
                if(auth()->user()->canEvent('edit_requisition'))
                { 
                    if($requisition->sales_by == auth()->user()->user_id)
                    {
                         $action .='<a href="'.url('edit_requisition/'.$requisition->requisition_id).'" class="mr-2">
                                                             <i class="fa fa-edit text-warning"></i>
                                                        </a> ';
                    }
                    
                }
            }
                if(auth()->user()->canEvent('view_requisition'))
                { 
                    $action .=' <a href="'.url('view_requisition/'.$requisition->requisition_id).'" class="mr-2">
                                                            <i class="fa fa-eye"></i>
                                                        </a>';
                }
            }else{
                // if($requisition->requistion_status == 0 || $requisition->requistion_status == 1){
                if($requisition->requistion_status < 3)
                {
                     $action .='<a href="'.url('edit_requisition/'.$requisition->requisition_id).'" class="mr-2">
                                                         <i class="fa fa-edit text-warning"></i>
                                                     </a> ';
                }
           // }
               
                $action .=' <a href="'.url('view_requisition/'.$requisition->requisition_id).'" class="mr-2">
                                                            <i class="fa fa-eye"></i>
                                                        </a>';
            }
            if(auth()->user()->canEvent('new_chalan'))
            {
                if($requisition->requistion_status == 3){
                        if($requisition->is_challan == 0){
                            $action .=' <a target="_blank" href="'.url('new_chalan?requisition_id='.$requisition->requisition_id).'" class="mr-2">
                                                       Create Challan
                                                    </a>';

                        }                            
                    }
            }
                
                if($requisition->invoice_number){
                    if(auth()->user()->canEvent('print_invoice')){
                    $action .=' <a target="_blank" href="'.url('print_invoice/'.$requisition->requisition_id).'" class="mr-2">
                                                           Print Invoice
                                                        </a>';
                    }
               }else{
                   if(auth()->user()->canEvent('generate_invoice')){
                   if($requisition->requistion_status == 3 || $requisition->requistion_status == 4){
                        $action .=' <a href="'.url('generate_invoice/'.$requisition->requisition_id).'" class="mr-2">
                                                           Generate Invoice
                                                        </a>';
                       
                    }
                   }
                    
               }
         
            
            
            

            


            //$action .='<a href="javascript:void(0);"><i class="fa fa-trash text-danger"></i></a>' ;

            $action .=' </div>';
            $date=date('Y-m-d',strtotime($requisition->requisition_date));
            if($requisition->payment_mode == 1){
                $mode='Cash On Delivery';
            }elseif($requisition->payment_mode == 2){
                $mode='Bank';
            }else{
                $mode='--';
            }
            if($requisition->requistion_status == 0)
                $status='Draft';
            else if($requisition->requistion_status == 1)
                $status='Pending';
            else if($requisition->requistion_status == 2)
               $status='Requisition Approved';
            else if($requisition->requistion_status == 3)
               $status='Accounts Approved';
            else if($requisition->requistion_status == 4)
                $status='Delivered';
            else if($requisition->requistion_status == 5)
                $status='Requisition Canceled';
            else
               $status='Accounts Rejected';
            if($requisition->bank_deposit_image){
                $img='<img height="80px" width="80px" src="'.url('public/images/bank_slip/').'/'.$requisition->bank_deposit_image.'">'; 
            }else{
                $img="";
            }
               
                                               
            $data_arr[] = array(
                "requisition_id" => $requisition->requisition_id,
                "Requsition_code" => $requisition->Requsition_code,
                "total_quantity" => $requisition->total_quantity,
                "total_amount" => number_format($requisition->total_amount,2),
                "paid_amount" => number_format($requisition->paid_amount,2),
                "total_incentive" => number_format($requisition->total_incentive,2),
                "requisition_date" => $requisition->requisition_date->format('d-m-Y'),
                "invoice_number" => $requisition->invoice_number,
                "customer_name" => $requisition->customer->customer_name,
                "customer_address" => $requisition->customer->customer_address,
                "region" => $requisition->customer->region ? $requisition->customer->region->region_name : '',
                "division" => $requisition->customer->division ? $requisition->customer->division->division_name : '',
                "district" => $requisition->customer->district ? $requisition->customer->district->district_name : '',
                "area" => $requisition->customer->area ? $requisition->customer->area->area_name : '',
                "customer_type_name" => $requisition->customer->type->customer_type_name,
                "employee_name" => $requisition->employee->employee_name,
                "branch_name" => $requisition->bank ? $requisition->bank->bank_name.'<br/>'.($requisition->branch ? $requisition->branch->bank_branch_name :'' ) : '',
                "deposit_slip" => $img,
                "payment_mode" => $mode,
                "grand_q" => 0,
                "grand_ta" => 0,
                "grand_tpa" => 0,
               // "bank_name" => $requisition->bank_name,
                "requistion_status" => $status,
                "Action" => $action,
            );
        }
        if(!empty($data_arr)){
            $data_arr[0]['grand_q']=$grand_q;
            $data_arr[0]['grand_ta']=$grand_ta;
            $data_arr[0]['grand_tpa']=$grand_tpa;
        }
        
        //totalsum
        $response = array(
            'd'=>$searchValue,
            "draw" => intval($draw),
            "recordsTotal" => $totalRecords,
            "recordsFiltered" => $totalRecords,
            "data" => $data_arr,
            'columnName'=>$columnName,
            'columnSortOrder'=>$columnSortOrder,
            'start'=>$start,
            'rowperpage'=>$rowperpage
        ); 

        echo json_encode($response);
        exit;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if(!auth()->user()->canEvent('new_requisition'))
        {
            return redirect('/');
        }

        $sales_man=null;
        if(auth()->user()->employee->user_type == 3){
            $dat=Carbon::now()->format('Y')*100+Carbon::now()->format('m');
            $salesTarget =SalesTarget::where('month',$dat)->where('employee_id',auth()->user()->user_id)->first();
            if($salesTarget){
                $area=json_decode($salesTarget->area);
            }else{
                $area=[];
            }
            $customers=Customer::whereIn('area_id',$area)->get();
        //$customers =Customer::where('status',1)->where('district_id' , auth()->user()->employee->district_id)->get();
        }else{
            $customers =Customer::where('status',1)->get();
            $sales_man=Emplyoee::where('user_type',3)->get();
        }
        $brands=Brand::where('status',1)->get();
        $banks=Bank::where('status',1)->get();
        return view("requisition.create",['sales_man'=>$sales_man,'customers'=>$customers,'brands'=>$brands,'banks'=>$banks]);
    }
    public function addCart(Request $request){
        $product=Product::where('product_id',$request->id)->first();
        $color=Color::where('color_id',$request->color)->first()->color_name;
        $barcode = Barcode::where('product_id',$request->id)->first();
        if($barcode){
            //if($barcode->quantity >= $request->qty){
             return view('backend.requisition.cart_item',['barcode'=>$barcode,'color_id'=>$request->color,'qty'=>$request->qty,'brand_id'=>$request->brand_id,'uniqueid'=>$request->uniqueid]);
             // }else{
             //    return 1;
             // }
         }else{
             return 1;
         }
        
       //return $request->all();
       
    }
    public function addCartStock(Request $request){
        $product=Product::where('product_id',$request->id)->first(); 
        // $color=Color::where('color_id',$request->color)->first()->color_name;
        $purchase_price = $request->price;
        $total_purchase_price = $request->price*$request->qty;
          
        return view('backend.stock.cart_item_ac',['product'=>$product,'color_id'=>$request->color,'qty'=>$request->qty,'brand_id'=>$request->brand_id,'uniqueid'=>$request->uniqueid,'purchase_price'=>$purchase_price,'total_purchase_price'=>$total_purchase_price]);
            
        
       //return $request->all();
       
    }
    public function addCartAc(Request $request){
        $product=Product::where('product_id',$request->id)->first();
        $color=Color::where('color_id',$request->color_id)->first()->color_name;
       //return $request->all();
        return view('stock.cart_item',['color'=>$color,'product'=>$product,'color_id'=>$request->color_id,'qty'=>$request->qty,'uniqueid'=>$request->uniqueid,'type'=>$request->type]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
      
      // return $request;
        $code=MCode::get();
      
        if($request->btn_value == "submit"){
            if($request->delivery_mode == 2){
                $validator = \Validator::make($request->all(), [
                    'requisition_date' => 'required',
                    'customer' => 'required',
                    'delivery_mode' => 'required',
                    'bank' => 'required',
                    'branch' => 'required',
                    'bank_slip' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
               
                ]);
            }else{
                $validator = \Validator::make($request->all(), [
                    'requisition_date' => 'required',
                    'customer' => 'required',
                    'delivery_mode' => 'required',
               
                ]);
            }
            
        }else if($request->btn_value == "draft"){
            $validator = \Validator::make($request->all(), [
                'customer' => 'required',
                'requisition_date' => 'required',
            ]);
        }
        
        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()->all()]);
        }else{
            $new_name="";
            if($request->btn_value == "submit"){
                if($request->delivery_mode == 2){
                    if ($request->hasFile('bank_slip')) {
                  
                        if ($request->file('bank_slip')->isValid()) {
                            $image = $request->file('bank_slip');
                            $new_name = $image->getClientOriginalName(). '.' . $image->getClientOriginalExtension();
                            $image->move(public_path('images/bank_slip'), $new_name);
                        }else{
                            return response()->json(['errors'=>['imag'=>'image not valid']]);
                        }
                    }else{
                        return response()->json(['errors'=>['imag'=>'image not found']]);
                    }
                }
            }   
            $code=MCode::where('requisition_time',date("Y").date('m'))->first();
            $requisition_n=1;
            if($code){
                $requisition_n =str_pad($code->requisition_code,4,0,STR_PAD_LEFT);
            }else{
                $requisition_n =str_pad($requisition_n,4,0,STR_PAD_LEFT);

            }
            try {
                DB::beginTransaction();
                 $total_price=0;
                $total_quantity=0;
                $total_incentive=0;
                $requisition_date=explode('-', $request->requisition_date);
                foreach($request->product_id as $k=>$v){
                    $product=Product::where('product_id',$v)->first();
                    $total_quantity += $request->qty[$k];
                    $total_price += $request->total_sale_price[$k];
                    $total_incentive += $request->total_incentive_price[$k];
                }
                $requisition =  new Requisition;
                $requisition->customer_id = $request->customer;
                $requisition->Requsition_code = date("Y").date('m').$requisition_n;
                $requisition->requisition_date = $requisition_date[2].'-'.$requisition_date[1].'-'.$requisition_date[0];
                $requisition->total_quantity = $total_quantity;
                $requisition->total_amount = $total_price;
                $requisition->paid_amount = $request->paid_amount;
                $requisition->total_incentive = $total_incentive;
                $requisition->payment_mode = $request->delivery_mode;
                if($request->delivery_mode == 2){
                    $requisition->bank_id = $request->bank;
                    $requisition->branch_id = $request->branch;
                    //$requisition->bank_deposit_number = $new_name;
                    $requisition->bank_deposit_image = $new_name;
                }
                if($request->btn_value == "draft"){
                    $requisition->requistion_status = 0;
                }else if($request->btn_value == "submit"){
                    $requisition->requistion_status = 1;
                }
               $requisition->sales_by = $request->sales_man;
                $requisition->created_by = auth()->user()->user_id;
                $requisition->save();
                $uid=$requisition->requisition_id;

                $i=0;
                foreach($request->product_id as $k=>$v){
                    $product=Product::where('product_id',$v)->first();
                    $details = new RequisitionDetails;

                    $details->requisition_id=$uid;
                    $details->product_id=$v;
                    $details->product_quantity=$request->qty[$i];
                    $details->color_id=$request->color[$i];
                    $details->product_unit_price=$product->sale_price;
                    $details->product_price=$product->sale_price * $request->qty[$i];
                    $details->incentive_price=$request->total_incentive_price[$i];
                    
                    
                    $details->save();

                    $i++;
                }
                //MCode::where('id',1)->update(['requisition_code'=>intval($code->requisition_code)+1]);
                if($code){
                    MCode::where('id',1)->update(['requisition_code'=>intval($code->requisition_code)+1]);
                }else{
                     MCode::where('id',1)->update(['requisition_code'=>2,'requisition_time'=>date("Y").date('m')]);
                }
                if($request->btn_value == "submit"){
                    $employees=Emplyoee::where('department_id',1)->where('user_type',2)->orwhere('user_type',1)->get();
                    foreach($employees as $employee){
                        $notification = new Notification;
                        $notification->message="Requisition is Created";
                        $notification->notefication_date=Carbon::now('Asia/dhaka');
                        $notification->target_url=$uid;
                        $notification->type=1;
                        $notification->user_id=$employee->user_id;
                        $notification->department_id=$employee->department_id;
                        $notification->created_by=auth()->user()->user_id;
                        $notification->save();
                    }
                    

                }
                DB::commit();
            } catch (\PDOException $e) {
                // Woopsy
                DB::rollBack();
                return response()->json(['errors'=>$e]);
            }
           
            
        }
        return response()->json(['errors'=>'0','success'=>'Record is successfully added']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Requisition  $requisition
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
       if(!auth()->user()->canEvent('view_requisition'))
        {
            return redirect('/');
        }

        // dd($salesTarget);
        $requisition=Requisition::where('requisition_id',$id)->first();
       // //dd($requisition->details->sortByDesc(function ($product, $key) {

       //                  return $product['product_id'].$product['color_id'];

       //              }));
        return view('requisition.show',['requisition'=>$requisition]);

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Requisition  $requisition
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if(!auth()->user()->canEvent('edit_requisition'))
        {
            return redirect('/');
        }
         $customers =Customer::get();
        $brands=Brand::get();
        $banks=Bank::get();
        $requisition=Requisition::where('requisition_id',$id)->first();
        $branchs=BankBranch::where('bank_id',$requisition->bank_id)->get();
        return view("requisition.edit",['requisition'=>$requisition,'customers'=>$customers,'brands'=>$brands,'banks'=>$banks,'branchs'=>$branchs]);
    }
    function generateInvoice($id){
        if(!auth()->user()->canEvent('generate_invoice'))
        {
            return redirect('/');
        }
        $requisition=Requisition::where('requisition_id',$id)->first();
        return view('requisition.generate_invoice',['requisition'=>$requisition]);
    }
    function postGenerateInvoice(Request $request){
        $validator = \Validator::make($request->all(), [
            'buyer_order_no' => 'max:150',
            
       
        ]);
        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()->all()]);
        }else{
            try {
                DB::beginTransaction();
                $id=$request->requisition_id;
                $requisition=Requisition::where('requisition_id',$id)->first();
                $code=MCode::where('r_invoice_time',date("Y").date('m'))->first();
                $invoice_number=1;
                if($code){
                    $invoice_number =str_pad($code->r_invoice_number,4,0,STR_PAD_LEFT);
                }else{
                    $invoice_number =str_pad($invoice_number,4,0,STR_PAD_LEFT);
                }
                $buyer_order_date=explode('-', $request->buyer_order_date);
                $invoice_date=explode('-', $request->invoice_date);
                $requisition->invoice_number=date("Y").date('m').$invoice_number;
                $requisition->buyer_order_no=$request->buyer_order_no;
                $requisition->invoice_date=$invoice_date[2].'-'.$invoice_date[1].'-'.$invoice_date[0];
                $requisition->buyer_order_date=$buyer_order_date[2].'-'.$buyer_order_date[1].'-'.$buyer_order_date[0];
                $requisition->other_reference=$request->other_reference;
                $requisition->terms_delivery=$request->terms_delivery;
                $requisition->save();
                 if($code){
                    MCode::where('id',1)->update(['r_invoice_number'=>intval($code->r_invoice_number)+1]);
                }else{
                     MCode::where('id',1)->update(['r_invoice_number'=>2,'r_invoice_time'=>date("Y").date('m')]);
                }
                DB::commit();
                return response()->json(['errors'=>'0','success'=>'Invoice Generate Successfully','id'=>$request->requisition_id]);
            } catch (\PDOException $e) {
                // Woopsy
                DB::rollBack();
                return response()->json(['errors'=>$e]);
            }
        }

    }
    function printInvoice($id){
        if(!auth()->user()->canEvent('print_invoice'))
        {
            return redirect('/');
        }
         $requisition=Requisition::where('requisition_id',$id)->first();
         return view('pdf.sell.invoice',['requisition'=>$requisition]);
         $pdf = PDF::loadView('pdf.sell.invoice', compact('requisition', 'copy'))->setPaper('a4');
        @unlink('pdf/requisition/' . 'invoice.pdf');
           $pdf->save('pdf/requisition/' . 'invoice.pdf');
         return redirect('pdf/requisition/' . 'invoice.pdf');
        $data = [
            'requisition' => $requisition
        ];
         $pdf = mPDF::loadView('pdf.sell.invoice', $data);
         return $pdf->stream('invoice.pdf');
       return view('pdf.sell.invoice',['requisition'=>$requisition]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Requisition  $requisition
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        //return $request;
        $code=MCode::get();
      
        if($request->btn_value == "submit"){
            if($request->delivery_mode == 2){
                $validator = \Validator::make($request->all(), [
                    'requisition_date' => 'required',
                    'customer' => 'required',
                    'delivery_mode' => 'required',
                    'bank' => 'required',
                    'branch' => 'required',
                    'bank_slip' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
               
                ]);
            }else{
                $validator = \Validator::make($request->all(), [
                    'requisition_date' => 'required',
                    'customer' => 'required',
                    'delivery_mode' => 'required',
               
                ]);
            }
            
        }else if($request->btn_value == "draft"){
            $validator = \Validator::make($request->all(), [
                'customer' => 'required',
                'requisition_date' => 'required',
            ]);
        }else{

            $validator = \Validator::make($request->all(), [
                'customer' => 'required',
                'requisition_date' => 'required',
            ]);
        
        }
        
        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()->all()]);
        }else{
                $new_name="";
                if($request->delivery_mode == 2){
                    if ($request->hasFile('bank_slip')) {
                  
                        if ($request->file('bank_slip')->isValid()) {
                            $image = $request->file('bank_slip');
                            $new_name = $image->getClientOriginalName(). '.' . $image->getClientOriginalExtension();
                            $image->move(public_path('images/bank_slip'), $new_name);
                        }else{
                            return response()->json(['errors'=>['imag'=>'image not valid']]);
                        }
                    }
                }
            
            
            try {
                DB::beginTransaction();
                 $total_price=0;
                $total_quantity=0;
                $total_incentive=0;
                $requisition_date=explode('-', $request->requisition_date);
                foreach($request->product_id as $k=>$v){
                    $product=Product::where('product_id',$v)->first();
                    $total_quantity += $request->qty[$k];
                    $total_price = $total_price+$request->total_sale_price[$k];
                    $total_incentive += $request->total_incentive_price[$k];
                }
                //return $total_price;
                $requisition =  Requisition::find($request->requisition_id);
                $requisition->customer_id = $request->customer;
                
                $requisition->requisition_date = $requisition_date[2].'-'.$requisition_date[1].'-'.$requisition_date[0];
                $requisition->total_quantity = $total_quantity;
                $requisition->total_amount = $total_price;
                $requisition->paid_amount = $request->paid_amount;
                $requisition->total_incentive = $total_incentive;
                $requisition->payment_mode = $request->delivery_mode;
                if($request->delivery_mode == 2){
                    $requisition->bank_id = $request->bank;
                    $requisition->branch_id = $request->branch;
                    //$requisition->bank_deposit_number = $new_name;
                    $requisition->bank_deposit_image = $new_name == "" ? $requisition->bank_deposit_image : $new_name;
                }
                if($request->btn_value == "draft"){
                    $requisition->requistion_status = 0;
                }else if($request->btn_value == "submit"){
                    $requisition->requistion_status = 1;
                }
               $requisition->updated_by = auth()->user()->user_id;
                $requisition->save();
                $uid=$requisition->requisition_id;

                $i=0;
                foreach($request->product_id as $k=>$v){
                    $product=Product::where('product_id',$v)->first();
                    $details = RequisitionDetails::where('requisition_id',$request->requisition_id)->where('product_id',$v)->where('color_id',$request->color[$i])->first();
                    if($details){
                         $details->requisition_id=$uid;
                        $details->product_id=$v;
                        $details->product_quantity=$request->qty[$i];
                        $details->incentive_price=$request->total_incentive_price[$i];
                        $details->color_id=$request->color[$i];
                        $details->product_unit_price=$product->sale_price;
                        $details->save();
                    }else{
                        $details = new RequisitionDetails;
                        $details->requisition_id=$uid;
                        $details->product_id=$v;
                        $details->product_quantity=$request->qty[$i];
                        $details->color_id=$request->color[$i];
                        $details->incentive_price=$request->total_incentive_price[$i];
                        $details->product_unit_price=$product->sale_price;
                        $details->save();
                    }

                   

                    $i++;
                }
                
                if($request->btn_value == "submit"){
                    $employees=Emplyoee::where('department_id',1)->where('user_type',2)->orwhere('user_type',1)->get();
                    foreach($employees as $employee){
                        $notification = new Notification;
                        $notification->message="Requisition is Created";
                        $notification->notefication_date=Carbon::now('Asia/dhaka');
                        $notification->target_url=$uid;
                        $notification->type=1;
                        $notification->user_id=$employee->user_id;
                        $notification->department_id=$employee->department_id;
                        $notification->created_by=auth()->user()->user_id;
                        $notification->save();
                    }
                    

                }
                if($request->btn_value == "update"){
                    $employees=Emplyoee::where('department_id',1)->where('user_type',2)->orwhere('user_type',1)->get();
                    foreach($employees as $employee){
                        $notification = new Notification;
                        $notification->message="Requisition is updated";
                        $notification->notefication_date=Carbon::now('Asia/dhaka');
                        $notification->target_url=$uid;
                        $notification->type=1;
                        $notification->user_id=$employee->user_id;
                        $notification->department_id=$employee->department_id;
                        $notification->created_by=auth()->user()->user_id;
                        $notification->save();
                    }
                    $employees=Emplyoee::where('department_id',2)->orwhere('user_type',1)->get();
                    foreach($employees as $employee){
                        $notification = new Notification;
                        $notification->message="Requisition is updated";
                        $notification->notefication_date=Carbon::now('Asia/dhaka');
                        $notification->target_url=$uid;
                        $notification->type=1;
                        $notification->user_id=$employee->user_id;
                        $notification->department_id=$employee->department_id;
                        $notification->created_by=auth()->user()->user_id;
                        $notification->save();
                    }
                    

                }
                DB::commit();
            } catch (\PDOException $e) {
                // Woopsy
                DB::rollBack();
                return response()->json(['errors'=>$e]);
            }
           
            
        }
        return response()->json(['errors'=>'0','success'=>'Record is successfully Updated']);
    }
    public function updateStatus($id,$action){
        if(!auth()->user()->canEvent('update_requisition_status'))
        {
            return redirect('/');
        }
     try {
              DB::beginTransaction();
        $requisition = Requisition::where('requisition_id',$id)->first();

        $message = "";
        $dep=0;
        $user=0;
        if($action == 'approve'){
            if($requisition->requistion_status == 1){
                $dep=3;
                $requisition->requistion_status = 2;
                $requisition->approved_by = auth()->user()->user_id;
                $requisition->approve_date = Carbon::now('Asia/dhaka');
                //$message="Requisition Approve for Account Veriry";
                $employees=Emplyoee::where('department_id',2)->orwhere('user_type',1)->get();
                foreach($employees as $employee){
                    $notification = new Notification;
                    $notification->message="Requisition Approve for Account Veriry";
                    $notification->notefication_date=Carbon::now('Asia/dhaka');
                    $notification->target_url=$requisition->requisition_id;
                    $notification->type=1;
                    $notification->user_id=$employee->user_id;
                    $notification->department_id=$employee->department_id;
                    $notification->created_by=auth()->user()->user_id;
                    $notification->save();
                }
                //$message="Approve for Account Veriry";
            }else{
                $dep=7;
                $requisition->requistion_status = 3;
                $requisition->verified_by =auth()->user()->user_id;
                $requisition->verify_date = Carbon::now('Asia/dhaka');
               
                $employees=Emplyoee::where('department_id',3)->orwhere('user_type',1)->get();
                foreach($employees as $employee){
                    $notification = new Notification;
                    $notification->message="Requisition Amount Verify for Delivery";
                    $notification->notefication_date=Carbon::now('Asia/dhaka');
                    $notification->target_url=$requisition->requisition_id;
                    $notification->type=1;
                    $notification->user_id=$employee->user_id;
                    $notification->department_id=$employee->department_id;
                    $notification->created_by=auth()->user()->user_id;
                    $notification->save();
                }
            }
        }else if($action == 'delivered'){
            
            $employee = Emplyoee::where('user_id',$requisition->sales_by)->first();
            $moth = \Carbon\Carbon::now('Asia/dhaka')->year * 100+\Carbon\Carbon::now('Asia/dhaka')->month;
            $salesTarget =   SalesTarget::where('employee_id',$employee->employee_id)->where('month',$moth)->first();
            if($salesTarget){
            foreach ($requisition->details as $key => $value) {
               $salesTargetDetails =  SaleTargetDetail::where('sale_target_id',$salesTarget->sale_target_id)->where('product_id',$value->product_id)->first();
                if($salesTargetDetails){
                    $salesTargetDetails->sales_quantity=$salesTargetDetails->sales_quantity+$value->product_quantity;
                    $salesTargetDetails->sales_amount=$salesTargetDetails->sales_amount+($value->product_unit_price * $value->product_quantity);
                    $salesTargetDetails->save();
                }
            }
            }
             $user=$requisition->sales_by;
            $requisition->requistion_status = 4;
            $requisition->delivered_by = auth()->user()->user_id;
            $requisition->delivered_date = Carbon::now('Asia/dhaka');
      
            $employees=Emplyoee::where('user_id',$requisition->sales_by)->orwhere('user_type',1)->get();
            foreach($employees as $employee){
                $notification = new Notification;
                $notification->message="Requisition is Delivered";
                $notification->notefication_date=Carbon::now('Asia/dhaka');
                $notification->target_url=$requisition->requisition_id;
                $notification->type=1;
                $notification->user_id=$employee->user_id;
                $notification->department_id=$employee->department_id;
                $notification->created_by=auth()->user()->user_id;
                $notification->save();
            }


        }else if($action == 'cancel'){
            $requisition->requistion_status = 5;
            $requisition->cancel_by = auth()->user()->user_id;
            $requisition->cancel_date = Carbon::now('Asia/dhaka');
           
            $notification = new Notification;
            $notification->message="Requisition is cancel By Sales Departent";
            $notification->notefication_date=Carbon::now('Asia/dhaka');
            $notification->target_url=$requisition->requisition_id;
            $notification->type=1;
            $notification->user_id=$requisition->sales_by;
            $notification->department_id=1;
            $notification->created_by=auth()->user()->user_id;
            $notification->save();

        }else if($action == 'reject'){
            $requisition->requistion_status = 6;
            $requisition->reject_by = auth()->user()->user_id;
            $requisition->reject_date = Carbon::now('Asia/dhaka');
            
            $employees=Emplyoee::where('department_id',1)->where('user_type',2)->orwhere('user_id',$requisition->sales_by)->orwhere('user_type',1)->get();
            foreach($employees as $employee){
                $notification = new Notification;
                $notification->message="Requisition is reject By Account Departent";
                $notification->notefication_date=Carbon::now('Asia/dhaka');
                $notification->target_url=$requisition->requisition_id;
                $notification->type=1;
                $notification->user_id=$employee->user_id;
                $notification->department_id=$employee->department_id;
                $notification->created_by=auth()->user()->user_id;
                $notification->save();
            }
        }
        

        $requisition->save();

        
          DB::commit();
        return redirect()->route('view_requisition',$id);
   
        } catch (\PDOException $e) {
            // Woopsy
            DB::rollBack();
           return $e;
        }
    }
    function print($id){
         $requisition=Requisition::where('requisition_id',$id)->first();
         $pdf = PDF::loadView('pdf.requisition.show', compact('requisition'))->setPaper('a4');
         @unlink('pdf/requisition/' . 'requisition.pdf');
            $pdf->save('pdf/requisition/' . 'requisition.pdf');
            return redirect('pdf/requisition/' . 'requisition.pdf');
         return view('pdf.requisition.show', compact('requisition'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Requisition  $requisition
     * @return \Illuminate\Http\Response
     */
    public function destroy(Requisition $requisition)
    {
        //
    }
}

VaKeR 2022