<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\AssetLocation;
use Illuminate\Support\Facades\Validator;
use  DB;

class AssetLocationController extends Controller
{
         public function __construct()
    {
               
    }

      function index()
    {
       $asset_locations = AssetLocation::orderBy('id', 'DESC')->get();
      
      return view('procurement/asset-location.index' ,compact('asset_locations') );
    }

    
    function create()
    {
        return view('procurement/asset-location.create' );
    }

    function insert(Request $request)
    {
        $validator = Validator::make($request->all(), [
                        'name' => 'required|unique:asset_location,name',
            ]);


           if ($validator->fails()) {
                return redirect('/asset-location/create')
                                ->withErrors($validator)
                                ->withInput();
            }

        DB::beginTransaction();

        try {

             $department = AssetLocation::create([
                        'name' => $request->name
              ]);

             
               DB::commit();
               return redirect()->route('asset.location')->with('success' , 'Asset Location  Added Successfully!');
          

          } 
            catch (\Exception $e) 
          {
           DB::rollback();
          return redirect()->route('asset.location')->with('success' , 'Something went wrong.');
          }
    }

    public function destroy($id)
    {
        if(is_numeric($id))
        {
          AssetLocation::where('id',$id)->delete();
        }

        return redirect()->route('asset.location')->with('success' , 'Asset Location Removed Successfully!');
    }


    function edit($id)
{
   if(is_numeric($id))
    {
          $asset_location = AssetLocation::where('id', $id)->first();
           return view('procurement/asset-location.edit' ,compact('asset_location') );
    }
}

public function update(Request $request) 
{

 $id = $request->input('id');
 if(is_numeric($id))
 {
        $validator = Validator::make($request->all(), [
                    'name' => 'required|unique:asset_location,name,'.$id,
        ]);

       if ($validator->fails()) {
            return redirect('/asset-location/edit/'.$id)
                            ->withErrors($validator)
                            ->withInput();
        }

       DB::beginTransaction();

        try {

        AssetLocation::where('id', '=', $id)->update(
        array( 'name' => $request->name ));

        DB::commit();

        return redirect()->route('asset.location')->with('success' , 'Asste Location Updated Successfully!');
   
      } 
        catch (\Exception $e) 
      {
        DB::rollback();
          return redirect()->route('asset.location')->with('success' , 'Asset Location Not Updated!');
      }
}

}

}
