<?php

namespace App\Http\Controllers\Product;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\Country;
use App\Models\ProductWarehouse;
use App\Models\State;
use App\Models\City;
use App\Models\CompanyAddress;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ProductWarehouseController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:product-warehouse-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = ProductWarehouse::select([
            'product_warehouses.id',
            'product_warehouses.state_id',
            'product_warehouses.country_id',
            'product_warehouses.company_id',
            'product_warehouses.name',
            'product_warehouses.trade_name',
            'product_warehouses.address_1',
            'product_warehouses.address_2',
            'product_warehouses.place',
            'product_warehouses.gst_no',
            'product_warehouses.priority',
            'product_warehouses.is_default',
            'product_warehouses.status',
        ])
        ->with('getCompany')
        ->with('getState')
        ->with('getCountry');

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('name', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

            return view('product-warehouse.table', compact('data'));
        } else {
            $data = $data->paginate(10);

            return view('product-warehouse.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $state           = State::all();
        $country         = Country::all();
        $company         = Company::all();
        $company_address = \Session::get('company_data')['companies_addresses'];

        return view('product-warehouse.create', compact('state','country','company','company_address'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name'       => 'required|unique:product_warehouses',
            'trade_name' => 'required',
            'state_id'   => 'required',
            'country_id' => 'required',
            'city_id'    => 'required',
            'company_id' => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $quality = ProductWarehouse::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Product Warehouse created successfully',
                'data'    => $quality
            ]);
        }
        return redirect()->route('product-warehouse.index')
            ->with('success', 'Product Warehouse created successfully');
    }


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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $warehouse = ProductWarehouse::find($id);
        $state     = State::all();
        $country   = Country::all();
        $city      = City::all();
        $company   = Company::all();
        return view('product-warehouse.edit', compact('state','country','company','warehouse' , 'city'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            'name'       => 'required|unique:product_warehouses,name,'.$id,
            'trade_name' => 'required',
            'company_id' => 'required',
            'city_id'    => 'required',
            'country_id' => 'required',
            'state_id'   => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $master = ProductWarehouse::find($id);

        if (!$master) {
            return redirect()->route('product-warehouse.index')
                ->with('error','Product Warehouse not found!');
        }

        $master->update($data);


        return redirect()->route('product-warehouse.index')
            ->with('success','Product Warehouse updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        ProductWarehouse::find($request->id)->delete();

        $Redirect = 'product-warehouse';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data'    => [
                'redirect' => $Redirect,
            ]
        ]);
    }
    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status );
            $Update = ProductWarehouse::where('id', '=', $request->id)->update($data);

            if($Update){
                return response()->json([
                    'success'=>true,
                    'message'=>['Warehouse status successfully change'],
                    'data'=>[
                       'redirect'=>'/users/',
                       'reload'=>true,
                    ]
                ]);
            } else {
                return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
                ]);
            }
        }
    }
    public function warehouseCountry(Request $request)
    {
        $data = [];
        if($request->has('q')){
            $search = $request->q;
            $data = DB::table("countries")
            ->select("id","name")
            ->where('name','LIKE',"%$search%")
            ->get();
        }

        return response()->json($data);
    }
}
