<?php

namespace App\Http\Controllers;

use App\Classes\EditLogHistory;
use App\Models\ClientSource;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;

class ClientSourceController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:client-source')->only('index', 'create', 'store', 'edit', 'update');
    }

    public function index()
    {
        $data = [
            'sources' => ClientSource::orderBy('id', 'asc')->get(),
        ];

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('clientSource.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|unique:client_sources,name',
        ]);

        $source = new ClientSource();
        $source->name = $request->name;
        $source->save();

        Toastr::success('Client source successfully created', 'Success');

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

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = [
            'source' => ClientSource::findOrFail($id),
        ];

        return view('clientSource.edit', $data);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required|unique:client_sources,name,' . $id,
        ]);

        $type = 'Client Source';
        $old_info = ClientSource::findOrFail($id);

        $source = ClientSource::findOrFail($id);
        $source->name = $request->name;
        $source->save();

        $new_info = ClientSource::findOrFail($id);
        (new EditLogHistory)->editLogSave($source, $type, $old_info, $new_info);

        Toastr::success('Client source successfully updated', 'Success');

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    // public function destroy($id)
    // {
    // $source = ClientSource::findOrFail($id);
    // $source->delete();

    // Toastr::success('Client source successfully deleted', 'Success');

    // return redirect()->route('client-source.index');
    // }
}
