<?php

namespace App\Http\Controllers;

use App\DataTables\PortDataTable;
use App\Models\Port;
use Illuminate\Http\Request;

class PortController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(PortDataTable $dataTable)
    {
       if(auth()->user()->can('show_ports')){

          return $dataTable->render('ports.index');
       }
        else{
         return abort(404);

        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $data = $this->validate($request, [
            'name' => 'required',
            'code' => 'required|min:3|max:10',
            'country' => 'required',
            'status' => 'required|boolean',
        ]);


       return Port::create($data);
    }

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

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  Port $port
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Port $port)
    {
        $data = $this->validate($request, [
            'name' => 'required',
            'code' => 'required|min:3|max:10',
            'country' => 'required',
            'status' => 'required|boolean',
        ]);

        return $port->update($data);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  Port $port
     * @return \Illuminate\Http\Response
     */
    public function destroy(Port $port)
    {
        return $port->delete();
    }


    public function countrySearch(){
        return \DB::table('ports')
        ->select('country as name', \DB::raw('count(*) as total'))
        ->groupBy('country')->paginate();
    }

    public function search(){
        return Port::paginate();
    }


}
