<?php

namespace App\Http\Controllers;

use App\Classes\EditLogHistory;
use App\Models\TokenSource;
use Illuminate\Http\Request;

class TokenSourceController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:token-source');
    }

    public function index()
    {
        $sources = TokenSource::orderBy('name')->get();
        return view('tokenSource.index', [
            'sources' => $sources,
        ]);
    }

    public function create()
    {
        return view('tokenSource.create');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255|unique:token_sources,name',
        ]);

        TokenSource::create($request->only('name'));
        return redirect()->route('tokenSource.index')->with('message', 'Token Source Added Successfully');
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $tokenSource = TokenSource::findOrFail($id);
        return view('tokenSource.edit', ['tokenSource' => $tokenSource]);
    }

    public function update(Request $request, $id)
    {
        $tokenSource = TokenSource::findOrFail($id);
        $this->validate($request, [
            'name' => ['required', 'string', 'max:255', 'unique:token_sources,name,' . $tokenSource->id],
        ]);
        $type = 'Token Source';
        $old_info = TokenSource::findOrFail($id);

        $tokenSource->update($request->only('name'));

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

        return redirect()->route('tokenSource.index')->with('message', 'Token Source Updated Successfully');
    }

    public function destroy($id)
    {
        // $tokenSource = TokenSource::findOrFail($id);
        // $tokenSource->delete();
        // return redirect()->route('tokenSource.index')->with('success_message', 'Token Source Deleted Successfully');
    }
}
