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 :  /proc/thread-self/root/home/vapecompany/demo.vapecompany.com.bd/app/Http/Controllers/Backend/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //proc/thread-self/root/home/vapecompany/demo.vapecompany.com.bd/app/Http/Controllers/Backend/ChalanController.php
<?php

namespace App\Http\Controllers\Backend;

use App\Models\Chalan;
use App\Models\Requisition;
use App\Models\Customer;
use App\Models\Product;
use App\Models\ChalanDetails;
use App\Models\MCode;
use App\Models\Courier;
use App\Models\Barcode;
use App\Models\Color;
use App\Models\Brand;
use App\Models\CentralReturn;
use App\Models\ProductImei;
use Barryvdh\DomPDF\Facade as PDF;
use App\Models\Emplyoee;
use App\Models\Notification;
use Illuminate\Http\Request;
use DB;
use Carbon\Carbon;
use App\Http\Controllers\Controller;
use App\Models\Category;

class ChalanController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function __construct()
    {
        $this->middleware('admin');

    }
    public function GetChalansByDivision(Request $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->category_id){
          $con['products.category_id']  =$request->category_id;
        }

        $divchalan=DB::table('divisions')
        ->select(DB::raw('sum(chalan_details.product_quantity) as quantity'), 'divisions.division_name')
        ->leftJoin('customers', 'divisions.division_id', '=', 'customers.division_id')
        ->leftJoin('chalans', 'chalans.customer_id', '=', 'customers.customer_id')
        ->leftJoin('chalan_details', 'chalan_details.chalan_id', '=', 'chalans.chalan_id')
        ->leftJoin('products', 'products.product_id', '=', 'chalan_details.product_id')
        ->whereBetween('chalans.chalan_date', [$start_date_month, $end_date_month])
        ->where($con)
        ->groupBy('divisions.division_name')
        ->get();
        return view('division_wise_sale',['divchalan'=>$divchalan]);
    }
    public function addCartBarcode(Request $request){
        $product=Product::where('product_id',$request->product_id)->first();
        $color=Color::where('color_id',$request->color_id)->first();
        return view('backend.chalan.cart_item',['product'=>$product,'qty'=>1,'color'=>$color,'uniqueid'=>$request->uniqueid]);
    }
    function addCartBarcodeCentralReturn(Request $request){
        if(isset($request->is_return)){
            $barcode = ProductImei::join('central_return_details','central_return_details.central_return_detail_id','product_imeis.central_return_detail_id')
            ->join('central_returns','central_return_details.central_return_id','central_returns.central_return_id')
            ->where('imei_1',$request->barcode)->orWhere('imei_2',$request->barcode)->first();
        }else{
            $barcode = ProductImei::join('chalan_details','chalan_details.chalan_details_id','product_imeis.chalan_details_id')
            ->join('chalans','chalan_details.chalan_id','chalans.chalan_id')
            ->where('imei_1',$request->barcode)->orWhere('imei_2',$request->barcode)->first();
        }

        if($barcode)
            return $barcode;
        else
            return "no";
    }
    public function addCartReturn(Request $request){
        $is_return=0;
        if(isset($request->is_return)){
            $is_return=1;
             $chalan=CentralReturn::join('central_return_details','central_return_details.central_return_id','central_returns.central_return_id')
                ->where('central_return_details.product_id',$request->id)
                ->where('central_returns.return_code',$request->invoice_no)
                ->where('central_return_details.color_id',$request->color)
                ->first();
               //return $chalan;

        }else{
           // return $request->invoice_no;
            $chalan=Chalan::join('chalan_details','chalan_details.chalan_id','chalans.chalan_id')
                ->where('chalan_details.product_id',$request->id)
                ->where('chalans.chalan_number',$request->invoice_no)
                ->where('chalan_details.color_id',$request->color)
                ->first();
        }

        if($chalan){
           // return  ;
            if(isset($request->is_return)){
                $c_qty=$chalan->quantity;
            }else{
                $c_qty=$chalan->product_quantity;
            }

            if($c_qty >= $request->qty){
                $is_barcode=1;
                $product=Product::where('product_id',$request->id)->first();
                        $color=Color::where('color_id',$request->color)->first();
                        $color_id=$request->color;
                        $brand_id=$product->brand_id;
                        $qty=$request->qty;
                return view('central return.cart_item',['is_return'=>$is_return,'chalan'=>$chalan,'is_barcode'=>$is_barcode,'product'=>$product,'color'=>$color,'color_id'=>$color_id,'qty'=>$qty,'brand_id'=>$brand_id,'uniqueid'=>$request->uniqueid]);
            }else{
                return 2;
            }

        }else{
            return 1;
        }

    }
    public function addCart(Request $request){
        $is_barcode=0;
        if(isset($request->barcode)){
            $res=array();
            $barcode = ProductImei::where('imei_1',$request->barcode)->orWhere('imei_2',$request->barcode)->first();
            if(isset($request->barcodelist[$barcode->imei_1]) || isset($request->barcodelist[$barcode->imei_2])){
                $res['error']=1;
                return $res;
                //return $request->barcodelist;
            }

            $res['error']=0;
            $res['product_id']=$barcode->product_id;
            $res['color_id']=$barcode->color;
            return $res;
            if($barcode){
                $product=Product::where('product_id',$barcode->product_id)->first();
                $color=Color::where('color_id',$barcode->color)->first()->color_name;
                $color_id=$barcode->color;
                $brand_id=$product->brand_id;
                $qty=1;
                $is_barcode=$request->barcode;
            }else{
                return 2;
            }


        }else{
            $barcode = Barcode::where('product_id',$request->id)->first();
            if( isset($barcode->quantity) && $barcode->quantity >= $request->qty){
                $product=Product::where('product_id',$request->id)->first();
                $color=Color::where('color_id',$request->color)->first();
                $color_id=$request->color;
                $brand_id=$request->brand_id;
                $qty=$request->qty;
            }else{
                return 1;
            }

        }


        return view('backend.chalan.cart_item',['is_barcode'=>$is_barcode,'product'=>$product,'color'=>$color,'color_id'=>$color_id,'qty'=>$qty,'brand_id'=>$brand_id,'uniqueid'=>$request->uniqueid]);
    }
    public function updateStatus($id,$action){

//        if(!auth()->user()->canEvent('chalan_status'))
//        {
//            return redirect('/');
//        }
      $chalan = Chalan::where('chalan_id',$id)->first();
       if($action == 'delivered'){

            $chalan->chalan_status = 2;
            // $chalan->status_update_by = auth()->user()->user_id;
            // $chalan->status_update_at = Carbon::now('Asia/dhaka');
            //$message="Chalan is Delivered for Customer";
            $employees=Emplyoee::where('user_type',2)->orwhere('user_type',1)->get();
            foreach($employees as $employee){
                $notification = new Notification;
                $notification->message="Chalan is Delivered for Customer";
                $notification->notefication_date=Carbon::now('Asia/dhaka');
                $notification->target_url=$chalan->chalan_id;
                $notification->type=2;
                $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{
            foreach($chalan->chalan_details as $key => $requisition_product){
                $barcode = Barcode::where('product_id',$requisition_product->product_id)->first();

                $barcode->quantity = $barcode->quantity+$requisition_product->product_quantity;
                $barcode->save();
                if($requisition_product->is_iemi == 1){
                    DB::table('product_imeis')
                      ->where('chalan_details_id', $requisition_product->chalan_details_id)
                      ->update(['chalan_details_id' => 0]);
                    // foreach ($requisition_product->imeis as $key => $imei) {
                    //   $product_iemi = ProductImei::where('product_imei_id',$imei->product_imei_id)->first();

                    //   $product_iemi->chalan_details_id=0;
                    //   $product_iemi->save();
                    //   //return $product_iemi;
                    // }
                }

            }
            $chalan->chalan_status = 3;
            // $chalan->status_update_by =auth()->user()->user_id;
            // $chalan->status_update_at = Carbon::now('Asia/dhaka');
            //$message="Chalan is Rejected By Customer";
            $employees=Emplyoee::where('user_type',2)->orwhere('user_type',1)->get();
            foreach($employees as $employee){
                $notification = new Notification;
                $notification->message="Chalan is Rejected By Customer";
                $notification->notefication_date=Carbon::now('Asia/dhaka');
                $notification->target_url=$chalan->chalan_id;
                $notification->type=2;
                $notification->user_id=$employee->user_id;
                $notification->department_id=$employee->department_id;
                // $notification->created_by=auth()->user()->user_id;
                $notification->save();
            }
        }

        $chalan->save();
        $copy="";
        return view('backend.chalan.show',['chalan'=>$chalan,'copy'=>$copy]);

    }
    public function index()
    {
    //    if(!auth()->user()->canEvent('chalan_list'))
    //     {
    //         return redirect('/');
    //     }
        return view('backend.chalan.list');
    }
    function get_all_chalan(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
        $chalans="";
        $totalRecords = 0;
        // $response = array(
        //     "dsfsd" => $request->all(),
        // );

        // echo json_encode($response);
        // exit;
        //  if(auth()->user()->employee->user_type == 3){
        //      $chalans =Chalan::orderBy($columnName,$columnSortOrder)
        //       ->leftJoin('emplyoees','emplyoees.employee_id','chalans.sales_user_id')
        //     ->leftJoin('customers','customers.customer_id','chalans.customer_id')
        //     ->leftJoin('customer_types','customer_types.customer_type_id','customers.customer_type_id');
        //     if($columnName_arr[0]['search']['value'] != null){
        //         $chalans=$chalans->Where('chalan_id', $columnName_arr[0]['search']['value']);
        //     }
        //     if($columnName_arr[1]['search']['value'] != null){
        //         $chalans=$chalans->Where('chalan_number', 'like', $columnName_arr[1]['search']['value'] . '%');
        //     }
        //     if($columnName_arr[2]['search']['value'] != null){
        //         $chalans=$chalans->Where('invoice_number', 'like', $columnName_arr[2]['search']['value'] . '%');
        //     }
        //     if($columnName_arr[3]['search']['value'] != null){
        //         $s_arr=explode('-',$columnName_arr[3]['search']['value']);
        //         $start_date=$s_arr[2].'-'.$s_arr[1].'-'.$s_arr[0];
        //         if($columnName_arr[4]['search']['value']){
        //             $s_arr1=explode('-',$columnName_arr[4]['search']['value']);
        //             $end_date=$s_arr1[2].'-'.$s_arr1[1].'-'.$s_arr1[0];
        //         }else{
        //             $end_date=$end_date=Carbon::now()->format('Y-m-d');
        //         }

        //         $chalans=$chalans->whereBetween('chalan_date', [$start_date, $end_date]);
        //     }
        //     // if($columnName_arr[3]['search']['value'] != null){
        //     //     $s_arr=explode('-',$columnName_arr[3]['search']['value']);

        //     //     $chalans=$chalans->Where('chalan_date', $s_arr[2].'-'.$s_arr[1].'-'.$s_arr[0]);
        //     //    // $chalans=$chalans->Where('chalan_date', 'like', $columnName_arr[3]['search']['value'] . '%');
        //     // }
        //     if($columnName_arr[5]['search']['value'] != null){
        //         $chalans=$chalans->Where('customer_type_name', 'like', $columnName_arr[5]['search']['value'] . '%');
        //     }
        //     if($columnName_arr[6]['search']['value'] != null){
        //         $chalans=$chalans->Where('customer_name', 'like', $columnName_arr[6]['search']['value'] . '%');
        //     }
        //     if($columnName_arr[7]['search']['value'] != null){
        //         $chalans=$chalans->Where('employee_name', 'like', $columnName_arr[7]['search']['value'] . '%');
        //     }
        //     if($columnName_arr[8]['search']['value'] != null){
        //         $chalans=$chalans->Where('delivery_mode',$columnName_arr[8]['search']['value'] );
        //     }
        //     if($columnName_arr[9]['search']['value'] != null){
        //         $chalans=$chalans->Where('chalan_status', $columnName_arr[9]['search']['value']);
        //     }
        //     $chalans=$chalans->where('sales_user_id' , auth()->user()->user_id);

        //      $totalRecords =$chalans->count();

        //  }else{
            \DB::connection()->enableQueryLog();
            $chalans =Chalan::orderBy($columnName,$columnSortOrder)
            ->leftJoin('emplyoees','emplyoees.employee_id','chalans.sales_user_id')
            ->leftJoin('customers','customers.customer_id','chalans.customer_id')
            ->leftJoin('customer_types','customer_types.customer_type_id','customers.customer_type_id');
            if($columnName_arr[0]['search']['value'] != null){
                $chalans=$chalans->Where('chalan_id', 'like', $columnName_arr[0]['search']['value'] . '%');
            }
            if($columnName_arr[1]['search']['value'] != null){
                $chalans=$chalans->Where('chalan_number', 'like', $columnName_arr[1]['search']['value'] . '%');
            }
            if($columnName_arr[2]['search']['value'] != null){
                $chalans=$chalans->Where('invoice_number', 'like', $columnName_arr[2]['search']['value'] . '%');
            }
            if($columnName_arr[3]['search']['value'] != null){
                $s_arr=explode('-',$columnName_arr[3]['search']['value']);
                $start_date=$s_arr[2].'-'.$s_arr[1].'-'.$s_arr[0];
                if($columnName_arr[4]['search']['value']){
                    $s_arr1=explode('-',$columnName_arr[4]['search']['value']);
                    $end_date=$s_arr1[2].'-'.$s_arr1[1].'-'.$s_arr1[0];
                }else{
                    $end_date=$end_date=Carbon::now()->format('Y-m-d');
                }

                $chalans=$chalans->whereBetween('chalan_date', [$start_date, $end_date]);
            }
            if($columnName_arr[5]['search']['value'] != null){
                $chalans=$chalans->Where('customer_type_name', 'like', $columnName_arr[5]['search']['value'] . '%');
            }
            if($columnName_arr[6]['search']['value'] != null){
                $chalans=$chalans->Where('customer_name', 'like', $columnName_arr[6]['search']['value'] . '%');
            }
            if($columnName_arr[7]['search']['value'] != null){
                $chalans=$chalans->Where('employee_name', 'like', $columnName_arr[7]['search']['value'] . '%');
            }
            if($columnName_arr[8]['search']['value'] != null){
                $chalans=$chalans->Where('delivery_mode', 'like', $columnName_arr[8]['search']['value'] . '%');
            }
            if($columnName_arr[9]['search']['value'] != null){
                $chalans=$chalans->Where('chalan_status', 'like', $columnName_arr[9]['search']['value'] . '%');
            }

            // ->Where('chalan_number', 'like', '%' .$searchValue . '%')
            // ->orWhere('invoice_number', 'like', '%' .$searchValue . '%')
            // ->orWhere('chalan_date', '=', $searchValue );
             $totalRecords =$chalans->count();

        //  }
        if($rowperpage < 0) {
            $rowperpage = 8999999999999999999;
        }
        $chalans=$chalans->skip($start)
            ->take($rowperpage)
            ->get();
$dsl=\DB::getQueryLog();
        $data_arr = array();

        foreach($chalans as $chalan){


            $action ='<div role="group" aria-label="Basic example" class="btn-group btn-group-sm">';
           // if($chalan->chalan_status == 0 || $chalan->chalan_status == 1){
                //  if(auth()->user()->canEvent('edit_chalan'))
                // {
                $action .='<a href="'.url('admin/edit_chalan/'.$chalan->chalan_id).'" class="mr-2">
                                                            <i class="fa fa-edit text-warning"></i>
                                                        </a> ';
                // }
           // }
            // if(auth()->user()->canEvent('viewchalan'))
            // {
             $action .='<a href="'.url('admin/viewchalan/'.$chalan->chalan_id).'" class="mr-2">
                                                        <i class="fa fa-eye"></i>
                                                    </a> ';
            // }
            $action .='</div>';

            $date=date('d-m-Y',strtotime($chalan->chalan_date));
            if($chalan->delivery_mode == 1){
                $mode='Courier Service';
            }elseif($chalan->delivery_mode == 2){
                $mode='Others';
            }else{
                $mode='--';
            }
            if($chalan->chalan_status == 0){
                $status='Draft';
            }elseif($chalan->chalan_status == 1){
                $status='Pending';
            }else{
                $status='Deliveried';
            }
            $data_arr[] = array(
                "chalan_id" => $chalan->chalan_id,
                "invoice_number" => $chalan->invoice_number,
                "chalan_number" => $chalan->chalan_number,
                "chalan_date" => $date,
                "customer_name" => $chalan->customer->customer_name,
                "region" => $chalan->customer->region ? $chalan->customer->region->region_name : '',
                "division" => $chalan->customer->division ? $chalan->customer->division->division_name : '',
                "district" => $chalan->customer->district ? $chalan->customer->district->district_name : '',
                "area" => $chalan->customer->area ? $chalan->customer->area->area_name : '',
                "customer_type_name" => $chalan->customer->type->customer_type_name,
                "employee_name" => $chalan->salesman->employee_name,
                "delivery_mode" => $mode,
                "chalan_status" => $status,
                "Action" => $action,
            );
        }
        $response = array(
            "draw" => intval($draw),
            "recordsTotal" => $totalRecords,
            "recordsFiltered" => $totalRecords,
            "data" => $data_arr,
            "dsfsd" => $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_chalan'))
        // {
        //     return redirect('/');
        // }
        //dd(request()->all());
       // dd(request()->all());
        $res_id=0;
        $req=null;
        $incentive_amount=0;
        if(isset(request()->requisition_id)){
            $res_id=request()->requisition_id;
            $req=Requisition::where('requisition_id',$res_id)->first();
            $paid_amount=$req->paid_amount;
            $incentive_amount=$req->total_incentive;
            $customers =Customer::where('customer_id',$req->customer_id)->first();
            $sales_man=Emplyoee::where('user_id',$req->sales_by)->first();
        }else{
            $customers =Customer::where('status',1)->get();
            $sales_man=Emplyoee::where('user_type',3)->get();
        }
        //$customers =Customer::where('status',1)->get();
        $couriers =Courier::where('status',1)->get();
        //$products=Product::get();
        $brands=Brand::where('status',1)->get();
        $categories=Category::where('status',1)->get();
        //$sales_man=Emplyoee::where('user_type',3)->get();
        return view("backend.chalan.create",['categories'=> $categories,'incentive_amount'=>$incentive_amount,'req'=>$req,'res_id'=>$res_id,'customers'=>$customers,'brands'=>$brands,'couriers'=>$couriers,'sales_man'=>$sales_man]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

       //$barcode = Barcode::where('product_id',$request->product_id[0])->where('color_id',$request->color[0])->get();
       //return json_decode($request->barcode,true);
        if($request->btn_value == "submit"){
            if($request->delivery_mode == 1){
                $validator = \Validator::make($request->all(), [
                    'requisition_date' => 'required',
                    'customer' => 'required',
                    'delivery_mode' => 'required',
                    'courier' => 'required',

                   'sales_man' => 'required',
                   'invoice_number' => 'required|unique:chalans|max:150',


                ]);
            }else{
                $validator = \Validator::make($request->all(), [
                    'requisition_date' => 'required',
                    'customer' => 'required',
                    'delivery_mode' => 'required',
                   'sales_man' => 'required',
                   'invoice_number' => 'required|unique:chalans|max:150',


                ]);
            }

        }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{

            $code=MCode::where('chalan_time',date("Y").date('m'))->first();
            $chalan_n=1;
            if($code){
                $chalan_n =str_pad($code->chanlan_code,4,0,STR_PAD_LEFT);
            }else{
                $chalan_n =str_pad($chalan_n,4,0,STR_PAD_LEFT);
            }


            try {
                DB::beginTransaction();
                $total_price=0;
                $total_quantity=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 += ($product->sale_price*$request->qty[$k]);
                }
                // $req=Requisition::where('requisition_id',$request->requisition_id)->first();
                // $req->is_challan=1;
                //$req->requistion_status = 4;
                // $req->save();
                $chalan =  new Chalan;
                $chalan->invoice_number = $request->invoice_number;
                $chalan->customer_id = $request->customer;
                // $chalan->requisition_id = $req->requisition_id;
                // $chalan->paid_amount = $req->paid_amount;
                // $chalan->incentive_amount = $req->total_incentive;
                $chalan->chalan_number = date("Y").date('m').$chalan_n;
                $chalan->chalan_date = Carbon::create($requisition_date[2].'-'.$requisition_date[1].'-'.$requisition_date[0],'Asia/Dhaka');
                $chalan->remarks = $request->remarks ? $request->remarks: '';
                //$requisition->total_amount = json_encode($request->product_color);
                if($request->delivery_mode)
                {
                    $chalan->delivery_mode = $request->delivery_mode;
                }

                if($request->delivery_mode == 1){
                    $chalan->courier_id = $request->courier;
                    //$requisition->bank_deposit_number = $new_name;
                    $chalan->track_no = $request->trackno ? $request->trackno : '';
                }
                if($request->btn_value == "draft"){
                    $chalan->chalan_status = 0;
                }else if($request->btn_value == "submit"){
                     $chalan->chalan_status = 1;
                }
               $chalan->total_quantity =$total_quantity;
               $chalan->total_amount =$total_price;
                $chalan->sales_user_id =$request->sales_man;
                // $chalan->created_by = auth()->user()->user_id;
                // $chalan->created_at = auth()->user()->user_id;
                $chalan->save();
                $uid=$chalan->chalan_id;

                $i=0;
                $iemis=json_decode($request->barcode,true);
                foreach($request->product_id as $k=>$v){
                    $product=Product::where('product_id',$request->product_id[$i])->first();
                   // $r_details=$req->details->where('product_id',$v)->where('color_id',$request->color[$i])->sum('incentive_price');
                    $details = new ChalanDetails;

                    $details->chalan_id=$uid;
                    $details->product_id=$v;
                    $details->chalan_date = Carbon::create($requisition_date[2].'-'.$requisition_date[1].'-'.$requisition_date[0],'Asia/Dhaka');
                    $details->product_quantity=$request->qty[$i];
                    // $details->color_id=$request->color[$i];
                    // $details->brand_id=$request->brand[$i];
                    // $details->color_id=1;
                    // $details->brand_id=1;
                    $details->product_id=$request->product_id[$i];
                    $details->product_name=$product->product_name;
                    // $details->is_iemi=isset($iemis[$v.'_'.$request->color[$i]]) ? 1 : 0;
                    $details->product_unit_price=$product->sale_price;
                    $details->product_price=$request->qty[$i]*$product->sale_price;
                    // $details->incentive_price=$req->details->where('product_id',$v)->where('color_id',$request->color[$i])->sum('incentive_price');
                    $details->save();
                    $ch_details=$details->chalan_details_id;

                    // if(isset($iemis[$v.'_'.$request->color[$i]])){
                    //     foreach ($iemis[$v.'_'.$request->color[$i]] as $key => $imei) {
                    //        $product_iemi = ProductImei::where('imei_1',trim($imei))->orWhere('imei_2',trim($imei))->first();
                    //        $product_iemi->s_status=1;

                    //        $product_iemi->chalan_details_id=$ch_details;
                    //        $product_iemi->save();
                    //        //return $product_iemi;
                    //     }
                    // }
                    $barcode = Barcode::where('product_id',$request->product_id[$i])->first();
                    if($barcode->quantity < $request->qty[$i]){
                         DB::rollBack();
                        //  $c=Color::where('color_id',$request->color[$i])->first();
                         $msg=$product->product_name.' Quantity is higher than stock';
                         return response()->json(['errors'=>['error'=>$msg]]);
                    }

                    $barcode->quantity = $barcode->quantity-$request->qty[$i];
                    $barcode->save();

                    $i++;
                }
                if($code){
                    $code->chanlan_code=intval($code->chanlan_code)+1;
                    $code->save();
                   // MCode::where('id',1)->update(['chanlan_code'=>intval($code->chanlan_code)+1]);
                }else{
                    $code= MCode::first();
                    $code->chalan_time=date("Y").date('m');
                    $code->chanlan_code=2;
                    $code->save();
                    //MCode::where('id',1)->update(['chanlan_code'=>2,'chalan_time'=>date("Y").date('m')]);
                }
                if($request->btn_value == "submit"){

                    $employees=Emplyoee::where('user_type',2)->orwhere('user_type',1)->get();
                    foreach($employees as $employee){
                        $notification = new Notification;
                        $notification->message="New Chalan is Created";
                        $notification->notefication_date=Carbon::now('Asia/dhaka');
                        $notification->target_url=$uid;
                        $notification->type=2;
                        $notification->r_status=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\Chalan  $chalan
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //  if(!auth()->user()->canEvent('viewchalan'))
        // {
        //     return redirect('/');
        // }
        $chalan = Chalan::where('chalan_id',$id)->first();
        $copy="Office Copy";

        return view('backend.chalan.show',['chalan'=>$chalan,'copy'=>$copy]);
    }
    public function printChalan($id,$copy){
        if(!auth()->user()->canEvent('p_office_a') || !auth()->user()->canEvent('p_office_w') || !auth()->user()->canEvent('p_customer_copy'))
        {
            return redirect('/');
        }
        $chalan = Chalan::where('chalan_id',$id)->first();
        //dd($chalan);
        if($copy == 1){
            $copy="Office Copy-A";
         }else if($copy == 2){
            $copy="Office Copy-W";
         }else{
            $copy="Customer Copy";
         }
      //return view('backend.chalan.chalanInvoice',['chalan'=>$chalan,'copy'=>$copy]);
        $pdf = PDF::loadview('backend.chalan.chalanInvoice', compact('chalan', 'copy'))->setPaper('a4');
         @unlink('pdf/chalan/' . 'chalan.pdf');
           $pdf->save('pdf/chalan/' . 'chalan.pdf');
         return redirect('pdf/chalan/' . 'chalan.pdf');
        //   $pdf = PDF::loadView('pdf.sell.invoice', compact('chalan', 'copy'))->setPaper('a4');
        //  @unlink('pdf/chalan/' . 'chalan.pdf');
        //   $pdf->save('pdf/chalan/' . 'chalan.pdf');
        // return redirect('pdf/chalan/' . 'chalan.pdf');
        // return view('pdf.sell.invoice',['chalan'=>$chalan,'copy'=>$copy]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Chalan  $chalan
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // if(!auth()->user()->canEvent('edit_chalan'))
        // {
        //     return redirect('/');
        // }
        $chalan=Chalan::where('chalan_id',$id)->first();
        //dd($chalan->chalan_details[0]->imeis);
        $customers =Customer::get();
        $couriers =Courier::get();
        $brands=Brand::get();
        $categories=Category::where('status',1)->get();
        $sales_man=Emplyoee::where('user_type',3)->get();
        return view("backend.chalan.edit",['customers'=>$customers,'categories'=>$categories,'brands'=>$brands,'couriers'=>$couriers,'chalan'=>$chalan,'sales_man'=>$sales_man]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Chalan  $chalan
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Chalan $chalan)
    {

            $id=$request->chalan_id;
            $chalan =  Chalan::where('chalan_id',$request->chalan_id)->first();
            //$chalan->requisition_id='41sd';
           // return $chalan;
            $validator = \Validator::make($request->all(), [
                'requisition_date' => 'required',
                'customer' => 'required',
                'delivery_mode' => 'required',
                'sales_man' => 'required',
            //    'requisition_id' => 'required',
               'invoice_number' => 'required|max:150|unique:chalans,invoice_number,'.$id.',chalan_id',
                //'product_color' => 'required',
               // 'specification' => 'required',
               // 'bank_slip' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

            ]);


        if ($validator->fails())
        {
            return response()->json(['errors'=>$validator->errors()->all()]);
        }else{

            $code=MCode::first();
            try {
                DB::beginTransaction();
                $requisition_date=explode('-', $request->requisition_date);
                $total_price=0;
                $total_quantity=0;
                foreach($request->product_id as $k=>$v){
                    $product=Product::where('product_id',$v)->first();
                    $total_quantity += $request->qty[$k];
                    $total_price += ($product->sale_price*$request->qty[$k]);
                }
                 //return $request;
                $req=Requisition::where('requisition_id',$request->requisition_id)->first();
               // return $req;
                //$chalan->requisition_id= $request->requisition_id;

                $chalan->invoice_number = $request->invoice_number;
                $chalan->customer_id = $request->customer;
               // $chalan->chalan_number = date("Y").date('m').date('d').$code->chanlan_code;
                $chalan->chalan_date =  Carbon::create($requisition_date[2].'-'.$requisition_date[1].'-'.$requisition_date[0],'Asia/Dhaka');
                $chalan->remarks =  $request->remarks ? $request->remarks: '';
                //$requisition->total_amount = json_encode($request->product_color);
                if($request->delivery_mode)
                {
                    $chalan->delivery_mode = $request->delivery_mode;
                }

                if($request->delivery_mode == 1){
                    $chalan->courier_id = $request->courier;
                    //$requisition->bank_deposit_number = $new_name;
                    $chalan->track_no = $request->trackno;
                }

                     //$chalan->chalan_status = 1;


                $chalan->total_quantity =$total_quantity;
                $chalan->total_amount = $total_price;
                // $chalan->requisition_id = $req->requisition_id;
                // $chalan->paid_amount = $req->paid_amount;
                // $chalan->incentive_amount = $req->total_incentive;
                $chalan->sales_user_id =$request->sales_man;
                // $chalan->updated_by = auth()->user()->user_id;
                $chalan->save();
                $uid=$chalan->chalan_id;

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



                    $details->chalan_id=$uid;
                    $details->product_id=$v;
                    $details->chalan_date = Carbon::create($requisition_date[2].'-'.$requisition_date[1].'-'.$requisition_date[0],'Asia/Dhaka');
                    // $details->brand_id=$request->brand[$i];
                    $details->product_quantity=$request->qty[$i];
                    // $details->color_id=$request->color[$i];
                    // $details->color_id=1;
                    // $details->brand_id=1;
                    $details->product_name=$product->product_name;
                    // $details->is_iemi=isset($iemis[$v.'_'.$request->color[$i]]) ? 1 : 0;
                    $details->product_unit_price=$product->sale_price;
                    $details->product_price=$request->qty[$i]*$product->sale_price;
                    // $details->product_unit_price=$req->details->where('product_id',$v)->where('color_id',$request->color[$i])->sum('product_unit_price');
                    // $details->product_price=$request->qty[$i]*$req->details->where('product_id',$v)->where('color_id',$request->color[$i])->sum('product_unit_price');
                    // $details->incentive_price=$req->details->where('product_id',$v)->where('color_id',$request->color[$i])->sum('incentive_price');
                    $details->save();
                    $barcode = Barcode::where('product_id',$v)->first();
                    $barcode->quantity = $barcode->quantity-$request->qty[$i];
                    $barcode->save();
                    }else{
                        $qty=$request->qty[$i];

                        if($details->product_quantity > $qty){
                            $qty=$details->product_quantity-$qty;
                            $barcode = Barcode::where('product_id',$v)->first();
                            $barcode->quantity = $barcode->quantity+$qty;
                            $barcode->save();
                        }else if($details->product_quantity < $qty){
                            $qty=$qty-$details->product_quantity;
                            $barcode = Barcode::where('product_id',$v)->first();
                            $barcode->quantity = $barcode->quantity-$qty;
                            $barcode->save();
                        }
                        // $details->product_unit_price=$req->details->where('product_id',$v)->where('color_id',$request->color[$i])->sum('product_unit_price');
                        // $details->product_price=$request->qty[$i]*$req->details->where('product_id',$v)->where('color_id',$request->color[$i])->sum('product_unit_price');
                        $details->product_quantity=$request->qty[$i];
                        // $details->incentive_price=$req->details->where('product_id',$v)->where('color_id',$request->color[$i])->sum('incentive_price');
                        $details->save();


                    }






                    $i++;
                }
                if($request->btn_value == "submit"){
                     $employees=Emplyoee::where('user_type',2)->orwhere('user_type',1)->get();
                    foreach($employees as $employee){
                        $notification = new Notification;
                        $notification->message="New Chalan is Created";
                        $notification->notefication_date=Carbon::now('Asia/dhaka')->format('Y-m-d h:i:s a');
                        $notification->target_url=$uid;
                        $notification->type=2;
                        $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('user_type',2)->orwhere('user_type',1)->get();
                    foreach($employees as $employee){
                        $notification = new Notification;
                        $notification->message="New Chalan is updated";
                        $notification->notefication_date=Carbon::now('Asia/dhaka');
                        $notification->target_url=$uid;
                        $notification->type=2;
                        $notification->r_status=2;
                        $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']);
    }

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

VaKeR 2022