<?php

namespace App\Http\Controllers;

use App\Http\Requests\Client\FilterClientRequest;
use App\Http\Requests\Client\StoreClientRequest;
use App\Http\Requests\Client\UpdateClientRequest;
use App\Models\Client;

class ClientController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\View\View
     */
    public function index(FilterClientRequest $request)
    {
        $validated = $request->validated();
        $data = [];
        $data['items'] = Client::get_data($validated);
        $data = array_merge($data, Client::load_index());

        return view('clients.index', $data);
    }

    public function get_data()
    {
        $data = [];
        $data['records'] = Client::get_data([]);
        $data['total_records'] = count($data['records']);

        return $data;
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $data = [];
        $data = array_merge($data, Client::load_create());

        return view('clients.create_edit', $data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(StoreClientRequest $request)
    {
        $validated = $request->validated();

        Client::create($validated);

        return redirect()->route('clients.index');
    }

    /**
     * Display the specified resource.
     *
     * @return \Illuminate\View\View
     */
    public function show(Client $client)
    {
        $data = [];
        $data['item'] = $client;
        $data['fields'] = (new Client)->getFillable();

        return view('clients.show', $data);
    }

    /**
     * Returns the resource in JSON format.
     *
     * @param  ModelType  $modelVariable
     * @return string
     */
    public function load(Client $client)
    {
        return $client->toJson();
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @return \Illuminate\View\View
     */
    public function edit(Client $client)
    {
        $data = [];
        $data['item'] = $client;

        // Load data for relationships
        $data = array_merge($data, Client::load_edit());

        return view('clients.create_edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(UpdateClientRequest $request, Client $client)
    {
        $validated = $request->validated();

        $client->update($validated);

        return redirect()->route('clients.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Client $client)
    {
        $client->delete();

        return redirect()->route('clients.index');
    }
}
