<?php

namespace App\Http\Controllers\Administrator\Construction;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\ConstructionModel\ConstructorModel;
use App\ConstructionModel\ProductModel;
use App\ConstructionModel\PurchaseOrderModel;
use App\ConstructionModel\TaskWorkingGroupModel;
use App\Helpers\Globals;
use App\JournalModel;
use App\ProjectModel;
use DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Yajra\DataTables\DataTables;
use Gate;

class ManageUsingController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    function __construct()
    {
        $this->middleware('permission:Construction-Ajust-Stock-List',['only'=>['ajust_stock_list']]);
        $this->middleware('permission:Construction-Manage-Using-List',['only'=>['index']]);
        $this->middleware('permission:Construction-Origin-Stock-Out-List',['only'=>['request_stock_out']]);
        $this->middleware('permission:Construction-Ajust-Stock-Out-List',['only'=>['ajustment_stock_out_index']]);
        $this->middleware('permission:Construction-Return-To-Ajust-Stock-List',['only'=>['ajust_stock_index']]);
    }
    public function index(Request $request)
    {
        if($request->ajax()){
            $data =DB::table('nso007_warehouse_assign_product_construction')
            ->join("nso007_project_stock","nso007_project_stock.id","nso007_warehouse_assign_product_construction.project_id")
            ->join('nso007_warehouse_construction','nso007_warehouse_construction.id','nso007_warehouse_assign_product_construction.warehouse_id')
            ->select("nso007_warehouse_assign_product_construction.*",
                "nso007_project_stock.project_name",
                "nso007_warehouse_construction.name as warehouse_name",
                )
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->get();
            return  DataTables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('date',function($data){
                    return date('d-m-Y',strtotime($data->date));
                })
                ->addColumn('action', function($data) {
                    $button ="";
                   if(Gate::check('Construction-Manage-Using-Show & Edit'))
                        $button .= "<a style='margin-left:10px;' title='Show & Edit Detail' href='".route('manage-using-controller.edit',$data->id)."' class='btn btn-sm btn-info'><i class='fa fa-eye' aria-hidden='true'></i></a>";
                    return $button;
                })
                ->rawColumns(['action'=>'action'])
                ->make(true);
        }
        return view("administrator.construction.manage-using.index");
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
             })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })->pluck('project_name','id')->prepend("Please Select","");
        $zones = DB::table('nso007_zone_construction')->get();

        $zone = "<option value=''>Please Select</option>";
        foreach($zones as $key=>$value)
        {
            $zone .= "<option value='".$value->id."'>".$value->name."</option>";
        }

        $number_houses = DB::table('nso007_item_stock')->get();
        $number_house = "<option value=''>Please Select</option>";
        foreach($number_houses as $key=>$value)
        {
            $number_house .= "<option value='".$value->id."'>".$value->item_house."</option>";
        }

        return view("administrator.construction.manage-using.create",compact('contractors','projects','zone','number_house'));
    }
    public function get_product_from_warehouse($warehouse_id)
    {
        return json_encode(DB::table('nso007_construction_product_origin_stock')
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_construction_product_origin_stock.product_id')
            ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select('nso007_construction_product_origin_stock.product_id','nso007_construction_product.name as product_name','nso007_unit_construction.name as unit_name','nso007_construction_product_origin_stock.qty')->where('warehouse_id',$warehouse_id)->get()
        );
    }
    public function create_zone_store(Request $request)
    {
        $data = array([
            'user_id'=>Auth::user()->id,
            'name'=>$request->zone,
            'date'=>date('Y-m-d',strtotime($request->date))
        ]);

        DB::table('nso007_zone_construction')->insert($data);
        \LogActivity::addToLog('Zone create successfully !');

        return json_encode(DB::table('nso007_zone_construction')->get());
    }
    public function create_house_number_store(Request $request)
    {
        $data = array([
            'user_id'=>Auth::user()->id,
            'name'=>$request->house_number,
            'date'=>date('Y-m-d',strtotime($request->date))
        ]);

        DB::table('nso007_house_number_construction')->insert($data);
        \LogActivity::addToLog('house_number create successfully !');

        return json_encode(DB::table('nso007_house_number_construction')->get());
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'project'=>'required',
            'warehouse'=>'required',
            'date'=>'required',
            'product_id.*'=>'required',
            'qty.*'=>'required',
            'place_to_use_zone.*'=>'required'
        ],[
            'project.required'=>'Project is required',
            'warehouse.required'=>'Warehouse is required',
            'date.required'=>'Date is required',
            'product_id.*.required'=>'Product is required',
            'qty.*.required'=>'Qty is required',
            'place_to_use_zone.*.required'=>'Zone is required'
        ]);
        $data = array(
            'project_id'=>$request->project,
            'warehouse_id'=>$request->warehouse,
            'date'=>date('Y-m-d',strtotime($request->date)),
            'user_id'=>Auth::user()->id
        );
        DB::table('nso007_warehouse_assign_product_construction')->insert($data);
        $insert_id = DB::table('nso007_warehouse_assign_product_construction')->max("id");
        foreach($request->product_id as $key=>$value){
            $data_insert = array(
                'product_id'=>$request->product_id[$key],
                'qty'=>$request->qty[$key],
                'zone_id'=>$request->place_to_use_zone[$key],
                'house_number_id'=>$request->place_to_use_house_number[$key],
                'other'=>$request->description[$key],
                'warehouse_assign_product_id'=>$insert_id
            );
            DB::table('nso007_warehouse_assign_product_detail_construction')->insert($data_insert);
        }
        \LogActivity::addToLog('Product asign successfully !');
        return redirect()->route('manage-using-controller.index')->with('success','Successfully!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        dd($id);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        // dd("OK");
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })->pluck('project_name','id')->prepend("Please Select","");
        $zones = DB::table('nso007_zone_construction')->get();

        $zone = "<option value=''>Please Select</option>";
        foreach($zones as $key=>$value)
        {
            $zone .= "<option value='".$value->id."'>".$value->name."</option>";
        }

        $number_houses = DB::table('nso007_item_stock')->get();
        $number_house = "<option value=''>Please Select</option>";
        foreach($number_houses as $key=>$value)
        {
            $number_house .= "<option value='".$value->id."'>".$value->item_house."</option>";
        }
        $data_main = DB::table('nso007_warehouse_assign_product_construction')->where('id',$id)->first();

        $warehouse_f = DB::table('nso007_warehouse_construction')->where('id',$data_main->warehouse_id)->pluck('name','id');
        $products = DB::table('nso007_construction_product_origin_stock')
                    ->join('nso007_construction_product','nso007_construction_product.id','nso007_construction_product_origin_stock.product_id')
                    ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
                    ->select('nso007_construction_product_origin_stock.product_id',
                        'nso007_construction_product.name as product_name')
                    ->where('warehouse_id',$data_main->warehouse_id)
                    ->get();
        $product_option_select = "<option value=''>Please Select</option>";
        foreach($products as $key=>$value)
        {
            $product_option_select .= "<option value='".$value->product_id."'>".$value->product_name."</option>";
        }

        return view("administrator.construction.manage-using.edit",compact('contractors','projects','zone','number_house','data_main','warehouse_f','zones','number_houses','products','product_option_select'));
    }
    public function get_edit($id)
    {
        $data_detail = DB::table('nso007_warehouse_assign_product_detail_construction')
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_warehouse_assign_product_detail_construction.product_id')
            ->join("nso007_unit_construction",'nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select("nso007_warehouse_assign_product_detail_construction.*",
                    "nso007_unit_construction.name as unit_name")
            ->where('nso007_warehouse_assign_product_detail_construction.warehouse_assign_product_id',$id)
            ->get();

        return json_encode($data_detail);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request,[
            'project_id'=>'required',
            'warehouse_id'=>'required',
            'date'=>'required',
            'product_id.*'=>'required',
            'qty.*'=>'required',
            'place_to_use_zone.*'=>'required'
        ]);
        $data = array(
            'project_id'=>$request->project_id,
            'warehouse_id'=>$request->warehouse_id,
            'date'=>date('Y-m-d',strtotime($request->date))
        );
        DB::table('nso007_warehouse_assign_product_construction')->where('id',$id)->update($data);

        DB::table('nso007_warehouse_assign_product_detail_construction')->where("warehouse_assign_product_id",$id)->delete();

        foreach($request->product_id as $key=>$value){
            $data_insert = array(
                'product_id'=>$request->product_id[$key],
                'qty'=>$request->qty[$key],
                'zone_id'=>$request->place_to_use_zone[$key],
                'house_number_id'=>$request->place_to_use_house_number[$key],
                'other'=>$request->description[$key],
                'warehouse_assign_product_id'=>$id
            );
            DB::table('nso007_warehouse_assign_product_detail_construction')->insert($data_insert);
        }
        \LogActivity::addToLog('Product assigning update successfully !');
        return redirect()->route('manage-using-controller.index')->with('success','Successfully!');

    }
    public function request_stock_out(Request $request)
    {
        if($request->ajax()){
            $data =DB::table('nso007_request_warehouse_construction')
            ->join("nso007_project_stock","nso007_project_stock.id","nso007_request_warehouse_construction.project_id")
            ->join('nso007_warehouse_construction','nso007_warehouse_construction.id','nso007_request_warehouse_construction.warehouse_id')
            ->join('nso007_constructor_construction','nso007_constructor_construction.id','nso007_request_warehouse_construction.constructor_id')
            ->select("nso007_request_warehouse_construction.*",
                    "nso007_project_stock.project_name",
                    "nso007_warehouse_construction.name as warehouse_name",
                    "nso007_constructor_construction.name as constructor_name"
                )
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->get();
            return  DataTables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('date',function($data){
                    return date('d-m-Y',strtotime($data->date));
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Construction-Origin-Stock-Out-Show & Edit'))
                        $button .= "<a style='margin-left:10px;' title='Show & Edit Detail' href='".route('manage-using-controller.edit_stock_out',$data->id)."' class='btn btn-sm btn-info'><i class='fa fa-eye' aria-hidden='true'></i></a>";
                    return $button;
                })
                ->rawColumns(['action'=>'action'])
                ->make(true);
        }
        return view("administrator.construction.manage-using.request-stock-out");
    }
    public function make_stock_out()
    {
        $contractors = ConstructorModel::pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })->pluck('project_name','id')->prepend("Please Select","");
        $zones = DB::table('nso007_zone_construction')->get();

        $zone = "<option value=''>Please Select</option>";
        foreach($zones as $key=>$value)
        {
            $zone .= "<option value='".$value->id."'>".$value->name."</option>";
        }

        $number_houses = DB::table('nso007_item_stock')->get();
        $number_house = "<option value=''>Please Select</option>";
        foreach($number_houses as $key=>$value)
        {
            $number_house .= "<option value='".$value->id."'>".$value->item_house."</option>";
        }

        $work_group_types = TaskWorkingGroupModel::pluck('name','id')->prepend("Please Select","");

        return view("administrator.construction.manage-using.create-stock-out",compact('contractors','projects','zone','number_house','work_group_types'));
    }
    public function get_product_stock_out($warehouse_id)
    {

        $using_to = isset($_GET['using_to'])?$_GET['using_to']:"";

        return json_encode(DB::table('nso007_construction_product_origin_stock')
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_construction_product_origin_stock.product_id')
            ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select('nso007_construction_product_origin_stock.product_id','nso007_construction_product.name as product_name','nso007_unit_construction.name as unit_name')
            ->where('nso007_construction_product_origin_stock.warehouse_id',$warehouse_id)
            ->where("nso007_construction_product_origin_stock.using_to",$using_to)
            ->groupBy('nso007_construction_product_origin_stock.product_id')
            ->get()
        );
    }
    public function check_qty_product(Request $request)
    {
        return json_encode(
            DB::table('nso007_construction_product_origin_stock')
            ->where('warehouse_id',$request->warehouse_id)
            ->where('product_id',$request->product_id)
            ->first()
        );
    }
    public function check_qty_product_stock_out(Request $request)
    {
        $house_number_id = $request->house_number_id;
        $qty = $request->qty;
        $type = $request->type;//if type == 1 stock controll by assign using ,else if type == 2 stock doesn't controll by assign using
        $warehouse_id = $request->warehouse_id;
        $using_to = $request->using_to;
        if($type == 1){
            $data_assign = DB::table('nso007_warehouse_assign_product_construction')
                        ->join('nso007_warehouse_assign_product_detail_construction',
                        'nso007_warehouse_assign_product_detail_construction.warehouse_assign_product_id',
                        'nso007_warehouse_assign_product_construction.id')
                        ->select(DB::raw('SUM(qty) as total_qty_assign'))
                        ->where("product_id",$request->product_id)
                        ->where(function($query) use($request){
                            if(!empty($request->using_to)&&$request->using_to==1)
                                $query->where("zone_id",$request->zone_id);
                        })
                        ->where(function($query) use($house_number_id){
                            if(!empty($house_number_id))
                                $query->where('house_number_id',$house_number_id);
                        })
                        ->first();
        }
        else{
            $data_assign = DB::table('nso007_construction_product_origin_stock')
                        ->select(DB::raw('SUM(qty) as total_qty_assign'))
                        ->where("product_id",$request->product_id)
                        ->where(function($query) use($request){
                            if(!empty($request->using_to)&&$request->using_to==1)
                                $query->where("zone_id",$request->zone_id);
                        })
                        ->where('warehouse_id',$warehouse_id)
                        ->first();
        }

        $data = DB::table('nso007_request_warehouse_detail_construction')
            ->join('nso007_request_warehouse_construction',
                'nso007_request_warehouse_detail_construction.request_warehouse_id',
                'nso007_request_warehouse_construction.id')
            ->select(DB::raw('SUM(qty) as total_qty_use'))
            ->where('product_id',$request->product_id)

            ->where(function($query) use($request){
                if(!empty($request->using_to)&&$request->using_to==1)
                    $query->where("zone",$request->zone_id);
            })
            ->where(function($query) use($house_number_id){
                if(!empty($house_number_id))
                    $query->where('house_number',$house_number_id);
            })

            ->first();

        $balance_qty = $data_assign->total_qty_assign - $data->total_qty_use;
        // dd($data_assign->total_qty_assign);
        if($type == 1){
            if(empty($data_assign->total_qty_assign)) return json_encode(['balance'=>0,'stock_out'=>false,"message"=>'Quantity-Assign is empty !']);
            if($balance_qty<$qty) return json_encode(
                ['balance'=>$balance_qty,'stock_out'=>false,'message'=>'Assign-Quantity less than Using-Quantity !']
            );
            else{
                return json_encode(['balance'=>$balance_qty,'stock_out'=>true,'message'=>'Successfully']);
            }
        }else{
            if(empty($data_assign->total_qty_assign)) return json_encode(['balance'=>0,'stock_out'=>false,"message"=>'Balance is empty !']);
            if($balance_qty<$qty) return json_encode(
                ['balance'=>$balance_qty,'stock_out'=>false,'message'=>'Balance less than Using-Quantity !']
            );
            else{
                return json_encode(['balance'=>$balance_qty,'stock_out'=>true,'message'=>'Successfully']);
            }
        }
    }
    public function request_product_stock_store(Request $request)
    {
        $this->validate($request,[
            'contractor'=>'required',
            'project'=>'required',
            'warehouse'=>'required',
            'date'=>'required',
            'product_id'=>'required',
            'place_to_use_zone.*'=>'required',
            'qty.*'=>'required',
            'unit.*'=>'required',
            'unit_type.*'=>'required',
            'work_group_type_id'=>'required',
            'using_to'=>'required'
        ]);

        $data = array(
            'constructor_id'=>$request->contractor,
            'project_id'=>$request->project,
            'date'=>date('Y-m-d',strtotime($request->date)),
            'user_id'=>Auth::user()->id,
            'warehouse_id'=>$request->warehouse,
            'type'=>$request->type,
            'work_group_type_id'=>$request->work_group_type_id,
            'using_to'=>$request->using_to
        );
        DB::table('nso007_request_warehouse_construction')->insert($data);
        $insert_id = DB::table('nso007_request_warehouse_construction')->max('id');

        $total_amount = 0;
        foreach($request->product_id as $key=>$value)
        {
            $qty = $request->qty[$key];
            if($request->unit_type[$key]==2){
                $qty = $request->qty[$key]/(\Globals::sub_unit_to_per_origin_unit($request->unit[$key]));
            }

            $house_number_id = $request->place_to_use_house_number[$key];
            $data_detail = array(
                'request_warehouse_id'=>$insert_id,
                'product_id'=>$value,
                'qty'=>$qty,
                'zone'=>$request->place_to_use_zone[$key],
                'house_number'=>$request->place_to_use_house_number[$key],
                'used_for'=>$request->description[$key],
                'unit_type'=>$request->unit_type[$key],
                'unit_id'=>$request->unit[$key]
            );
            DB::table('nso007_request_warehouse_detail_construction')->insert($data_detail);

            $stock_detail_max_id = DB::table('nso007_request_warehouse_detail_construction')->max("id");

            #Get expense & Update Purchase detail
                $get_purchase_info = PurchaseOrderModel::join("nso007_construction_purchase_details","nso007_construction_purchase_details.purchase_id","nso007_construction_purchase.id")
                    ->where("project_id",$request->project)->where("zone_id",$request->place_to_use_zone[$key])
                    ->whereColumn("qty",">","qty_stock_out")->where("product_id",$value)
                    ->select("nso007_construction_purchase_details.*","nso007_construction_purchase.date")
                    ->orderBy("nso007_construction_purchase.date","ASC")
                    ->get();

                $balance_qty = 0;$total = 0;$qty_using = $qty;

                foreach($get_purchase_info as $info){
                    $balance_qty = $info->qty - $info->qty_stock_out;
                    if($balance_qty>0){
                        $using_amount = 0;
                        if($balance_qty >= $qty_using){
                            $using_amount = $info->price * $qty_using;
                            $total += $using_amount; 
                            DB::table("nso007_construction_purchase_details")->where("id",$info->id)->update(['qty_stock_out'=>DB::raw('qty_stock_out +'.$qty_using)]);
                            DB::table("nso007_stock_out_purchase_detail")->insert(['purchase_detail_id'=>$info->id,"stock_out_detail_id"=>$stock_detail_max_id,"qty"=>$qty_using,"unit_price"=>$info->price]);
                            break;
                        }
                        else{
                            $using_amount = $info->price * $balance_qty;
                            $total += $using_amount;
                            $qty_using = $qty_using - $balance_qty;
                            DB::table("nso007_construction_purchase_details")->where("id",$info->id)->update(['qty_stock_out'=>DB::raw('qty_stock_out +'.$balance_qty)]);
                            DB::table("nso007_stock_out_purchase_detail")->insert(['purchase_detail_id'=>$info->id,"stock_out_detail_id"=>$stock_detail_max_id,"qty"=>$balance_qty,"unit_price"=>$info->price]);
                        }

                        $stock_out_purchase_detail_id = DB::table("nso007_stock_out_purchase_detail")->max("id");

                        \Globals::stock_out_add_accounting($stock_out_purchase_detail_id,$info->purchase_id,$info->product_id,$request->project,$using_amount,date('Y-m-d',strtotime($request->date)));

                    }
                }
            #End

            DB::table('nso007_request_warehouse_detail_construction')->where("id",$stock_detail_max_id)->update(['amount'=>$total]);

            $total_amount += $total;

            DB::table('nso007_construction_product_origin_stock')
            ->where('warehouse_id',$request->warehouse)
            ->where('product_id',$value)
            ->where('zone_id',$request->place_to_use_zone[$key])
            ->update(['qty'=>DB::raw('qty-'.$qty)]);

            DB::table('nso007_warehouse_assign_product_detail_construction')
            ->where('zone_id',$request->place_to_use_zone[$key])
            ->when(!empty($request->place_to_use_house_number[$key]),function($query) use ($house_number_id){
                $query->where("house_number_id",$house_number_id);
            })
            ->update(['delete_status'=>1]);
        }

        DB::table('nso007_request_warehouse_construction')->where("id",$insert_id)->update(['total_amount'=>$total_amount]);

        \LogActivity::addToLog('request stock out successfully !');
        return redirect()->route('construction.request_stock_out')->with('success','successfully!');
    }
    public function edit_stock_out($id)
    {
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
             })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })
        ->pluck('project_name','id')->prepend("Please Select","");

        $number_houses = DB::table('nso007_item_stock')->get();
        $number_house = "<option value=''>Please Select</option>";
        foreach($number_houses as $key=>$value)
        {
            $number_house .= "<option value='".$value->id."'>".$value->item_house."</option>";
        }
        $data = DB::table('nso007_request_warehouse_construction')->where("id",$id)->first();
        $data_warehouse = DB::table('nso007_warehouse_construction')->where('id',$data->warehouse_id)->pluck("name","id");
        $data_detail = DB::table('nso007_request_warehouse_detail_construction')
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_request_warehouse_detail_construction.product_id')
            ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->join('nso007_zone_construction','nso007_zone_construction.id','nso007_request_warehouse_detail_construction.zone')
            ->leftJoin('nso007_house_number_construction','nso007_house_number_construction.id','nso007_request_warehouse_detail_construction.house_number')
            ->select("nso007_request_warehouse_detail_construction.*",
                "nso007_construction_product.name as product_name",
                "nso007_construction_product.id as product_id",
                "nso007_unit_construction.name as unit_name",
                'nso007_unit_construction.id as unit_main_id',
                "nso007_zone_construction.name as zone_name",
                "nso007_zone_construction.id as zone_id",
                "nso007_house_number_construction.name as house_number_name",
                "nso007_house_number_construction.id as house_number_id"
            )
            ->where("request_warehouse_id",$id)
            ->get();
        
        /*$products = DB::table('nso007_warehouse_assign_product_detail_construction')
            ->join('nso007_warehouse_assign_product_construction','nso007_warehouse_assign_product_construction.id','nso007_warehouse_assign_product_detail_construction.warehouse_assign_product_id')
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_warehouse_assign_product_detail_construction.product_id')
            ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select('nso007_warehouse_assign_product_detail_construction.product_id','nso007_construction_product.name as product_name','nso007_unit_construction.name as unit_name')
            ->where('nso007_warehouse_assign_product_construction.warehouse_id',$data->warehouse_id)
            ->groupBy('nso007_warehouse_assign_product_detail_construction.product_id')
            ->get();*/

        $products = DB::table('nso007_construction_product_origin_stock')
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_construction_product_origin_stock.product_id')
            ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select('nso007_construction_product_origin_stock.product_id','nso007_construction_product.name as product_name','nso007_unit_construction.name as unit_name')
            ->where('nso007_construction_product_origin_stock.warehouse_id',$data->warehouse_id)
            ->where("nso007_construction_product_origin_stock.using_to",$data->using_to)
            ->groupBy('nso007_construction_product_origin_stock.product_id')
            ->get();

        $tr = "";
        $zones = DB::table('nso007_zone_construction')->get();
        $zone = "<option value=''>Please Select</option>";
        foreach($zones as $key=>$value)
        {
            $zone .= "<option value='".$value->id."'>".$value->name."</option>";
        }
        $zone_con = '<option value="">Please Select</option>';
        $number_house_con = '<option value="">Please Select</option>';
        $product_con = '';
        foreach($data_detail as $k=>$value){
            foreach($products as $key=>$valu){
                if($valu->product_id==$value->product_id){
                    $product_con .= "<option value='".$valu->product_id."' selected>".$valu->product_name."</option>";
                }
                else{
                    $product_con .= "<option value='".$valu->product_id."'>".$valu->product_name."</option>";
                }
            }
            foreach($zones as $key=>$val)
            {
                if($val->id==$value->zone_id){
                    $zone_con .= "<option value='".$val->id."' selected>".$val->name."</option>";
                }
                else{
                    $zone_con .= "<option value='".$val->id."'>".$val->name."</option>";
                }
            }
            foreach($number_houses as $key=>$v)
            {
                if($v->id == $value->house_number_id){
                    $number_house_con .= "<option value='".$v->id."' selected>".$v->item_house."</option>";
                }
                 else{
                    $number_house_con .= "<option value='".$v->id."'>".$v->item_house."</option>";
                 }   
            }
            $qty = $value->qty;
            
            if($value->unit_type==2)
            {
                $unit_option = '<option value="'.$value->unit_main_id.'" data-type="1">'.$value->unit_name.'</option>';
                
                $qty = $value->qty*(\Globals::sub_unit_to_per_origin_unit($value->unit_id));
                $data_sub_units = DB::table('nso007_sub_unit_construction')->where("id",$value->unit_id)->get();
                foreach($data_sub_units as $k=>$val)
                {
                    if($val->id == $value->unit_id)
                    {
                        $unit_option.='<option value="'.$val->id.'" data-type="2" selected>'.$val->name.'</option>';
                    }
                    else{
                        $unit_option.='<option value="'.$val->id.'" data-type="2">'.$val->name.'</option>';
                    }
                    
                }
            }
            else{
                $unit_option = '<option value="'.$value->unit_main_id.'" data-type="1" selected>'.$value->unit_name.'</option>';
                $data_sub_units = DB::table('nso007_sub_unit_construction')->where("main_unit_id",$value->unit_id)->where('product_id',$value->product_id)->get();
                // dd($value->unit_id);
                foreach($data_sub_units as $k=>$val)
                {
                    $unit_option.='<option value="'.$val->id.'" data-type="2">'.$val->name.'</option>';
                    
                }
            }
            
            
            if($k==0){
                $tr.='<tr>
                    <td width="4%">
                        <span>'.($k+1).'</span>
                    </td>
                    <td width="12%">
                        <select name="product_id[]" class="form-control select2" id="first-select-product" onchange="selected_product(this)">
                        '.$product_con.'
                        </select>
                    </td>
                    <td style="width: 200px !important;">
                        <select name="place_to_use_zone[]" class="form-control select2" >
                            '.$zone_con.'
                        </select>
                    </td>
                    <td style="width: 200px !important;">
                        <select name="place_to_use_house_number[]" class="form-control select2" >
                            '.$number_house_con.'
                        </select>
                    </td>
                    <td width="10%">
                        <input type="text" class="form-control" name="qty[]" onchange="check_qty(this)" value="'.$qty.'">
                    </td>
                    <td width="160px">
                        <select class="form-control select2" name="unit[]" onchange="select_unit(this)">
                            '.$unit_option.'
                        </select>
                        <input type="hidden" name = "unit_type[]" value="'.$value->unit_type.'">
                    </td>
                    <td>
                        <textarea name = "description[]" class="form-control" rows="2" placeholder="Description">'.$value->used_for.'</textarea>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-danger" disabled>
                            <span class="fa fa-trash"></span>
                        </button>
                    </td>
                </tr>';
            }else{
                $tr.='<tr>
                    <td width="4%">
                        <span>'.($k+1).'</span>
                    </td>
                    <td width="12%">
                        <select name="product_id[]" class="form-control select2" id="first-select-product" onchange="selected_product(this)">
                        '.$product_con.'
                        </select>
                    </td>
                    <td style="width: 200px !important;">
                        <select name="place_to_use_zone[]" class="form-control select2" >
                            '.$zone_con.'
                        </select>
                    </td>
                    <td style="width: 200px !important;">
                        <select name="place_to_use_house_number[]" class="form-control select2" >
                            '.$number_house_con.'
                        </select>
                    </td>
                    <td width="10%">
                        <input type="text" class="form-control" name="qty[]" onchange="check_qty(this)" value="'.$qty.'">
                    </td>
                    <td width="160px">
                        <select class="form-control select2" name="unit[]" onchange="select_unit(this)">
                            '.$unit_option.'
                        </select>
                        <input type="hidden" name = "unit_type[]" value="'.$value->unit_type.'">
                    </td>
                    <td>
                        <textarea name = "description[]" class="form-control" rows="2" placeholder="Description">'.$value->used_for.'</textarea>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-danger" onclick="remove(this)">
                            <span class="fa fa-trash"></span>
                        </button>
                    </td>
                </tr>';
            }
        }
        $product_for_select = '<option value="">Please Select</option>';
        foreach($products as $key=>$value)
        {
            $product_for_select.='<option value="'.$value->product_id.'">'.$value->product_name.'</option>';
        }

        $work_group_types = TaskWorkingGroupModel::pluck('name','id')->prepend("Please Select","");

        return view("administrator.construction.manage-using.edit-stock-out",compact('contractors','projects','zone','number_house','data','data_warehouse','data_detail','tr','product_for_select','work_group_types'));
    }
    public function update_stock_out(Request $request,$id)
    {
        $this->validate($request,[
            'constructor_id'=>'required',
            'project_id'=>'required',
            'warehouse_id'=>'required',
            'date'=>'required',
            'product_id'=>'required',
            'place_to_use_zone.*'=>'required',
            'qty.*'=>'required',
            'unit.*'=>'required',
            'unit_type.*'=>'required',
            'using_to'=>'required'
        ]);
        // dd($request->all());
        $data = array(
            'constructor_id'=>$request->constructor_id,
            'project_id'=>$request->project_id,
            'date'=>date('Y-m-d',strtotime($request->date)),
            'warehouse_id'=>$request->warehouse_id,
            'work_group_type_id'=>$request->work_group_type_id,
            'using_to'=>$request->using_to
        );
        DB::table('nso007_request_warehouse_construction')->where('id',$id)->update($data);


        //Update old info by decreasing

        $data_de = DB::table('nso007_request_warehouse_detail_construction')->where('request_warehouse_id',$id)->get();
        foreach($data_de as $value){
            DB::table('nso007_construction_product_origin_stock')
            ->where('warehouse_id',$request->warehouse_id)
            ->where('product_id',$value->product_id)
            ->update(['qty'=>DB::raw('qty+'.$value->qty)]);

            $stock_out_purchase_details = DB::table("nso007_stock_out_purchase_detail")->where("stock_out_detail_id",$value->id);
            if(!empty($stock_out_purchase_details->get())&&count($stock_out_purchase_details->get())>0){
                foreach($stock_out_purchase_details->get() as $detail_stock_out_pur){
                    DB::table("nso007_construction_purchase_details")->where("id",$detail_stock_out_pur->purchase_detail_id)->update(['qty_stock_out'=>DB::raw('qty_stock_out -'.$detail_stock_out_pur->qty)]);

                    JournalModel::where("transaction_type","Stock-Out")->where("journal_referenceid",$detail_stock_out_pur->id)->delete();
                }

                $stock_out_purchase_details->delete();
            }
        }
        
        //End  

        $total_amount = 0;

        DB::table('nso007_request_warehouse_detail_construction')->where('request_warehouse_id',$id)->delete();

        foreach($request->product_id as $key=>$value)
        {
            $qty = $request->qty[$key];
            if($request->unit_type[$key]==2){
                $qty = $request->qty[$key]/(\Globals::sub_unit_to_per_origin_unit($request->unit[$key]));
            }
            $data_detail = array(
                'request_warehouse_id'=>$id,
                'product_id'=>$value,
                'qty'=>$qty,
                'zone'=>$request->place_to_use_zone[$key],
                'house_number'=>$request->place_to_use_house_number[$key],
                'used_for'=>$request->description[$key],
                'unit_type'=>$request->unit_type[$key],
                'unit_id'=>$request->unit[$key]
            );
            DB::table('nso007_request_warehouse_detail_construction')->insert($data_detail);

            $stock_detail_max_id = DB::table('nso007_request_warehouse_detail_construction')->max("id");

            #Get expense & Update Purchase detail
                $get_purchase_info = PurchaseOrderModel::join("nso007_construction_purchase_details","nso007_construction_purchase_details.purchase_id","nso007_construction_purchase.id")
                    ->where("project_id",$request->project_id)->where("zone_id",$request->place_to_use_zone[$key])
                    ->whereColumn("qty",">","qty_stock_out")->where("product_id",$value)
                    ->select("nso007_construction_purchase_details.*","nso007_construction_purchase.date")
                    ->orderBy("nso007_construction_purchase.date","ASC")
                    ->get();

                $balance_qty = 0;$total = 0;$qty_using = $qty;

                foreach($get_purchase_info as $info){
                    $balance_qty = $info->qty - $info->qty_stock_out;
                    if($balance_qty>0){
                        $total = 0;
                        if($balance_qty >= $qty_using){
                            $using_amount = $info->price * $qty_using;
                            $total += $using_amount; 
                            DB::table("nso007_construction_purchase_details")->where("id",$info->id)->update(['qty_stock_out'=>DB::raw('qty_stock_out +'.$qty_using)]);
                            DB::table("nso007_stock_out_purchase_detail")->insert(['purchase_detail_id'=>$info->id,"stock_out_detail_id"=>$stock_detail_max_id,"qty"=>$qty_using,"unit_price"=>$info->price]);
                            break;
                        }
                        else{
                            $using_amount = $info->price * $balance_qty;
                            $total += $using_amount;
                            $qty_using = $qty_using - $balance_qty;
                            DB::table("nso007_construction_purchase_details")->where("id",$info->id)->update(['qty_stock_out'=>DB::raw('qty_stock_out +'.$balance_qty)]);
                            DB::table("nso007_stock_out_purchase_detail")->insert(['purchase_detail_id'=>$info->id,"stock_out_detail_id"=>$stock_detail_max_id,"qty"=>$balance_qty,"unit_price"=>$info->price]);
                        }

                        $stock_out_purchase_detail_id = DB::table("nso007_stock_out_purchase_detail")->max("id");

                        \Globals::stock_out_add_accounting($stock_out_purchase_detail_id,$info->purchase_id,$info->product_id,$request->project_id,$using_amount,date('Y-m-d',strtotime($request->date)));
                    }

                }
            #End

            DB::table('nso007_request_warehouse_detail_construction')->where("id",$stock_detail_max_id)->update(['amount'=>$total]);

            $total_amount += $total;

            DB::table('nso007_construction_product_origin_stock')
            ->where('warehouse_id',$request->warehouse_id)
            ->where('product_id',$value)
            ->update(['qty'=>DB::raw('qty - '.$qty)]);
        }

        //Update Total Amount
        DB::table('nso007_request_warehouse_construction')->where("id",$id)->update(['total_amount'=>$total_amount]);
        
        \LogActivity::addToLog('request stock out update successfully !');
        return redirect()->route('construction.request_stock_out')->with('success','successfully!');
    }
    public function ajust_stock_index(Request $request)
    {
        if($request->ajax()){
            $data =DB::table('nso007_construction_product_ajustment_stock')
            ->join("nso007_project_stock","nso007_project_stock.id","nso007_construction_product_ajustment_stock.project_id")
            ->join('nso007_warehouse_construction','nso007_warehouse_construction.id','nso007_construction_product_ajustment_stock.warehouse_id')
            ->join('nso007_constructor_construction','nso007_constructor_construction.id','nso007_construction_product_ajustment_stock.constructor_id')
            ->select("nso007_construction_product_ajustment_stock.*",
                    "nso007_project_stock.project_name",
                    "nso007_warehouse_construction.name as warehouse_name",
                    "nso007_constructor_construction.name as constructor_name"
                )
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->get();
            return  DataTables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('date',function($data){
                    return date('d-m-Y',strtotime($data->date));
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Construction-Return-To-Ajust-Stock-Show & Edit'))
                        $button .= "<a style='margin-left:10px;' title='Show & Edit Detail' href='".route('construction.return_stock_show',$data->id)."' class='btn btn-sm btn-info'><i class='fa fa-eye' aria-hidden='true'></i></a>";
                    return $button;
                })
                ->rawColumns(['action'=>'action'])
                ->make(true);
        }
        return view("administrator.construction.manage-using.ajust-stock-index");
    }
    public function return_stock_show($id)
    {
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
             })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })->pluck('project_name','id')->prepend("Please Select","");
        $zones = DB::table('nso007_zone_construction')->get();

        $zone = "<option value=''>Please Select</option>";
        foreach($zones as $key=>$value)
        {
            $zone .= "<option value='".$value->id."'>".$value->name."</option>";
        }

        $number_houses = DB::table('nso007_item_stock')->get();
        $number_house = "<option value=''>Please Select</option>";
        foreach($number_houses as $key=>$value)
        {
            $number_house .= "<option value='".$value->id."'>".$value->item_house."</option>";
        }
        $data = DB::table("nso007_construction_product_ajustment_stock")->where('id',$id)->first();
        $warehouse_f = DB::table("nso007_warehouse_construction")->where("id",$data->warehouse_id)->pluck("name","id");

        $products = DB::table('nso007_warehouse_assign_product_detail_construction')
            ->join('nso007_warehouse_assign_product_construction','nso007_warehouse_assign_product_construction.id','nso007_warehouse_assign_product_detail_construction.warehouse_assign_product_id')
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_warehouse_assign_product_detail_construction.product_id')
            ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select('nso007_warehouse_assign_product_detail_construction.product_id','nso007_construction_product.name as product_name','nso007_unit_construction.name as unit_name')
            ->where('nso007_warehouse_assign_product_construction.warehouse_id',$data->warehouse_id)
            ->groupBy('nso007_warehouse_assign_product_detail_construction.product_id')
            ->get();
        $product_option = "<option value=''>Please Select</option>";
        foreach($products as $key=>$value){
            $product_option .= "<option value='".$value->product_id."'>".$value->product_name."</option>";
        }

        $data_detail = DB::table('nso007_construction_product_ajustment_stock_detail')
            ->join('nso007_zone_construction','nso007_zone_construction.id','nso007_construction_product_ajustment_stock_detail.zone_id')
            ->leftJoin('nso007_house_number_construction','nso007_house_number_construction.id','nso007_construction_product_ajustment_stock_detail.house_number_id')
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_construction_product_ajustment_stock_detail.product_id')
            ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select(
                "nso007_construction_product_ajustment_stock_detail.*",
                'nso007_unit_construction.name as unit_name',
                'nso007_unit_construction.id as unit_main_id',
            )
            ->where('main_stock_id',$id)
            ->get();

        
        $tr = '';
        foreach($data_detail as $k=>$val){
            $product_select = "<option value=''>Please Select</option>";
            foreach($products as $key=>$value){
                if($value->product_id==$val->product_id){
                    $product_select .= "<option value='".$value->product_id."' selected>".$value->product_name."</option>";
                }else{
                    $product_select .= "<option value='".$value->product_id."'>".$value->product_name."</option>";
                }

                $zone_select = "<option value=''>Please Select</option>";
                foreach($zones as $key=>$value)
                {
                    if($value->id==$val->zone_id){
                        $zone_select .= "<option value='".$value->id."' selected>".$value->name."</option>";
                    }
                    else{
                        $zone_select .= "<option value='".$value->id."'>".$value->name."</option>";
                    }
                    
                }
                $number_house_select = "<option value=''>Please Select</option>";
                foreach($number_houses as $key=>$value)
                {
                    if($value->id==$val->house_number_id)
                    {
                        $number_house_select .= "<option value='".$value->id."' selected>".$value->item_house."</option>";
                    }
                    else{
                        $number_house_select .= "<option value='".$value->id."'>".$value->item_house."</option>";
                    }
                }
                $qty = $val->qty;
                if($val->unit_type==2)
                {
                    $unit_option = '<option value="'.$val->unit_main_id.'" data-type="1">'.$val->unit_name.'</option>';
                    
                    $qty = $val->qty*(\Globals::sub_unit_to_per_origin_unit($val->unit_id));
                    $data_sub_units = DB::table('nso007_sub_unit_construction')->where("id",$val->unit_id)->get();
                    foreach($data_sub_units as $k=>$valu)
                    {
                        if($valu->id == $val->unit_id)
                        {
                            $unit_option.='<option value="'.$valu->id.'" data-type="2" selected>'.$valu->name.'</option>';
                        }
                        else{
                            $unit_option.='<option value="'.$valu->id.'" data-type="2">'.$valu->name.'</option>';
                        }
                        
                    }
                }
                else{
                    $unit_option = '<option value="'.$val->unit_main_id.'" data-type="1" selected>'.$val->unit_name.'</option>';
                    $data_sub_units = DB::table('nso007_sub_unit_construction')->where("main_unit_id",$val->unit_id)->where('product_id',$val->product_id)->get();
                    // dd($value->unit_id);
                    foreach($data_sub_units as $k=>$va)
                    {
                        $unit_option.='<option value="'.$va->id.'" data-type="2">'.$va->name.'</option>';
                        
                    }
                }

                if($k==0){
                    $tr .=' <tr>
                            <td width="4%">
                                <span>1</span>
                            </td>
                            <td width="12%">
                                <select name="product_id[]" class="form-control select2" id="first-select-product" onchange="selected_product(this)">
                                    '.$product_select.'
                                </select>
                            </td>
                            <td style="width: 200px !important;">
                                <select name="place_to_use_zone[]" class="form-control select2" >
                                    '.$zone_select.'
                                </select>
                            </td>
                            <td style="width: 200px !important;">
                                <select name="place_to_use_house_number[]" class="form-control select2" >
                                    '.$number_house_select.'
                                </select>
                            </td>
                            <td width="10%">
                                <input type="text" class="form-control" name="qty[]" onchange="check_qty(this)" value="'.$qty.'">
                            </td>
                            <td width="160px">
                                <select class="form-control select2" name="unit[]" onchange="select_unit(this)">
                                    '.$unit_option.'
                                </select>
                                <input type="hidden" name = "unit_type[]" value="'.$val->unit_type.'">
                            </td>
                            <td>
                                <textarea name="Description[]" class="form-control" placeholder="Description" rows="2">'.$val->description.'</textarea>
                            </td>
                            <td><button class="btn btn-sm btn-danger" disabled>
                                <span class="fa fa-trash"></span></button>
                            </td>
                        </tr>';
                }
                else{
                    $tr .=' <tr>
                            <td width="4%">
                                <span>1</span>
                            </td>
                            <td width="12%">
                                <select name="product_id[]" class="form-control select2" id="first-select-product" onchange="selected_product(this)">
                                    '.$product_select.'
                                </select>
                            </td>
                            <td style="width: 200px !important;">
                                <select name="place_to_use_zone[]" class="form-control select2" >
                                    '.$zone_select.'
                                </select>
                            </td>
                            <td style="width: 200px !important;">
                                <select name="place_to_use_house_number[]" class="form-control select2" >
                                    '.$number_house_select.'
                                </select>
                            </td>
                            <td width="10%">
                                <input type="text" class="form-control" name="qty[]" onchange="check_qty(this)" value="'.$qty.'">
                            </td>
                            <td width="160px">
                                <select class="form-control select2" name="unit[]" onchange="select_unit(this)">
                                    '.$unit_option.'
                                </select>
                                <input type="hidden" name = "unit_type[]" value="'.$val->unit_type.'">
                            </td>
                            <td>
                                <textarea name="Description[]" class="form-control" placeholder="Description" rows="2">'.$val->description.'</textarea>
                            </td>
                            <td><button class="btn btn-sm btn-danger" disabled>
                                <span class="fa fa-trash"></span></button>
                            </td>
                        </tr>';
                }
            }

        }
        return view("administrator.construction.manage-using.ajust-stock-show",compact('contractors','projects','zone','number_house','data','warehouse_f','product_option','product_select','tr'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
    public function ajust_stock_list(Request $request)
    {
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('branch_id', \Branch::branch_id());
        })
        ->pluck('project_name', 'id')->prepend('Please Select Option', '')->toArray();
        $products = DB::table('nso007_construction_product')->pluck("name","id")->prepend("Please Select Option","");
        $categories = DB::table('nso007_product_categories_construction')->pluck("name",'id')->prepend("Please Select Option","");
        if($request->ajax()){
            $input = $request->all();
            $data =DB::table('nso007_construction_product_ajust_stock')
            ->leftJoin('nso007_warehouse_construction','nso007_warehouse_construction.id','nso007_construction_product_ajust_stock.warehouse_id')
            ->leftJoin("nso007_project_stock","nso007_project_stock.id","nso007_warehouse_construction.project_id")
            ->leftJoin('nso007_construction_product','nso007_construction_product.id','nso007_construction_product_ajust_stock.product_id')
            ->leftJoin('nso007_product_brand_construction','nso007_product_brand_construction.id','nso007_construction_product.brand_id')
            ->leftJoin('nso007_product_categories_construction','nso007_product_categories_construction.id','nso007_construction_product.category_id')
            ->leftJoin('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select("nso007_construction_product_ajust_stock.*",
                "nso007_project_stock.project_name",
                "nso007_construction_product.name as product_name",
                'nso007_unit_construction.name as unit_name',
                'nso007_product_categories_construction.name as product_category_name',
                "nso007_product_brand_construction.name as brand_name",
                "nso007_warehouse_construction.name as warehouse_name"
                )
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->where(function($query) use ($input){
               
                if(!empty($input['warehouses'])){
                    $query->where("nso007_warehouse_construction.id",$input['warehouses']);
                }
                if(!empty($input['projects'])){
                    $query->where("nso007_project_stock.id",$input['projects']);
                }
                if(!empty($input['categories'])){
                    $query->where("nso007_construction_product.category_id",$input['categories']);
                }
                if(!empty($input['products'])){
                    $query->where("nso007_construction_product.id",$input['products']);
                }
                
            })
            
            ->get();
            return  DataTables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Construction-Ajust-Stock-Transfer-To-Origin-Stock'))
                        $button = "<a title='Transfer To Origin Stock' href='javascript:void(0)' onclick='display_transfer(".$data->id.")' class='btn btn-sm btn-primary'><i class='fa fa-scissors' aria-hidden='true'></i></a>";
                    return $button;
                })
                ->rawColumns(['action'=>'action'])
                ->make(true);
        }
        if($request->isMethod('POST')){
            $input = $request->all();
            $data =DB::table('nso007_construction_product_ajust_stock')
                ->leftJoin('nso007_warehouse_construction','nso007_warehouse_construction.id','nso007_construction_product_ajust_stock.warehouse_id')
                ->leftJoin("nso007_project_stock","nso007_project_stock.id","nso007_warehouse_construction.project_id")
                ->leftJoin('nso007_construction_product','nso007_construction_product.id','nso007_construction_product_ajust_stock.product_id')
                ->leftJoin('nso007_product_brand_construction','nso007_product_brand_construction.id','nso007_construction_product.brand_id')
                ->leftJoin('nso007_product_categories_construction','nso007_product_categories_construction.id','nso007_construction_product.category_id')
                ->leftJoin('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
                ->select("nso007_construction_product_ajust_stock.*",
                    "nso007_project_stock.project_name",
                    "nso007_construction_product.name as product_name",
                    'nso007_unit_construction.name as unit_name',
                    'nso007_product_categories_construction.name as product_category_name',
                    "nso007_product_brand_construction.name as brand_name",
                    "nso007_warehouse_construction.name as warehouse_name"
                    )
                ->when(empty(\Branch::branch_key()), function ($query) {
                    $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
                })
                ->where(function($query) use ($input){
                
                    if(!empty($input['warehouses'])){
                        $query->where("nso007_warehouse_construction.id",$input['warehouses']);
                    }
                    if(!empty($input['projects'])){
                        $query->where("nso007_project_stock.id",$input['projects']);
                    }
                    if(!empty($input['categories'])){
                        $query->where("nso007_construction_product.category_id",$input['categories']);
                    }
                    if(!empty($input['products'])){
                        $query->where("nso007_construction_product.id",$input['products']);
                    }
                    
                })
                
                ->get();
                $branch = DB::table('nso007_branches')->where('id', \Branch::branch_id())->first();
                return view('administrator.construction.product-stock.report',compact('data','branch'));
        }

        return view('administrator.construction.product-stock.ajust-stock-list',compact('projects','products','categories'));
    }
    public function return_stock_create()
    {
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
             })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })->pluck('project_name','id')->prepend("Please Select","");
        $zones = DB::table('nso007_zone_construction')->get();

        $zone = "<option value=''>Please Select</option>";
        foreach($zones as $key=>$value)
        {
            $zone .= "<option value='".$value->id."'>".$value->name."</option>";
        }

        $number_houses = DB::table('nso007_item_stock')->get();
        $number_house = "<option value=''>Please Select</option>";
        foreach($number_houses as $key=>$value)
        {
            $number_house .= "<option value='".$value->id."'>".$value->item_house."</option>";
        }
        return view("administrator.construction.manage-using.return-stock",compact('contractors','projects','zone','number_house'));
    }
    public function return_stock_store(Request $request)
    {
        
        $this->validate($request,[
            'contractor_id'=>'required',
            'project_id'=>'required',
            'warehouse_id'=>'required',
            'date'=>'required',
            'product_id.*'=>'required',
            'place_to_use_zone.*'=>'required',
            'qty.*'=>'required',
            'unit.*'=>'required',
            'unit_type.*'=>'required'
        ]);

        $data = array(
            'constructor_id'=>$request->contractor_id,  
            'user_id'=>Auth::user()->id,
            'project_id'=>$request->project_id,
            'warehouse_id'=>$request->warehouse_id,
            'date'=>date('Y-m-d',strtotime($request->date))
        );
        DB::table('nso007_construction_product_ajustment_stock')->insert($data);

        $insert_id = DB::table('nso007_construction_product_ajustment_stock')->max("id");
        foreach($request->product_id as $key=>$value)
        {
            $qty = $request->qty[$key];
            if($request->unit_type[$key]==2){
                $qty = $request->qty[$key]/(\Globals::sub_unit_to_per_origin_unit($request->unit[$key]));
            }
            $data_detail = array(
                'product_id'=>$value,
                'zone_id'=>$request->place_to_use_zone[$key],
                'house_number_id'=>$request->place_to_use_house_number[$key],
                'qty'=>$qty,
                'description'=>$request->description[$key],
                'main_stock_id'=>$insert_id,
                'unit_type'=>$request->unit_type[$key],
                'unit_id'=>$request->unit[$key]
            );
            DB::table('nso007_construction_product_ajustment_stock_detail')->insert($data_detail);

            $check_warehouse = DB::table('nso007_construction_product_ajust_stock')->where('warehouse_id',$request->warehouse_id)->first();
            if(empty($check_warehouse)){
                $data = array(
                    'warehouse_id'=>$request->warehouse_id,
                    'product_id'=>$value,
                    'qty'=>$qty,
                    'user_id'=>Auth::user()->id
                );
                DB::table('nso007_construction_product_ajust_stock')->insert($data);
            }else{
                $check_product = DB::table('nso007_construction_product_ajust_stock')->where('product_id',$value)->where('warehouse_id',$request->warehouse_id)->first();

                if(empty($check_product)){
                    $data = array(
                        'warehouse_id'=>$request->warehouse_id,
                        'product_id'=>$value,
                        'qty'=>$qty,
                        'user_id'=>Auth::user()->id,
                    );
                    DB::table('nso007_construction_product_ajust_stock')->insert($data);
                }else{
                    DB::table('nso007_construction_product_ajust_stock')->where('product_id',$value)->where('warehouse_id',$request->warehouse_id)->increment('qty',$qty);
                }
            }
        }

        \LogActivity::addToLog('return stock successfully !');

        return redirect()->route('construction.ajust_stock_index')->with('success','successfully !');
    }
    public function store_return_stock_edit(Request $request,$id)
    {
        $this->validate($request,[
            'constructor_id'=>'required',
            'project_id'=>'required',
            'warehouse_id'=>'required',
            'date'=>'required',
            'product_id.*'=>'required',
            'place_to_use_zone.*'=>'required',
            'qty.*'=>'required',
            'unit.*'=>'required',
            'unit_type.*'=>'required'
        ]);

        $data = array(
            'constructor_id'=>$request->constructor_id,
            'project_id'=>$request->project_id,
            'warehouse_id'=>$request->warehouse_id,
            'date'=>date('Y-m-d',strtotime($request->date))
        );
        DB::table('nso007_construction_product_ajustment_stock')->where('id',$id)->update($data);

        $data_details = DB::table('nso007_construction_product_ajustment_stock_detail')->where("main_stock_id",$id)->get();
        foreach($data_details as $k => $va){
            DB::table('nso007_construction_product_ajust_stock')->where('product_id',$va->product_id)->where('warehouse_id',$request->warehouse_id)->decrement('qty',$va->qty);
        }

        DB::table('nso007_construction_product_ajustment_stock_detail')->where("main_stock_id",$id)->delete();
        foreach($request->product_id as $key=>$value)
        {
            $qty = $request->qty[$key];
            if($request->unit_type[$key]==2){
                $qty = $request->qty[$key]/(\Globals::sub_unit_to_per_origin_unit($request->unit[$key]));
            }
            $data_detail = array(
                'product_id'=>$value,
                'zone_id'=>$request->place_to_use_zone[$key],
                'house_number_id'=>$request->place_to_use_house_number[$key],
                'qty'=>$qty,
                'description'=>$request->Description[$key],
                'main_stock_id'=>$id,
                'unit_type'=>$request->unit_type[$key],
                'unit_id'=>$request->unit[$key]
            );
            DB::table('nso007_construction_product_ajustment_stock_detail')->insert($data_detail);

            $check_warehouse = DB::table('nso007_construction_product_ajust_stock')->where('warehouse_id',$request->warehouse_id)->first();
            if(empty($check_warehouse)){
                $data = array(
                    'warehouse_id'=>$request->warehouse_id,
                    'product_id'=>$value,
                    'qty'=>$qty,
                    'user_id'=>Auth::user()->id
                );
                DB::table('nso007_construction_product_ajust_stock')->insert($data);
            }else{
                $check_product = DB::table('nso007_construction_product_ajust_stock')->where('product_id',$value)->where('warehouse_id',$request->warehouse_id)->first();

                if(empty($check_product)){
                    $data = array(
                        'warehouse_id'=>$request->warehouse_id,
                        'product_id'=>$value,
                        'qty'=>$qty,
                        'user_id'=>Auth::user()->id,
                    );
                    DB::table('nso007_construction_product_ajust_stock')->insert($data);
                }else{
                    // dd("OK");
                    DB::table('nso007_construction_product_ajust_stock')->where('product_id',$value)->where('warehouse_id',$request->warehouse_id)->increment('qty',$qty);
                }
            }

        }
        \LogActivity::addToLog('return stock update successfully !');

        return redirect()->route('construction.ajust_stock_index')->with('success','successfully !');
    }
    public function return_to_origin_stock()
    {
        dd("OK");
    }
    public function ajustment_stock_out_index(Request $request)
    {
        if($request->ajax()){
            $data =DB::table('nso007_ajustment_stock_out_construction')
            ->join("nso007_project_stock","nso007_project_stock.id","nso007_ajustment_stock_out_construction.project_id")
            ->join('nso007_warehouse_construction','nso007_warehouse_construction.id','nso007_ajustment_stock_out_construction.warehouse_id')
            ->join('nso007_constructor_construction','nso007_constructor_construction.id','nso007_ajustment_stock_out_construction.constructor_id')
            ->select("nso007_ajustment_stock_out_construction.*",
                    "nso007_project_stock.project_name",
                    "nso007_warehouse_construction.name as warehouse_name",
                    "nso007_constructor_construction.name as constructor_name"
                )
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->get();
            return  DataTables::of($data)
                ->setRowId('id')
                ->addIndexColumn()
                ->editColumn('date',function($data){
                    return date('d-m-Y',strtotime($data->date));
                })
                ->addColumn('action', function($data) {
                    $button ="";
                    if(Gate::check('Construction-Ajust-Stock-Out-Show & Edit'))
                        $button .= "<a style='margin-left:10px;' title='Show & Edit Detail' href='".route('construction.ajustment_stock_out_edit',$data->id)."' class='btn btn-sm btn-info'><i class='fa fa-eye' aria-hidden='true'></i></a>";
                    return $button;
                })
                ->rawColumns(['action'=>'action'])
                ->make(true);
        }
        return view("administrator.construction.manage-using.ajust-stock-out-list");
    }
    public function ajustment_stock_out()
    {
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
             })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })->pluck('project_name','id')->prepend("Please Select","");
        $zones = DB::table('nso007_zone_construction')->get();

        $zone = "<option value=''>Please Select</option>";
        foreach($zones as $key=>$value)
        {
            $zone .= "<option value='".$value->id."'>".$value->name."</option>";
        }

        $number_houses = DB::table('nso007_item_stock')->get();
        $number_house = "<option value=''>Please Select</option>";
        foreach($number_houses as $key=>$value)
        {
            $number_house .= "<option value='".$value->id."'>".$value->item_house."</option>";
        }

        return view("administrator.construction.manage-using.ajust-stock-out",compact('contractors','projects','zone','number_house'));
    }
    public function check_ajustment_stock_out_qty(Request $request)
    {
        $house_number_id = $request->house_number_id;
        $qty = $request->qty;
        $data_assign = DB::table('nso007_construction_product_ajustment_stock')
                        ->join('nso007_construction_product_ajustment_stock_detail',
                        'nso007_construction_product_ajustment_stock_detail.main_stock_id',
                        'nso007_construction_product_ajustment_stock.id')
                        ->select(DB::raw('SUM(qty) as total_qty_assign'))
                        ->where("product_id",$request->product_id)
                        ->where("zone_id",$request->zone_id)
                        ->where('house_number_id',$house_number_id)
                        ->first();

        $data = DB::table('nso007_ajustment_stock_out_construction_detail')
            ->join('nso007_ajustment_stock_out_construction',
                'nso007_ajustment_stock_out_construction_detail.main_stock_out_id',
                'nso007_ajustment_stock_out_construction.id')
            ->select(DB::raw('SUM(qty) as total_qty_use'))
            ->where('product_id',$request->product_id)
            ->where('zone_id',$request->zone_id)
            ->where('house_number_id',$house_number_id)
            ->first();

        $balance_qty = $data_assign->total_qty_assign - $data->total_qty_use;
        // dd($data_assign->total_qty_assign);
        if(empty($data_assign->total_qty_assign)) return json_encode(['status'=>2,'balance_qty'=>$balance_qty]);//Don't have this product
        if($balance_qty<$qty) return json_encode(['status'=>1,'balance_qty'=>$balance_qty]);//Qty less
        else{
            return json_encode(['status'=>0]);//Correct Request
        }
    }
    public function ajustment_stock_out_store(Request $request)
    {
        $this->validate($request,[
            'contractor'=>'required',
            'project'=>'required',
            'warehouse'=>'required',
            'date'=>'required',
            'product_id.*'=>'required',
            'place_to_use_zone.*'=>'required',
            'qty.*'=>'required',
            'unit.*'=>'required',
            'unit_type.*'=>'required'
        ]);
        $data = array(
            'constructor_id'=>$request->contractor,
            'project_id'=>$request->project,
            'warehouse_id'=>$request->warehouse,
            'date'=>date('Y-m-d',strtotime($request->date)),
            'user_id'=>Auth::user()->id
        );
        DB::table('nso007_ajustment_stock_out_construction')->insert($data);
        $insert_id = DB::table('nso007_ajustment_stock_out_construction')->max("id");
        foreach($request->product_id as $key=>$value)
        {
            $qty = $request->qty[$key];
            if($request->unit_type[$key]==2){
                $qty = $request->qty[$key]/(\Globals::sub_unit_to_per_origin_unit($request->unit[$key]));
            }
            $data_detail = array(
                'product_id'=>$value,
                'zone_id'=>$request->place_to_use_zone[$key],
                'house_number_id'=>$request->place_to_use_house_number[$key],
                'qty'=>$qty,
                'description'=>$request->description[$key],
                'main_stock_out_id'=>$insert_id,
                'unit_type'=>$request->unit_type[$key],
                'unit_id'=>$request->unit[$key]
            );
            DB::table('nso007_ajustment_stock_out_construction_detail')->insert($data_detail);

            DB::table('nso007_construction_product_ajust_stock')
                ->where("warehouse_id",$request->warehouse)
                ->where('product_id',$value)
                ->update(["qty"=>DB::raw('qty - '.$qty)]);
        }
        \LogActivity::addToLog('ajustment stock out successfully !');
        return redirect()->route('construction.ajustment_stock_out_index')->with("success","successfully!");
    }
    public function ajustment_stock_out_edit($id)
    {
        $contractors = ConstructorModel::join('nso007_project_stock','nso007_project_stock.id','nso007_constructor_construction.project_id')
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
             })
            ->pluck('nso007_constructor_construction.name','nso007_constructor_construction.id')
            ->prepend('Please Select','');
        $projects = ProjectModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
        })->pluck('project_name','id')->prepend("Please Select","");
        $zones = DB::table('nso007_zone_construction')->get();

        $zone = "<option value=''>Please Select</option>";
        foreach($zones as $key=>$value)
        {
            $zone .= "<option value='".$value->id."'>".$value->name."</option>";
        }

        $number_houses = DB::table('nso007_item_stock')->get();
        $number_house = "<option value=''>Please Select</option>";
        foreach($number_houses as $key=>$value)
        {
            $number_house .= "<option value='".$value->id."'>".$value->item_house."</option>";
        }
        $data = DB::table('nso007_ajustment_stock_out_construction')->where('id',$id)->first();
        $warehouse = DB::table('nso007_warehouse_construction')->where('id',$data->warehouse_id)->pluck("name","id");
        $data_detail = DB::table("nso007_ajustment_stock_out_construction_detail")
            ->join('nso007_construction_product','nso007_construction_product.id','nso007_ajustment_stock_out_construction_detail.product_id')
            ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
            ->select(
                "nso007_ajustment_stock_out_construction_detail.*",
                "nso007_construction_product.name as product_name",
                "nso007_unit_construction.name as unit_name",
                'nso007_unit_construction.id as unit_main_id',
            )
            ->where("main_stock_out_id",$id)
            ->get();
        $products = DB::table('nso007_construction_product_ajust_stock')
                ->join('nso007_construction_product','nso007_construction_product.id','nso007_construction_product_ajust_stock.product_id')
                ->select(
                    "nso007_construction_product.id as product_id",
                    "nso007_construction_product.name as product_name"
                    )
                ->where('nso007_construction_product_ajust_stock.warehouse_id',$data->warehouse_id)
                ->get();
        $product_option = '<option value="">Please Select</option>';
        foreach($products as $k=>$val)
        {
            $product_option .= '<option value="'.$val->product_id.'">'.$val->product_name.'</option>';
        }
        $tr = "";$product_select = "";$zone_select='';$house_number_select = '';
        foreach($data_detail as $key=>$value)
        {
            foreach($products as $k=>$val)
            {
                if($val->product_id==$value->product_id){
                    $product_select .= '<option value="'.$val->product_id.'" selected>'.$val->product_name.'</option>';
                }
                else{
                    $product_select .= '<option value="'.$val->product_id.'">'.$val->product_name.'</option>';
                }
                
            }

            foreach($zones as $k=>$val)
            {
                if($val->id == $value->zone_id){
                    $zone_select .= "<option value='".$val->id."' selected>".$val->name."</option>";
                }
                else{
                    $zone_select .= "<option value='".$val->id."'>".$val->name."</option>";
                }
            }
            foreach($number_houses as $k=>$val)
            {
                if($val->id==$value->house_number_id)
                {
                    $house_number_select .= "<option value='".$val->id."' selected>".$val->item_house."</option>";
                }
                else{
                    $house_number_select .= "<option value='".$val->id."'>".$val->item_house."</option>";
                }
            }
            $qty = $value->qty;
            if($value->unit_type==2)
            {
                $unit_option = '<option value="'.$value->unit_main_id.'" data-type="1">'.$value->unit_name.'</option>';
                
                $qty = $value->qty*(\Globals::sub_unit_to_per_origin_unit($value->unit_id));
                $data_sub_units = DB::table('nso007_sub_unit_construction')->where("id",$value->unit_id)->get();
                foreach($data_sub_units as $k=>$val)
                {
                    if($val->id == $value->unit_id)
                    {
                        $unit_option.='<option value="'.$val->id.'" data-type="2" selected>'.$val->name.'</option>';
                    }
                    else{
                        $unit_option.='<option value="'.$val->id.'" data-type="2">'.$val->name.'</option>';
                    }
                    
                }
            }
            else{
                $unit_option = '<option value="'.$value->unit_main_id.'" data-type="1" selected>'.$value->unit_name.'</option>';
                $data_sub_units = DB::table('nso007_sub_unit_construction')->where("main_unit_id",$value->unit_id)->where('product_id',$value->product_id)->get();
                // dd($value->unit_id);
                foreach($data_sub_units as $k=>$val)
                {
                    $unit_option.='<option value="'.$val->id.'" data-type="2">'.$val->name.'</option>';
                    
                }
            }

            if($key==0){
                $tr .='
                    <tr>
                        <td width="4%">
                            <span>'.($key+1).'</span>
                        </td>
                        <td width="12%">
                            <select name="product_id[]" class="form-control select2" id="first-select-product" onchange="selected_product(this)">
                                '.$product_select.'
                            </select>
                        </td>
                        <td style="width: 200px !important;">
                            <select name="place_to_use_zone[]" class="form-control select2" >
                                '.$zone_select.'
                            </select>
                        </td>
                        <td style="width: 200px !important;">
                            <select name="place_to_use_house_number[]" class="form-control select2" >
                                '.$house_number_select.'
                            </select>
                        </td>
                        <td width="10%">
                            <input type="text" class="form-control" name="qty[]" onchange="check_qty(this)" value="'.$qty.'">
                        </td>
                        <td width="160px">
                            <select class="form-control select2" name="unit[]" onchange="select_unit(this)">
                                '.$unit_option.'
                            </select>
                            <input type="hidden" name = "unit_type[]" value="'.$value->unit_type.'">
                        </td>
                        <td>
                            <textarea name="description[]" class="form-control" rows="2" placeholder="Description">'.$value->description.'</textarea>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-danger" disabled>
                                <span class="fa fa-trash"></span>
                            </button>
                        </td>
                    </tr>';
            }else{
                $tr .='
                    <tr>
                        <td width="4%">
                            <span>'.($key+1).'</span>
                        </td>
                        <td width="12%">
                            <select name="product_id[]" class="form-control select2" onchange="selected_product(this)">
                                '.$product_select.'
                            </select>
                        </td>
                        <td style="width: 200px !important;">
                            <select name="place_to_use_zone[]" class="form-control select2" >
                                '.$zone_select.'
                            </select>
                        </td>
                        <td style="width: 200px !important;">
                            <select name="place_to_use_house_number[]" class="form-control select2" >
                                '.$house_number_select.'
                            </select>
                        </td>
                        <td width="10%">
                            <input type="text" class="form-control" name="qty[]" onchange="check_qty(this)" value="'.$qty.'">
                        </td>
                        <td width="160px">
                            <select class="form-control select2" name="unit[]" onchange="select_unit(this)">
                                '.$unit_option.'
                            </select>
                            <input type="hidden" name = "unit_type[]" value="'.$value->unit_type.'">
                        </td>
                        <td>
                            <textarea name="description[]" class="form-control" rows="2" placeholder="Description">'.$value->description.'</textarea>
                        </td>
                        <td>
                            <button class="btn btn-sm btn-danger" onclick="remove(this)">
                                <span class="fa fa-trash"></span>
                            </button>
                        </td>
                    </tr>';
            }
        }

        return view("administrator.construction.manage-using.ajustment-stock-out-edit",compact('contractors','projects','zone','number_house','data','warehouse','product_option','tr'));
    }
    public function ajustment_stock_out_edit_store(Request $request,$id)
    {
        // dd($request->all());
        $this->validate($request,[
            'constructor_id'=>'required',
            'project_id'=>'required',
            'warehouse_id'=>'required',
            'date'=>'required',
            'product_id.*'=>'required',
            'place_to_use_zone.*'=>'required',
            'qty.*'=>'required',
            'unit.*'=>'required',
            'unit_type.*'=>'required'
        ]);
        $data = array(
            'constructor_id'=>$request->constructor_id,
            'project_id'=>$request->project_id,
            'warehouse_id'=>$request->warehouse_id,
            'date'=>date('Y-m-d',strtotime($request->date))
        );
        DB::table('nso007_ajustment_stock_out_construction')->where('id',$id)->update($data);
        
        $data_detail_info = DB::table('nso007_ajustment_stock_out_construction_detail')->where('main_stock_out_id',$id)->get();
        
        foreach($data_detail_info as $key => $value)
        {
            DB::table('nso007_construction_product_ajust_stock')
                ->where("warehouse_id",$request->warehouse_id)
                ->where('product_id',$value->product_id)
                ->update(["qty"=>DB::raw('qty + '.$value->qty)]);
        }

        DB::table('nso007_ajustment_stock_out_construction_detail')->where('main_stock_out_id',$id)->delete();
        foreach($request->product_id as $key=>$value)
        {
            $qty = $request->qty[$key];
            if($request->unit_type[$key]==2){
                $qty = $request->qty[$key]/(\Globals::sub_unit_to_per_origin_unit($request->unit[$key]));
            }
            $data_detail = array(
                'product_id'=>$value,
                'zone_id'=>$request->place_to_use_zone[$key],
                'house_number_id'=>$request->place_to_use_house_number[$key],
                'qty'=>$qty,
                'description'=>$request->description[$key],
                'main_stock_out_id'=>$id,
                'unit_type'=>$request->unit_type[$key],
                'unit_id'=>$request->unit[$key]
            );
            DB::table('nso007_ajustment_stock_out_construction_detail')->insert($data_detail);

            DB::table('nso007_construction_product_ajust_stock')
                ->where("warehouse_id",$request->warehouse_id)
                ->where('product_id',$value)
                ->update(["qty"=>DB::raw('qty - '.$qty)]);
        }
        \LogActivity::addToLog('ajustment stock out update successfully !');
        return redirect()->route('construction.ajustment_stock_out_index')->with("success","successfully!");
    }
    public function get_warehouse($project_id)
    {
        $warehouses = DB::table('nso007_warehouse_construction')->where('project_id',$project_id)->get();
        return json_encode($warehouses);
    }
    public function transfer_to_origin_stock(Request $request)
    {
        $ajustment_stock_id = $request->ajustment_stock_id;
        $warehouse_id = $request->warehouse_id;

        $data = DB::table('nso007_construction_product_ajust_stock')->where('id',$ajustment_stock_id)->first();
        if($data->qty<=0){
            return \back()->with("warning","Quantities of the product is zero");
        }
        $check_warehouse = DB::table('nso007_construction_product_origin_stock')->where('warehouse_id',$warehouse_id)->first();
        if(empty($check_warehouse)){
            $data_pro = array(
                'warehouse_id'=>$request->warehouse_id,
                'product_id'=>$data->product_id,
                'qty'=>$data->qty,
                'user_id'=>Auth::user()->id
            );
            DB::table('nso007_construction_product_origin_stock')->insert($data_pro);
        }else{

            $check_product = DB::table('nso007_construction_product_origin_stock')->where('product_id',$data->product_id)->where('warehouse_id',$request->warehouse_id)->first();

            if(empty($check_product)){
                $data_pro = array(
                    'warehouse_id'=>$request->warehouse_id,
                    'product_id'=>$data->product_id,
                    'qty'=>$data->qty,
                    'user_id'=>Auth::user()->id,
                );
                DB::table('nso007_construction_product_origin_stock')->insert($data_pro);
            }else{
                DB::table('nso007_construction_product_origin_stock')->where('product_id',$data->product_id)->where('warehouse_id',$request->warehouse_id)->increment('qty',$data->qty);
            }
        }
        DB::table('nso007_construction_product_ajust_stock')->where('id',$ajustment_stock_id)->update(['qty'=>0]);
        \LogActivity::addToLog('transfer form ajustment stock to origin stock successfully !');
        return \back()->with('success','successfull!');

    }
    public function get_unit_product($product_id)
    {
        $product = ProductModel::join("nso007_product_brand_construction","nso007_product_brand_construction.id",'nso007_construction_product.brand_id')
                   ->join('nso007_unit_construction','nso007_unit_construction.id','nso007_construction_product.unit_id')
                   ->select("nso007_product_brand_construction.name as subcategory_name",
                        "nso007_unit_construction.name as unit_name",
                        "nso007_unit_construction.id as unit_id",
                        'nso007_construction_product.*')
                   ->where("nso007_construction_product.id",$product_id)
                   ->first();
        
        $sub_units = DB::table('nso007_sub_unit_construction')->where('main_unit_id',$product->unit_id)->where('product_id',$product_id)->get();
        $data = array(
            'product'=>$product,
            'sub_units'=>$sub_units
        );
        
        return json_encode($data);
    }
    public function check_edit_product_using_stock(Request $request)
    {
        $house_number_id = $request->house_number_id;
        $request_stock_id = $request->request_stock_id;
        $qty = $request->qty;
        $type =  $request->type;
        $warehouse_id = $request->warehouse_id;
        if($type==1){
            $data_assign = DB::table('nso007_warehouse_assign_product_construction')
                        ->join('nso007_warehouse_assign_product_detail_construction',
                        'nso007_warehouse_assign_product_detail_construction.warehouse_assign_product_id',
                        'nso007_warehouse_assign_product_construction.id')
                        ->select(DB::raw('SUM(qty) as total_qty_assign'))
                        ->where("product_id",$request->product_id)
                        ->where(function($query) use ($request){
                            if(!empty($request->using_to)&&$request->using_to==1){
                                $query->where("zone_id",$request->zone_id);
                            }
                        })
                        ->where(function($query) use ($house_number_id){
                            if(!empty($house_number_id)){
                                $query->where('house_number_id',$house_number_id);
                            }
                        })
                        ->first();
        }
        else{
            $data_assign = DB::table('nso007_construction_product_origin_stock')
                        ->select(DB::raw('SUM(qty) as total_qty_assign'))
                        ->where("product_id",$request->product_id)
                        ->where(function($query) use ($request){
                            if(!empty($request->using_to)&&$request->using_to==1){
                                $query->where("zone_id",$request->zone_id);
                            }
                        })
                        ->where('warehouse_id',$warehouse_id)
                        ->first();
        }

        $data = DB::table('nso007_request_warehouse_detail_construction')
            ->join('nso007_request_warehouse_construction',
                'nso007_request_warehouse_detail_construction.request_warehouse_id',
                'nso007_request_warehouse_construction.id')
            ->select(DB::raw('SUM(qty) as total_qty_use'))
            ->where('product_id',$request->product_id)
            ->where(function($query) use ($request){
                if(!empty($request->using_to)&&$request->using_to==1){
                    $query->where("zone",$request->zone_id);
                }
            })
            ->where(function($query) use ($house_number_id){
                if(!empty($house_number_id)){
                    $query->where('house_number',$house_number_id);
                }
            })
            ->first();
        
        $data_cerren = DB::table('nso007_request_warehouse_detail_construction')
            ->join('nso007_request_warehouse_construction',
                'nso007_request_warehouse_detail_construction.request_warehouse_id',
                'nso007_request_warehouse_construction.id')
            ->select(DB::raw('SUM(qty) as total_qty_use'))
            ->where('product_id',$request->product_id)
            ->where(function($query) use ($request){
                if(!empty($request->using_to)&&$request->using_to==1){
                    $query->where("zone",$request->zone_id);
                }
            })
            ->where(function($query) use ($house_number_id){
                if(!empty($house_number_id)){
                    $query->where('house_number',$house_number_id);
                }
            })
            ->where('nso007_request_warehouse_construction.id',$request_stock_id)
            ->first();

        $balance_qty = $data_assign->total_qty_assign - ($data->total_qty_use - $data_cerren ->total_qty_use);
        // dd($data_assign->total_qty_assign);
        if($type == 1){
            if(empty($data_assign->total_qty_assign)) return json_encode(['balance'=>0,'stock_out'=>false,"message"=>'Quantity-Assign is empty !']);
            if($balance_qty<$qty) return json_encode(
                ['balance'=>$balance_qty,'stock_out'=>false,'message'=>'Assign-Quantity less than Using-Quantity !']
            );
            else{
                return json_encode(['balance'=>$balance_qty,'stock_out'=>true,'message'=>'Successfully']);
            }
        }else{
            if(empty($data_assign->total_qty_assign)) return json_encode(['balance'=>0,'stock_out'=>false,"message"=>'Balance is empty !']);
            if($balance_qty<$qty) return json_encode(
                ['balance'=>$balance_qty,'stock_out'=>false,'message'=>'Balance less than Using-Quantity !']
            );
            else{
                return json_encode(['balance'=>$balance_qty,'stock_out'=>true,'message'=>'Successfully']);
            }
        }
        
    }
    public function get_house_number(){
        $data = DB::table('nso007_house_number_construction')->get();
        return view("administrator.construction.manage-using.house_number_list",compact('data'));
    }
    public function store_house_number(Request $request){
        DB::table('nso007_house_number_construction')->insert(['user_id'=>Auth::user()->id,'name'=>$request->name,'date'=>date("Y-m-d")]);
        return \back()->with('success','create');
    }
    public function update_house_number(Request $request){
        DB::table('nso007_house_number_construction')->where("id",$request->id)->update(['name'=>$request->name]);
        return \back()->with('success','create');
    }
    public function get_zone_warehouse(Request $request){
        if(!empty($request->using_to==1)){
            $data = DB::table("nso007_zone_construction")
                ->join("nso007_construction_product_origin_stock","nso007_construction_product_origin_stock.zone_id","nso007_zone_construction.id")
                ->join("nso007_warehouse_construction","nso007_warehouse_construction.id","nso007_construction_product_origin_stock.warehouse_id")
                ->where("nso007_warehouse_construction.id",$request->warehouse_id)->where("nso007_construction_product_origin_stock.using_to",$request->using_to)->select("nso007_zone_construction.name","nso007_zone_construction.id")
                ->get();
        }else{
            $data = DB::table("nso007_zone_construction")->select("nso007_zone_construction.name","nso007_zone_construction.id")->get();
        }
        return response()->json($data);
    }
}
