<?php



namespace App\Http\Controllers\Administrator;



use App\Fun\Fun;
use App\Model\product\ProductUnitModel;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use App\Model\stock_inventory\StockModel;

use App\Model\setup\WarehouseModel;

use App\Model\AdjustmentModel;

use App\Model\AdjustmentDetailModel;

use Illuminate\Support\Facades\DB;

use Yajra\DataTables\DataTables;

use Illuminate\Support\Facades\Auth;

use MongoDB\Driver\Session;

class AdjustmentController extends Controller

{

     function __construct()

      {

           $this->middleware('permission:Report Stocks', ['only' => ['index']]);

      }

    public function index(){



        return view('administrator.adjustment.index');

    }



    public function get_ajustment_stock()

    {

        Fun::lang();
        $data = DB::table('nso007_adjustment')

                ->join('nso007_adjustment_details','nso007_adjustment_details.adjustment_id','nso007_adjustment.id')

                ->join('nso007_warehouse','nso007_warehouse.id','nso007_adjustment.warehouse_id')

                ->select(

                    'nso007_adjustment.*','nso007_warehouse.warehouse_name',

                    DB::raw("SUM(nso007_adjustment_details.adjustment_qty) AS qty")

                )

                ->groupBy('nso007_adjustment_details.adjustment_id');



        return Datatables::of($data)

               ->addColumn('adjustment_date',function($data){

                    return date('d-m-Y',strtotime($data->adjustment_date));

               })

               ->addColumn('invoice_number',function($data){

                    return '<a href="#" title="Edit" class="button_info">'.$data->invoice_number.'</a>';

               })

               ->addColumn('action',function($data){

//                   <input data-id="{{'.$data->id.'}}" class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ '.$data->status.' ? "checked" : "" }}>



                    return '<a data-width="700px" data-href="'.route('adjustment.show',$data->id).'" class="button_info getHtmlFormShow">'.__('administrator.show').'</a>';

               })

               ->addIndexColumn()

               ->rawColumns(['invoice_number'=>'invoice_number','action'=>'action'])

               ->make(true);

    }





    public function base_on_warehouse(Request $request){

        $base_on_warehouse = $request->id;

        session()->put('base_on_warehouse', $base_on_warehouse);

        session::forget('stock_adjustment');

        echo json_encode($base_on_warehouse);



    }

    public function create(){

        $warehouse = WarehouseModel::where('status',1)->pluck('warehouse_name','id')->prepend('Please Select', '');

        return view('administrator.adjustment.create',compact('warehouse'));

    }

    public function adjustment_autocomplete(Request $request)

    {

        $products = StockModel::select(

            'nso007_stocks.product_id',

            'nso007_products.id',

            'nso007_products.product_name'

        )

        ->leftJoin('nso007_products', 'nso007_products.id', '=', 'nso007_stocks.product_id')

        ->where('nso007_stocks.warehouse_id',session()->get('base_on_warehouse'))

        ->where(function ($query) use ($request) {

            $query->orwhere("nso007_products.barcode", "LIKE", "%{$request->input('term')}%");

            $query->orwhere("nso007_products.product_name", "LIKE", "%{$request->input('term')}%");

        })

        ->get();

        $data = '<ul class="list-group" style="margin: 1px">';

        foreach($products as $product)

        {

            $img = DB::table('nso007_product_image')->where('product_id',$product->id)->first();

            $images = empty($img->images)?'placeholder.png':$img->images;

            $data.= '<li class="list-group-item">

                <img src="'.asset($images).'" style="height: 40px; width: 40px;">

                <span style="margin-left: 10px">'.$product->product_name.'</span>

                <button type="button" data-id="'.$product->id.'" class="add_adjustment button_primary pull-right" style="top: 3px;">

                    <i  class="fa fa-check"></i>

                </button>

            </li>';

        }

        $data.='</ul>';



        return response()->json(['html' => $data]);

    }

    public function adjustment_addcart(Request $request)

    {

            $messages = '';

            $product = StockModel::select(

                'nso007_stocks.product_id',

                'nso007_stocks.stock_qty',

                'nso007_products.id',

                // 'nso007_products.vendor_price',

                'nso007_products.qty',

                'nso007_products.product_name'

            )

            ->leftJoin('nso007_products', 'nso007_products.id', '=', 'nso007_stocks.product_id')

            ->where('nso007_stocks.warehouse_id',session()->get('base_on_warehouse'))

            ->where('nso007_products.id',$request->product_id)

            ->first();
            $stock_adjustment = session()->get('stock_adjustment');

            if(!$product) {

                $messages = 'The warehouse does not have product.';

            }else{

                if(isset($stock_adjustment[$request->product_id])) {

                    session()->put('stock_adjustment', $stock_adjustment);

                    $messages = 'Product is add already exist !';

                }else{

                    $stock_adjustment[$request->product_id] = [

                        "product_code" => $product->product_code,

                        "product_name" => $product->product_name,

                        "id" => $product->id,

                        'product_id' => $request->product_id,

                        "stock_qty" => $product->stock_qty,

                        "qty" => $product->qty,

                    ];

                    session()->put('stock_adjustment', $stock_adjustment);

                    $messages = 'success';

                }
            }

        echo json_encode($messages);

    }

    public function ajax_stock_adjustment()

    {

        $tbody = '';

        $i = 0;

        $data ='';

        if(session('stock_adjustment')){

            foreach (session('stock_adjustment') as $key => $value) {

                $unit = DB::table('nso007_product_unit')->where('product_id',$value['id'])->get();

                $i++;

                if(count($unit) == 1){

                    $data = '<option value="'.$unit[0]->qty_per_unit.'">'.$unit[0]->unit_name.'</option>';

                }else{

                    $data = '<option value="'.$unit[0]->qty_per_unit.'">'.$unit[0]->unit_name.'</option>

                            <option value="'.$unit[1]->qty_per_unit.'">'.$unit[1]->unit_name.'</option>

                            ';

                }



                if(@$unit[1]->qty_per_unit){

                    $qty_per_unit = $unit[1]->qty_per_unit;

                }else{

                    $qty_per_unit = 1;

                };

                $tbody .=   '<tr>

                                <td>'.$key.'</td>

                                <td>'.$value["product_code"].'<input type="hidden" class="qty" value="'.$value["stock_qty"].'">

                                <input type="hidden" name="one['.$key.']" class="qty_one" value="'.intval($value["stock_qty"]/$qty_per_unit).'">

                                <input type="hidden" name="qty_per_unit['.$key.']" class="qty_per_unit" value="'.$qty_per_unit.'">

                                </td>

                                <td><input type="text" class="form-control pro_name" value="'.$value["product_name"].'" readonly></td>

                                <td><input type="text" class="form-control stock_qty" value="'. intval($value["stock_qty"]/$qty_per_unit ).'" readonly></td>

                                <td><select class="select2 form-control unit" name="unit['.$key.']">'. $data .'</select></td>

                                <td>

                                    <select class="select2 form-control type" name="adjustment_type['.$key.']">

                                        <option value="">Please Select</option>

                                        <option value="Subtraction">Subtraction</option>

                                        <option value="Addition">Addition</option>

                                    </select>

                                </td>

                                <td><input type="text" class="form-control adjustment_qty" name="adjustment_qty['.$key.']"></td>

                                <td><a class="remove btn btn-danger btn-xs" data-product_id="'.$value["product_id"].'"><span class="fa fa-minus"></span></a></td>

                            </tr>';

            }

        }

        echo $tbody;

    }

    public function remove_stock_adjustment(Request $request)

    {

        $messages = array();

        $product_id = $request->product_id;

        session()->forget('stock_adjustment.' . $product_id);

        $messages = array('status' => 'success' );

        echo json_encode($messages);

    }

    public function store(Request $request)

    {

         $this->validate($request, [

            'adjustment_date'      => 'required',

            'reference'      => 'required',

            'warehouse_id'      => 'required',

        ]);
        //Insert to adjustments

        $adjustment = new AdjustmentModel();

        $adjustment->user_id = Auth::user()->id;

        $adjustment->warehouse_id = $request->warehouse_id;

        $adjustment->invoice_number = $request->reference;

        $adjustment->adjustment_date = date('Y-m-d',strtotime($request->adjustment_date));

        $adjustment->year_adjasment = date('Y');

        $adjustment->transaction_code = 'POSW' . date('YmdHis');

        $adjustment->save();

        $last_id_adjustment =  $adjustment->id;

        $stock_adjustment = session()->get('stock_adjustment');

//dd($stock_adjustment);

        foreach ($stock_adjustment as $key => $value) {

            $unit_name = ProductUnitModel::where('product_id',$value['product_id'])->where('type',($request->unit[$key]==1?'parent':'child'))->first();

            $adjustment_detail = array(

                'adjustment_id'   => $last_id_adjustment,

                'unit'  => $unit_name!=null?$unit_name->unit_name:'',

                'product_id'  => $value['product_id'],

                'adjustment_qty'   =>  $request->adjustment_qty[$key],

                'adjustment_type'   =>  $request->adjustment_type[$key],

            );

            AdjustmentDetailModel::insert($adjustment_detail);

            $stock = StockModel::updateOrCreate([

                'product_id' => $value['product_id'],

                'warehouse_id' => $request->warehouse_id

            ]);

            if($request->adjustment_type[$key] == 'Addition'){

                if($request->unit[$key] == 1){

                    $stock->stock_qty += $request->adjustment_qty[$key]*$request->qty_per_unit[$key];

                }else{

                    $stock->stock_qty += $request->adjustment_qty[$key];

                }

            }else{

                if($request->unit[$key] == 1){

                    $stock->stock_qty -= $request->adjustment_qty[$key]*$request->qty_per_unit[$key];

                }else{

                    $stock->stock_qty -= $request->adjustment_qty[$key];

                }

            }



            $stock->save();

        }



        session::forget('stock_adjustment');



        return redirect()->route('adjustment.index')

        ->with('success','Product created successfully');

    }

    public function show($id){

        $adj = AdjustmentModel::find($id);

        $adj_detail = AdjustmentDetailModel::where('adjustment_id',$id)->get();

        return view('administrator.adjustment.show',compact('adj','adj_detail'));

    }



}

