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/StockController.php
<?php

namespace App\Http\Controllers\Backend;

use App\Models\Stock;
use App\Models\StockColor;
use App\Models\Supplier;
use App\Models\Product;
use App\Models\Brand;
use App\Models\Barcode;
use App\Models\Color;
use App\Models\CNF;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ProuductImport;
use App\Models\StockDoa;
use App\Models\Customer;
use App\Models\StockDoaDetail;
use App\Models\ProductImei;
use DB;
use Carbon\Carbon;
use App\Http\Controllers\Controller;
use App\Models\Category;

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

    // }
    public function index()
    {
        //  if(!auth()->user()->canEvent('all_stock'))
        // {
        //     return redirect('/');
        // }
        return view('backend.stock.stock_in_list');
        // return view('stock.list');
    }
    public function all_stock_in_doa()
    {
        //  if(!auth()->user()->canEvent('all_stock'))
        // {
        //     return redirect('/');
        // }
        return view('backend.stock.stock_in_doa_list');
        // return view('stock.list');
    }
    function show_iemi_stock_in_list($id){
        // if(!auth()->user()->canEvent('show_iemi_stock_in_list'))
        // {
        //     return redirect('/');
        // }
        return view('backend.stock.stock_in_iemi_list',['id'=>$id]);
    }
    function get_iemi_stock_in(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

        $stock_id = $request->get('stock_id');
        $stockss=ProductImei::leftJoin('stock_colors','product_imeis.stock_color_id','stock_colors.stock_color_id')->where('stock_colors.stock_color_id',$stock_id);
        if($searchValue){
            $stockss=$stockss->where('product_imeis.imei_1', 'like', $searchValue . '%')
            ->orWhere('product_imeis.imei_2', 'like', $searchValue . '%');
        }
        $totalRecords = $stockss->count();
       //return $rowperpage;
        $stocks=$stockss;
        if($rowperpage != -1){
            $stocks= $stockss->skip($start)
           ->take($rowperpage);
        }

           $stocks=$stocks->get();
        //return $stocks;

        $data_arr=array();
        $sl=$start+1;
        foreach($stocks as $product_iemi){

             $data_arr[] = array(
                'sl'=>$sl,
                "stock_date" => $product_iemi->stock_color->stock->stock_date->format('d-m-Y'),
                "brand" => $product_iemi->product->brand->brand_name,
                "product_name" => $product_iemi->product->product_name,
                "carton_code" => $product_iemi->carton_code,
                "item_code" => $product_iemi->item_code,
                "model" => $product_iemi->model,
                "color" => $product_iemi->stock_color->color->color_name,
                "imei1" => $product_iemi->imei_1,
                "imei2" => $product_iemi->imei_2,
                "status" => $product_iemi->chalan_details_id == 0 ? "Not Sale" :"Sold",
            );
             $sl++;
        }
        $response = array(
            "draw" => intval($draw),
            "recordsTotal" => $totalRecords,
            "recordsFiltered" => $totalRecords,
            "data" => $data_arr,
            "starts" => $rowperpage
        );

        echo json_encode($response);
        exit;
    }

    function get_all_stock(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 =StockColor::get()
        ->unique(function ($item) {
            return $item['stock_id'].$item['product_id'];
        })->count();
        $stocks=StockColor::get()
        ->unique(function ($item) {
            return $item['stock_id'].$item['product_id'];
        }) ->skip($start)
           ->take($rowperpage);
        // $products =Product::orderBy($columnName,'desc')
        //     ->where('product_id', 'like', '%' .$searchValue . '%')
        //     ->orWhere('product_name', 'like', '%' .$searchValue . '%')
        //     //->orWhere('model_no', 'like', '%' .$searchValue . '%')
        //     ->orWhere('purchase_price', 'like', '%' .$searchValue . '%')
        //     ->orWhere('sale_price', 'like', '%' .$searchValue . '%')
        //     ->orWhere('wholesale_price', 'like', '%' .$searchValue . '%')
        //     //->orderBy('product_id','asc')
        //     ->skip($start)
        //     ->take($rowperpage)
        //     ->get();
        $data_arr = array();
        $colors=Color::get();
        $i=1;
        foreach($stocks as $stock_color){






           $arr=array(
                "SL" => $i,
                "Date" => $stock_color->stock->stock_date->format('d-m-Y'),
                "Bill No" => $stock_color->stock->bill_no,
                "Supplier Name" => $stock_color->stock->supplier->supplier_name,
                "C&F Name" => $stock_color->stock->cnf->cnf_name,
                "Brand" => $stock_color->product->brand->brand_name,
                "Product Name" => $stock_color->product->product_name,
                "Model" => $stock_color->product->model->model_name,
                "Specification" => $stock_color->product->specification,

            );
           $total=0;
           $action="";
           if($stock_color->stock->is_iemi == 1){
                $action ='<div role="group" aria-label="Basic example" class="btn-group btn-group-sm"> ';
            if(auth()->user()->canEvent('show_iemi_stock_in_list'))
           {
             $action .='<a href="'.url('show_iemi_stock_in_list/'.$stock_color->stock->stock_id).'" class="mr-2">
                                                        IMEI List
                                                    </a> ';
            }
            $action .='
                                                </div>';
           }
           foreach ($colors as $key => $color) {

                $qty=$stock_color->stock->details->where('color_id',$color->color_id)->where('product_id',$stock_color->product_id)->sum('product_quantity');
                $arr[$color->color_name]=$qty;
                $total += $qty;
            }
            $doa=$stock_color->stock->doa->where('product_id',$stock_color->product_id);
            $arr['DOA']=$doa->sum('doa_quantity');
            $mis=$doa->sum('m_quantity');
            $arr['Missing Qty']=$mis;
            $arr['Remarks']=$stock_color->stock->remarks;
            $arr['Received Quantity']=$total+$mis;
            $arr['Total']=$total;
            $arr['Action']=$action;




            $data_arr[] = $arr;
            $i++;
        }
        $response = array(
            "draw" => intval($draw),
             "logo" =>  $request->get('logo'),
            "recordsTotal" => $totalRecords,
            "recordsFiltered" => $totalRecords,
            "data" => $data_arr
        );

        echo json_encode($response);
        exit;
    }
    function get_all_stock_in(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

        $stocks = Stock::orderBy($columnName,$columnSortOrder)
                ->leftJoin('suppliers','stocks.supplier_id','suppliers.supplier_id')
                // ->leftJoin('c_n_f_s','stocks.cnf_id','c_n_f_s.cnf_id')
                ->Where('suppliers.supplier_name', 'like', $searchValue . '%')
                // ->Where('c_n_f_s.cnf_name', 'like', $searchValue . '%')
                ->Where('stocks.stock_date', 'like', $searchValue . '%')
                ->Where('stocks.bill_no', 'like', $searchValue . '%');
        $totalRecords =$stocks->count();
        $stocks =$stocks->skip($start)
            ->take($rowperpage)
            ->get();


        $data_arr = array();

        $i=1;
        foreach($stocks as $stock){






           $arr=array(
                "stock_id" => $i,
                "stock_date" => $stock->stock_date->format('d-m-Y'),
                "bill_no" => $stock->bill_no,
                "supplier_name" => $stock->supplier->supplier_name,
                // "cnf_name" => $stock->cnf->cnf_name,
                "quantity" => $stock->quantity,

            );
           $total=0;
           $action="";
           $action ='<div role="group" aria-label="Basic example" class="btn-group btn-group-sm"> ';


        //     if(auth()->user()->canEvent('edit_stock_in'))
        //    {
             $action .='<a href="'.url('admin/edit_stock_in/'.$stock->stock_id).'" class="mr-2">
                                                        <i class="fa fa-edit text-warning"></i>
                                                    </a> ';
            // }

            // if(auth()->user()->canEvent('view_stock_in'))
            // {
                $action .=' <a href="'.url('admin/view_stock_in/'.$stock->stock_id).'" class="mr-2">
                                                            <i class="fa fa-eye"></i>
                                                        </a>';
            // }
            $action .='
                                                </div>';

            // $doa=$stock->doa;
            // $arr['DOA']=$doa ? $doa->doa_quantity : 0;
            // $mis=$doa ? $doa->m_quantity : 0;
            // $arr['Missing Qty']=$mis;
            // $arr['Received Quantity']=$total;
            // $arr['Total']=$stock->quantity-$mis;
            $arr['Action']=$action;




            $data_arr[] = $arr;
            $i++;
        }
        $response = array(
            "draw" => intval($draw),
             "logo" =>  $request->get('logo'),
            "recordsTotal" => $totalRecords,
            "recordsFiltered" => $totalRecords,
            "data" => $data_arr
        );

        echo json_encode($response);
        exit;
    }
    function get_all_stock_in_doa(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
        if($columnName == 'created_at'){
            $columnName="stock_doas.created_at";
        }
        \DB::connection()->enableQueryLog();
        $stockDoas = StockDoa::orderBy($columnName,$columnSortOrder)
        ->leftJoin('stocks','stocks.stock_id','stock_doas.stock_id')
            ->leftJoin('suppliers','suppliers.supplier_id','stocks.supplier_id')
            ->leftJoin('c_n_f_s','c_n_f_s.cnf_id','stocks.cnf_id')
            ->select('stock_doas.*','stocks.stock_date','stocks.bill_no','suppliers.supplier_name','c_n_f_s.cnf_name');
            $ssr="";
            if($columnName_arr[0]['search']['value'] != null){
                $stockDoas=$stockDoas->Where('stock_doa_id', 'like', $columnName_arr[0]['search']['value'] . '%');
            }
            if($columnName_arr[1]['search']['value'] != null){
               // $stockDoas=$stockDoas->Where('stock_doas.created_at', 'like', $columnName_arr[1]['search']['value'] . '%');
                $c_arr=explode('-',$columnName_arr[1]['search']['value']);

                $stockDoas=$stockDoas->whereDate('stock_doas.created_at', Carbon::create($c_arr[2].'-'.$c_arr[1].'-'.$c_arr[0])->toDateString());
                $ssr=Carbon::create($c_arr[2].'-'.$c_arr[1].'-'.$c_arr[0])->toDateString();
            }
            if($columnName_arr[2]['search']['value'] != null){
                $s_arr=explode('-',$columnName_arr[2]['search']['value']);

                $stockDoas=$stockDoas->Where('stock_date', $s_arr[2].'-'.$s_arr[1].'-'.$s_arr[0]);
            }
            if($columnName_arr[3]['search']['value'] != null){
                $stockDoas=$stockDoas->Where('bill_no', 'like', $columnName_arr[3]['search']['value'] . '%');
            }
            if($columnName_arr[4]['search']['value'] != null){
                $stockDoas=$stockDoas->Where('supplier_name', 'like', $columnName_arr[4]['search']['value'] . '%');
            }
            if($columnName_arr[5]['search']['value'] != null){
                $stockDoas=$stockDoas->Where('cnf_name', 'like', $columnName_arr[5]['search']['value'] . '%');
            }
            if($columnName_arr[6]['search']['value'] != null){
                $stockDoas=$stockDoas->Where('remarks', 'like', $columnName_arr[6]['search']['value'] . '%');
            }


                // ->leftJoin('suppliers','stocks.supplier_id','suppliers.supplier_id')
                // ->leftJoin('c_n_f_s','stocks.cnf_id','c_n_f_s.cnf_id')
                // ->Where('suppliers.supplier_name', 'like', $searchValue . '%')
                // ->Where('c_n_f_s.cnf_name', 'like', $searchValue . '%')
                // ->Where('stocks.stock_date', 'like', $searchValue . '%')
                // ->Where('stocks.bill_no', 'like', $searchValue . '%');
        $totalRecords =$stockDoas->count();
        $stockDoas =$stockDoas->skip($start)
            ->take($rowperpage)
            ->get();

        $queries = \DB::getQueryLog();
        $data_arr = array();

        $i=1;
        foreach($stockDoas as $stockDoa){






           $arr=array(
                "stock_doa_id" => $stockDoa->stock_doa_id,
                "created_at" => $stockDoa->created_at->format('d-m-Y'),
                "stock_date" => $stockDoa->stock->stock_date->format('d-m-Y'),
                "bill_no" => $stockDoa->stock->bill_no,
                "supplier_name" => $stockDoa->stock->supplier->supplier_name,
                "cnf_name" => $stockDoa->stock->cnf->cnf_name,
                "customer_name" => $stockDoa->customer ? $stockDoa->customer->customer_name : '',
                "doa_quantity" => $stockDoa->doa_quantity,
                "m_quantity" => $stockDoa->m_quantity,
                "remarks" => $stockDoa->remarks,
            );
           $total=0;
           $action="";
           $action ='<div role="group" aria-label="Basic example" class="btn-group btn-group-sm"> ';


            if(auth()->user()->canEvent('edit_doa'))
            {
             $action .='<a href="'.url('edit_stock_in_doa/'.$stockDoa->stock_doa_id ).'" class="mr-2">
                                                        <i class="fa fa-edit text-warning"></i>
                                                    </a>';
            }

            if(auth()->user()->canEvent('view_doa'))
            {
                $action .=' <a href="'.url('view_stock_in_doa/'.$stockDoa->stock_doa_id).'" class="mr-2">
                                                            <i class="fa fa-eye"></i>
                                                        </a>';
            }
            // if($stockDoa->doa_quantity-$stockDoa->doa_q_a > 0 || $stockDoa->m_quantity-$stockDoa->missing_q_a > 0){
            //     $action .=' <a class="btn btn-success" href="'.url('adjust_stock_doa/'.$stockDoa->stock_doa_id).'" class="mr-2">
            //                                                 Adjust
            //                                             </a>';
            // }

            $action .='
                                                </div>';


            $arr['Action']=$action;




            $data_arr[] = $arr;
            $i++;
        }
        $response = array(
            "draw" => intval($draw),
             "logo" =>  $request->get('logo'),
            "recordsTotal" => $totalRecords,
            "recordsFiltered" => $totalRecords,
            "data" => $data_arr,
            'ss'=>$queries
        );

        echo json_encode($response);
        exit;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        // if(!auth()->user()->canEvent('add_stock'))
        // {
        //     return redirect('/');
        // }
        $Suppliers =Supplier::get();
        $cnfs=CNF::get();
        $categories=Category::get();
        return view("backend.stock.create",['cnfs'=>$cnfs,'categories'=>$categories,'suppliers'=>$Suppliers,'categories'=>$categories]);
    }
    public function createiemi()
    {
        if(!auth()->user()->canEvent('add_iemi'))
        {
            return redirect('/');
        }
        $suppliers =Supplier::get();
        $cnfs=CNF::get();
        $brands=Brand::get();
      //$product=Product::where('product_id',1)->first();
       // dd(in_array(0,));


        return view("stock.createiemi",['cnfs'=>$cnfs,'suppliers'=>$suppliers,'brands'=>$brands]);
    }
    public function createStockInAc()
    {
        $Suppliers =Supplier::get();
        $products=Product::get();
        return view("stock.createAC",['products'=>$products,'suppliers'=>$Suppliers]);
    }
    public function createStockInDoa()
    {
        if(!auth()->user()->canEvent('add_doa'))
        {
            return redirect('/');
        }
        $Suppliers =Supplier::get();
        $customers =Customer::get();
        //$products=Product::get();
         $brands=Brand::get();
        return view("stock.createDoa",['customers'=>$customers,'brands'=>$brands,'suppliers'=>$Suppliers]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */

    public function importExcel(Request $request)
    {

        //  $res = [];
        //   Excel::toArray([], request()->file('import_file'));
        // Excel::load(request()->file('import_file'), function($reader) use( &$res ) {
        //     $reader = $reader->getSheet(0);
        //     $res = $reader->toArray();
        // });
        if($request->is_import == 0){
            $datas=Excel::toArray([], request()->file('import_file'));
            $ms=6;
            if(sizeof($datas[0][0]) >= 6){
               //return sizeof($datas[0]);
                $color=Color::select('color_id','color_name')->get()->groupBy('color_name')->toArray();
                $product=Product::where('product_id',$request->product)->first();
                $product_color=json_decode($product->product_color);
                return view('stock.import_data',['product_color'=>$product_color,'color'=>$color,'totalQty'=>sizeof($datas[0])-1,'datas'=>json_encode($datas[0])]);
            }else{
                return "this is correct column. Need ".($ms-sizeof($datas[0][0])).' columns';
            }
        }else{
           // return Excel::toArray(new ProuductImport, request()->file('import_file'));
            if ($request->errorvalid)
            {
                return response()->json(['errors'=>'Excel file has Error']);
            }else{



            try {

                $validator = \Validator::make($request->all(), [
                    'supplier' => 'required',
                    'stock_date' => 'required',
                    'bill_no' => 'required',
                    'cnf' => 'required',

                ]);
                if ($validator->fails())
                {
                    return response()->json(['errors'=>$validator->errors()->all()]);
                }else{
                    try{
                        DB::beginTransaction();
                        $totalqty=0;
                        $totalprice=0;
                       $stock_date=explode('-',$request->stock_date);
                        $product=Product::where('product_id',$request->product)->first();
                        $stock=Stock::where('stock_date',$stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0])->where('supplier_id',$request->supplier)->where('bill_no',$request->bill_no)->where('cnf_id',$request->cnf)->first();
                        if($stock){

                            $stock->quantity = $stock->quantity+$request->quantity;
                            $stock->updated_by = auth()->user()->user_id;
                        }else{
                            $stock =  new Stock;
                            $stock->supplier_id = $request->supplier;
                            $stock->stock_date = $stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0];
                            $stock->bill_no = $request->bill_no;
                            $stock->cnf_id = $request->cnf;
                            $stock->quantity = $request->quantity;
                            $stock->price = $product->purchase_price*$request->quantity;
                            $stock->created_by = auth()->user()->user_id;
                        }

                        $stock->is_iemi =1;



                        $stock->save();
                        $uid=$stock->stock_id;

                        foreach ($request->color as $key => $value) {


                        $product=Product::where('product_id',$request->product)->first();
                         $stockColor=StockColor::where('stock_id',$uid)->where('product_id',$product)->where('color_id',$key)->first();
                         if($stockColor){
                                $stockColor->is_iemi =1;
                                $stockColor->product_quantity=$stockColor->product_quantity+$value;
                         }else{
                            $stockColor = new StockColor;

                            $stockColor->stock_id=$uid;
                            $stockColor->product_id=$request->product;
                            $stockColor->stock_date = $stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0];
                            $stockColor->category_id=$product->category_id;
                            $stockColor->brand_id=$product->brand_id;
                            $stockColor->product_quantity=$value;
                            $stockColor->is_iemi =1;
                            $stockColor->color_id=$key;
                            $stockColor->created_by = auth()->user()->user_id;
                         }

                        $stockColor->save();
                        $stock_c_id=$stockColor->stock_color_id;
                        //return $stock_c_id;
                        Excel::import(new ProuductImport($request->product,$stock_c_id,$key), request()->file('import_file'));
                        $barcode =  Barcode::where('product_id',$request->product)->where('color_id',$request->key)->where('is_iemi',1)->first();
                        if($barcode == null){
                            $barcode = new Barcode;
                            $barcode->product_id=$request->product;
                            $barcode->quantity=$value;
                            $barcode->color_id=$key;
                            $barcode->is_iemi =1;
                            // $barcode->sale_price= $product->sale_price;
                            // $barcode->wholesale_price=$product->wholesale_price;
                            // $barcode->purchase_price=$product->purchase_price;
                            // $q=array();
                            // $q[$product->purchase_price]=$value;
                            // $barcode->purchase_quantity=json_encode($q);
                            //$barcode->created_by = auth()->user()->user_id;
                            $barcode->save();
                        }else{
                            //$barcode->product_id=$v;
                            $barcode->quantity=$barcode->quantity+$value;
                           // $barcode->color=$request->color[$i];
                            // $barcode->sale_price= $product->sale_price;
                            // $barcode->wholesale_price=$product->wholesale_price;
                            // $barcode->purchase_price=$product->purchase_price;;
                            // $oldq= json_decode($barcode->purchase_quantity, true);
                            // if(isset($oldq[$product->purchase_price])){
                            //     $oldq[$product->purchase_price]=$oldq[$product->purchase_price]+$value;
                            // }else{
                            //     $oldq[$product->purchase_price]=$value;
                            // }

                            // $barcode->purchase_quantity=json_encode($oldq);
                            //$barcode->created_by = auth()->user()->user_id;
                            $barcode->save();

                        }
                    }
                       DB::commit();
                    } catch (\PDOException $e) {
                        // Woopsy
                        DB::rollBack();
                    return response()->json(['errors'=>$e]);
                   }
                }



            } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
                $failures = $e->failures();
                $arr=array();
                $arr["errors"]=1;
                foreach ($failures as $failure) {
                    $arr['error'][]=$failure->errors();
                    $arr['row'][]= $failure->row();
                    $arr['keys'][]= $failure->attribute();
                    $arr['values'][]= $failure->values();

                }
                return  $arr;
            }


           return response()->json(['errors'=>'0','success'=>'Records is successfully Imported']);
       }
        }



    }
    public function store(Request $request)
    {

        $validator = \Validator::make($request->all(), [
            'supplier' => 'required',
            'stock_date' => 'required',
            'bill_no' => 'required',

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

           try {
                DB::beginTransaction();
                $stock_date=explode('-',$request->stock_date);
                $totalqty=0;
                $totalprice=0;
                foreach($request->product_id as $k=>$v){
                    $product=Product::where('product_id',$v)->first();
                    $totalqty += $request->qty[$k];
                    $totalprice += $request->total_purchase_price[$k];
                    $product->purchase_price = $request->purchase_price[$k];
                    $product->save();
                }
                $stock =  new Stock;
                $stock->supplier_id = $request->supplier;
                $stock->stock_date = $stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0];
                $stock->bill_no = $request->bill_no;
                // $stock->cnf_id = $request->cnf;
                $stock->quantity = $totalqty;
                $stock->price = $totalprice;

                // $stock->created_by = auth()->user()->user_id;
                $stock->save();
                $uid=$stock->stock_id;

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

                    $stockColor->stock_id=$uid;
                    $stockColor->product_id=$v;
                    // $stockColor->stock_date = $stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0];
                    // $stockColor->category_id=$product->category_id;
                    // $stockColor->brand_id=$product->brand_id;
                    $stockColor->product_quantity=$request->qty[$i];
                    // $stockColor->color_id=$request->color[$i];
                    // $stockColor->created_by = auth()->user()->user_id;
                    $stockColor->save();
                  $barcode =  Barcode::where('product_id',$v)->first();
                    if($barcode == null){
                        $barcode = new Barcode;
                        $barcode->product_id=$v;
                        $barcode->quantity=$request->qty[$i];
                        // $barcode->color_id=$request->color[$i];
                        // $barcode->sale_price= $product->sale_price;
                        // $barcode->wholesale_price=$product->wholesale_price;
                        // $barcode->purchase_price=$product->purchase_price;
                        $q=array();
                        $q[$product->purchase_price]=$request->qty[$i];
                        $barcode->purchase_quantity=json_encode($q);
                        //$barcode->created_by = auth()->user()->user_id;
                        $barcode->save();
                    }else{
                    //$barcode->product_id=$v;
                    $barcode->quantity=$barcode->quantity+$request->qty[$i];
                   // $barcode->color=$request->color[$i];
                    // $barcode->sale_price= $product->sale_price;
                    // $barcode->wholesale_price=$product->wholesale_price;
                    // $barcode->purchase_price=$product->purchase_price;;
                    // $oldq= json_decode($barcode->purchase_quantity, true);
                    // if(isset($oldq[$product->purchase_price])){
                    //     $oldq[$product->purchase_price]=$oldq[$product->purchase_price]+$request->qty[$i];
                    // }else{
                    //     $oldq[$product->purchase_price]=$request->qty[$i];


                    // }

                    // $barcode->purchase_quantity=json_encode($oldq);
                    //$barcode->created_by = auth()->user()->user_id;
                    $barcode->save();
                    }




                    $i++;
                }

               DB::commit();
            } catch (\PDOException $e) {
                // Woopsy
                DB::rollBack();
            return response()->json(['errors'=>$e]);
           }


        }
        return response()->json(['errors'=>'0','success'=>'Record is successfully added']);
    }
    public function storeStockInDoa(Request $request)
    {

        //return Carbon::parse($stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0]);
        $validator = \Validator::make($request->all(), [
            'supplier' => 'required',
            'stock_date' => 'required',
            'bill_no' => 'required',
            //'cnf' => 'required',

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

           try {
                DB::beginTransaction();
              $stock_date=explode('-',$request->stock_date);
                $stock =  Stock::where('stock_date',Carbon::parse($stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0]))->where('bill_no',$request->bill_no)->where('supplier_id',$request->supplier)->first();
                if($stock)
                {
                    $doatotal=0;$m_total=0;
                    $i=0;
                    foreach ($request->qty as $key => $value) {
                        if($request->type[$i] == 1){
                            $doatotal += $value;
                        }else{
                            $m_total += $value;
                        }
                        $i++;
                    }
                    $stockDoa = new StockDoa;
                    $stockDoa->stock_id=$stock->stock_id;
                    $stockDoa->customer_id=0;
                    $stockDoa->doa_quantity=$doatotal;
                    $stockDoa->m_quantity=$m_total;
                    $stockDoa->created_at = Carbon::now('Asia/dhaka');
                    $stockDoa->created_by = auth()->user()->user_id;
                    $stockDoa->save();
                    $stock_doa_id=$stockDoa->stock_doa_id;

                        $i=0;
                    foreach($request->product_id as $k=>$v){
                        $stockDoaDetail = new StockDoaDetail;
                        $stockDoaDetail->stock_doa_id=$stock_doa_id;
                        $stockDoaDetail->product_id=$v;
                        $stockDoaDetail->color_id=$request->color_id[$i];
                        if($request->type[$i] == 1){
                            $stockDoaDetail->doa=$request->qty[$i];
                        }else{
                            $stockDoaDetail->missing=$request->qty[$i];
                        }
                        $stockDoaDetail->created_by = auth()->user()->user_id;
                        $stockDoaDetail->save();
                        if($request->type[$i] != 1){
                            $barcode =  Barcode::where('product_id',$v)->where('color_id',$request->color_id[$i])->first();
                            $barcode->quantity=$barcode->quantity-$request->qty[$i];
                            $barcode->save();
                        }
                        $i++;
                    }
                }else{
                    return response()->json(['errors'=>1,'msg'=>"Bill no. , Supplier id or date is not match in stock"]);
                }



               DB::commit();
            } catch (\PDOException $e) {
                // Woopsy
                DB::rollBack();
            return response()->json(['errors'=>$e]);
           }


        }
        return response()->json(['errors'=>'0','success'=>'Record is successfully added']);
    }
    public function storeStockInAc(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'supplier' => 'required',

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

            try {
                DB::beginTransaction();
                $totalqty=0;
                foreach($request->qty as $k=>$v){
                    $totalqty += $v;
                }
                $stock =  new Stock;
                $stock->supplier_id = $request->supplier;
                $stock->quantity = $totalqty;
                $stock->price = 0;

                $stock->created_by = auth()->user()->user_id;
                $stock->save();
                $uid=$stock->stock_id;

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

                    $stockColor->stock_id=$uid;
                    $stockColor->product_id=$v;
                     $stockColor->category_id=$product->category_id;
                        $stockColor->brand_id=$product->brand_id;
                    $stockColor->product_quantity=$request->qty[$i];
                    //$stockColor->product_color=$request->color[$i];
                    $stockColor->created_by = auth()->user()->user_id;
                    $stockColor->save();

                    $i++;
                }

                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\Stock  $stock
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // if(!auth()->user()->canEvent('view_stock_in'))
        // {
        //     return redirect('/');
        // }
        $stock=Stock::where('stock_id',$id)->first();
     //dd($stock->doa->details->where('product_id',4)->where('color_id',1)[0]->missing);
        return view('backend.stock.show_stock_in',['stock'=>$stock]);
    }
    public function showDoa($id)
    {
        if(!auth()->user()->canEvent('view_doa'))
        {
            return redirect('/');
        }
        $stockDoa=StockDoa::where('stock_doa_id',$id)->first();
        //dd($stockDoa->details);
        return view('stock.show_stock_doa',['stockDoa'=>$stockDoa]);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Stock  $stock
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // if(!auth()->user()->canEvent('edit_stock_in'))
        // {
        //     return redirect('/');
        // }
        $Suppliers =Supplier::get();
        $cnfs=CNF::get();
        $brands=Brand::get();
        $categories=Category::get();
        $stock=Stock::where('stock_id',$id)->first();
        return view("backend.stock.edit_stock_in",['stock'=>$stock,'cnfs'=>$cnfs,'suppliers'=>$Suppliers,'brands'=>$brands,'categories'=>$categories]);

       //return view('stock.edit_stock_in',['stock'=>$stock]);
    }
    public function editDoa($id)
    {
        if(!auth()->user()->canEvent('edit_doa'))
        {
            return redirect('/');
        }
        $Suppliers =Supplier::get();
        $customers =Customer::get();
        $cnfs=CNF::get();
        $brands=Brand::get();
        $stockDoa=StockDoa::where('stock_doa_id',$id)->first();
        return view("stock.edit_stock_doa",['customers'=>$customers,'stockDoa'=>$stockDoa,'cnfs'=>$cnfs,'suppliers'=>$Suppliers,'brands'=>$brands]);

       //return view('stock.edit_stock_in',['stock'=>$stock]);
    }
     public function adjust_stock_doa($id)
    {
        if(!auth()->user()->canEvent('add_stock'))
        {
            return redirect('/');
        }
        $Suppliers =Supplier::get();

        $stockDoa=StockDoa::where('stock_doa_id',$id)->first();
        return view("stock.stock_doa_adjust",['stockDoa'=>$stockDoa,'suppliers'=>$Suppliers]);

       //return view('stock.edit_stock_in',['stock'=>$stock]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Stock  $stock
     * @return \Illuminate\Http\Response
     */
        public function update(Request $request)
    {
        //return $request;
        $stock_date=explode('-',$request->stock_date);
         $validator = \Validator::make($request->all(), [
            'supplier' => 'required',
            'stock_date' => 'required',
            'bill_no' => 'required',

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

           try {
                DB::beginTransaction();
                $totalqty=0;
                $totalprice=0;
                foreach($request->product_id as $k=>$v){
                    $product=Product::where('product_id',$v)->first();
                    $totalqty += $request->qty[$k];
                    $totalprice += $request->total_purchase_price[$k];
                    $product->purchase_price = $request->purchase_price[$k];
                    $product->save();
                }
                $haystack = $request->existcolor_id;

                $stock = Stock::where('stock_id',$request->stock_id)->first();
                $stock->supplier_id = $request->supplier;
                $stock->stock_date = $stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0];
                $stock->bill_no = $request->bill_no;
                // $stock->cnf_id = $request->cnf;
                $stock->quantity = $totalqty;
                $stock->price = $totalprice;

                // $stock->created_by = auth()->user()->user_id;
                $stock->save();
                $uid=$stock->stock_id;

                $i=0;
                foreach($request->product_id as $k=>$v){
                    $is_exist=0;
                    $aq=0;
                    $product=Product::where('product_id',$v)->first();
                    $stockColor=StockColor::where('stock_id',$uid)->where('product_id',$v)->first();
                    if($stockColor){
                        if($stockColor->product_quantity > $request->qty[$i]){
                            $is_exist=1;
                            $aq=$stockColor->product_quantity-$request->qty[$i];
                        }else{
                            $is_exist=2;
                            $aq=$request->qty[$i]-$stockColor->product_quantity;
                        }
                        $stockColor->product_quantity=$request->qty[$i];

                        // $stockColor->updated_by = auth()->user()->user_id;

                    }else{
                        $stockColor = new StockColor;

                        $stockColor->stock_id=$uid;
                        $stockColor->product_id=$v;
                        // $stockColor->stock_date = $request->stock_date;
                        // $stockColor->category_id=$product->category_id;
                        // $stockColor->brand_id=$product->brand_id;
                        $stockColor->product_quantity=$request->qty[$i];
                        // $stockColor->color_id=$request->color[$i];
                        // $stockColor->created_by = auth()->user()->user_id;

                    }
                    $stockColor->save();
                    if (($key = array_search( $stockColor->stock_color_id, $haystack)) !== FALSE) {
                      unset($haystack[$key]);
                    }

                  $barcode =  Barcode::where('product_id',$v)->first();
                    if($barcode == null){
                        $barcode = new Barcode;
                        $barcode->product_id=$v;
                        $barcode->quantity=$request->qty[$i];
                        // $barcode->color_id=$request->color[$i];
                        // $barcode->sale_price= $product->sale_price;
                        // $barcode->wholesale_price=$product->wholesale_price;
                        // $barcode->purchase_price=$product->purchase_price;
                        // $q=array();
                        $q[$product->purchase_price]=$request->qty[$i];
                        $barcode->purchase_quantity=json_encode($q);
                        //$barcode->created_by = auth()->user()->user_id;
                        $barcode->save();
                    }else{
                        if($is_exist == 0){
                             //$barcode->product_id=$v;
                            $barcode->quantity=$barcode->quantity+$request->qty[$i];
                           // $barcode->color=$request->color[$i];
                           // $barcode->sale_price= $product->sale_price;
                          //  $barcode->wholesale_price=$product->wholesale_price;
                           // $barcode->purchase_price=$product->purchase_price;;
                            // $oldq= json_decode($barcode->purchase_quantity, true);
                            // if(isset($oldq[$product->purchase_price])){
                            //     $oldq[$product->purchase_price]=$oldq[$product->purchase_price]+$request->qty[$i];
                            // }else{
                            //     $oldq[$product->purchase_price]=$request->qty[$i];


                            // }

                            // $barcode->purchase_quantity=json_encode($oldq);
                            //$barcode->created_by = auth()->user()->user_id;
                            $barcode->save();
                        }else{
                             //$barcode->product_id=$v;
                            if($is_exist == 1){
                                $barcode->quantity=$barcode->quantity-$aq;
                            }else{
                                $barcode->quantity=$barcode->quantity+$aq;
                            }

                           // $barcode->color=$request->color[$i];
                            // $barcode->sale_price= $product->sale_price;
                            // $barcode->wholesale_price=$product->wholesale_price;
                            // $barcode->purchase_price=$product->purchase_price;;
                            // $oldq= json_decode($barcode->purchase_quantity, true);
                            // if(isset($oldq[$product->purchase_price])){
                            //     $oldq[$product->purchase_price]=$oldq[$product->purchase_price]+$request->qty[$i];
                            // }else{
                            //     $oldq[$product->purchase_price]=$request->qty[$i];


                            // }

                            // $barcode->purchase_quantity=json_encode($oldq);
                            //$barcode->created_by = auth()->user()->user_id;
                            $barcode->save();
                        }

                    }




                    $i++;
                }
                foreach($haystack as $k=>$v){
                    $stockColor=StockColor::where('stock_color_id',$v)->first();
                    $stockColor->delete();
                }

               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 updateDoa(Request $request)
    {
        //return $request;
          $stock_date=explode('-',$request->stock_date);
        //return Carbon::parse($stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0]);
        $validator = \Validator::make($request->all(), [
            'supplier' => 'required',
            'stock_date' => 'required',
            'bill_no' => 'required',
            //'cnf' => 'required',

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

           try {
                DB::beginTransaction();

                $stock =  Stock::where('stock_date',Carbon::parse($stock_date[2].'-'.$stock_date[1].'-'.$stock_date[0]))->where('bill_no',$request->bill_no)->where('supplier_id',$request->supplier)->first();
                if($stock)
                {
                    $doatotal=0;$m_total=0;
                    $i=0;
                    foreach ($request->qty as $key => $value) {
                        if($request->type[$i] == 1){
                            $doatotal += $value;
                        }else{
                            $m_total += $value;
                        }
                        $i++;
                    }
                    $stockDoa = StockDoa::where('stock_doa_id',$request->stock_doa_id)->first();
                    $stockDoa->stock_id=$stock->stock_id;
                    $stockDoa->customer_id=0;
                    $stockDoa->doa_quantity=$doatotal;
                    $stockDoa->m_quantity=$m_total;
                    $stockDoa->remarks=$request->remarks;
                    $stockDoa->updated_at = Carbon::now('Asia/dhaka');
                    $stockDoa->updated_by = auth()->user()->user_id;
                    $stockDoa->save();
                    $stock_doa_id=$stockDoa->stock_doa_id;

                        $i=0;
                    $haystack = $request->exist_id;
                    foreach($request->product_id as $k=>$v){
                        $stockDoaDetail=StockDoaDetail::where('stock_doa_id',$stock_doa_id)->where('product_id',$v)->where('color_id',$request->color_id[$i])->first();
                        if($stockDoaDetail){

                           $doaq=$stockDoaDetail->doa;
                            if($request->type[$i] == 1){
                                $stockDoaDetail->doa=$request->qty[$i];
                            }else{
                                $stockDoaDetail->missing=$request->qty[$i];
                            }
                            $stockDoaDetail->updated_by = auth()->user()->user_id;
                            $stockDoaDetail->save();
                            if($request->type[$i] != 1){
                                $dq=0;
                                if($doaq > $request->qty[$i]){
                                    $barcode =  Barcode::where('product_id',$v)->where('color_id',$request->color_id[$i])->first();
                                    $barcode->quantity=$barcode->quantity+($doaq - $request->qty[$i]);
                                    $barcode->save();
                                }else{
                                    $barcode =  Barcode::where('product_id',$v)->where('color_id',$request->color_id[$i])->first();
                                    $barcode->quantity=$barcode->quantity-($request->qty[$i] - $doaq);
                                    $barcode->save();
                                }

                            }
                        }else{
                            $stockDoaDetail = new StockDoaDetail;
                            $stockDoaDetail->stock_doa_id=$stock_doa_id;
                            $stockDoaDetail->product_id=$v;
                            $stockDoaDetail->color_id=$request->color_id[$i];
                            if($request->type[$i] == 1){
                                $stockDoaDetail->doa=$request->qty[$i];
                            }else{
                                $stockDoaDetail->missing=$request->qty[$i];
                            }
                            $stockDoaDetail->created_by = auth()->user()->user_id;
                            $stockDoaDetail->save();
                            if($request->type[$i] != 1){
                                $barcode =  Barcode::where('product_id',$v)->where('color_id',$request->color_id[$i])->first();
                                $barcode->quantity=$barcode->quantity-$request->qty[$i];
                                $barcode->save();
                            }

                        }

                        $i++;
                        if (($key = array_search($stockDoaDetail->stock_doa_detail_id, $haystack)) !== FALSE) {
                          unset($haystack[$key]);
                        }
                    }
                    foreach($haystack as $k=>$v){
                        $stockColor=stockDoaDetail::where('stock_doa_detail_id',$v)->first();
                        $stockColor->delete();
                    }
                    DB::commit();
                }else{
                    return response()->json(['errors'=>1,'msg'=>"Bill no. , Supplier id or date is not match in stock"]);
                }




            } catch (\PDOException $e) {
                // Woopsy
                DB::rollBack();
            return response()->json(['errors'=>$e]);
           }


        }
        return response()->json(['errors'=>'0','success'=>'Record is successfully updated']);
    }
    public function updateDoaAdjust(Request $request)
    {
        //return $request;



           try {
                DB::beginTransaction();


                    $doatotal=0;$m_total=0;$predoatotal=0;$pre_m_total=0;
                    $i=0;
                    foreach ($request->qty1 as $key => $value) {
                        if($request->type[$i] == 1){
                            $doatotal += $value;
                             $predoatotal += $request->preqty[$i];
                        }else{
                            $pre_m_total += $request->preqty[$i];
                            $m_total += $value;
                        }
                        $i++;
                    }
                    $stockDoa = StockDoa::where('stock_doa_id',$request->stock_doa_id)->first();

                    $stockDoa->doa_q_a=$predoatotal+$doatotal;
                    $stockDoa->missing_q_a=$pre_m_total+$m_total;
                    $stockDoa->adjust_at = Carbon::now('Asia/dhaka');
                    $stockDoa->adjust_by = auth()->user()->user_id;
                    $stockDoa->save();
                    $stock_doa_id=$stockDoa->stock_doa_id;

                        $i=0;

                    foreach($request->product_id as $k=>$v){
                        $stockDoaDetail=StockDoaDetail::where('stock_doa_detail_id',$request->exist_id[$i])->first();



                            if($request->type[$i] == 1){
                                $stockDoaDetail->doa_a= $request->preqty[$i]+$request->qty1[$i];
                            }else{
                                $stockDoaDetail->missing_a= $request->preqty[$i]+$request->qty1[$i];
                            }
                            $stockDoaDetail->adjust_by = auth()->user()->user_id;
                            $stockDoaDetail->save();


                        $i++;

                    }

                    DB::commit();





            } catch (\PDOException $e) {
                // Woopsy
                DB::rollBack();
            return response()->json(['errors'=>$e]);
           }



        return response()->json(['errors'=>'0','success'=>'Record is successfully updated']);
    }

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

VaKeR 2022