<?php

namespace App\Http\Controllers;

use App\Http\Requests\ClientCreateRequest;
use App\Http\Requests\ClientUpdateRequest;
use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;

class ClientController extends Controller
{
    public function index(Request $request)
    {
        $count = Client::count();

        $search = $request->input('s');

        /** @var LengthAwarePaginator $clients */

        $builder = Client::orderBy('id', 'DESC');
        if($search) {
            $builder->where('name', 'LIKE', "%{$search}%");
        }
        $clients = $builder
            ->paginate(30)
            ->withQueryString();

        return view('client.index', [
            'count' => $count,
            'clients' => $clients
        ]);
    }

    public function create()
    {
        $client = new Client();
        return view('client.edit', ['client' => $client]);
    }

    public function store(ClientCreateRequest $request)
    {
        $validated = $request->validated();
        if(!$validated) {
            return redirect()->back()->withInput()->withErrors($request->messages());
        }
        $client = Client::create($request->all());
        return redirect()->route('adm.client.edit', ['client' => $client->id]);
    }

    public function show($id)
    {
        $client = Client::find($id);
        return view('client.view', ['client' => $client]);
    }

    public function edit($id)
    {
        $client = Client::find($id);
        return view('client.edit', ['client' => $client]);
    }

    public function update(ClientUpdateRequest $request, $id)
    {
        $validated = $request->validated();
        if(!$validated) {
            return redirect()->back()->withInput()->withErrors($request->messages());
        }
        $client = Client::find($id);
        $client->fill($request->all());
        $client->save();
        session()->flash('success_alert', 'Updated');
        return redirect()->route('adm.client.edit', ['client' => $client->id]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
