<?php

namespace App\Http\Controllers;

use App\Models\TokenCat;
use App\Models\TokenCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TokenCodeController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:token-code',['only'=>['index']]);
    }

    public function index()
    {
        // $tokenCode = TokenCode::all();
        $tokenCode = DB::table('token_codes')
            ->join('token_cats', 'token_codes.tokenCategory', '=', 'token_cats.id')
            ->select('token_codes.*', 'token_cats.tokenCategory')
            ->get();

        return view('tokenCode.index', [
            'tokenCode' => $tokenCode,
            // 'page_title' => 'Support',
            // 'add_button' => 'true',
            // 'url' => route('tokenCode.create'),
            // 'class' => 'text-white bg-blue-600',
            // 'value' => 'Add New Token Code'
        ]);
    }

    public function create()
    {
        $tokenCategory = TokenCat::latest()->get();
        return view('tokenCode.create', ['tokenCategory' => $tokenCategory]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'tokenCode' => 'required|unique:token_codes'
        ]);

        $tokenCode = new TokenCode();
        $tokenCode->fill($request->all());
        $tokenCode->save();
        return redirect()->route('tokenCode.index')->with('success_message', 'Token Code Added Successufll');
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        $tokenCategory = TokenCat::latest()->get();
        $tokenCode = TokenCode::find($id);
        return view('tokenCode.edit', [
            'tokenCode' => $tokenCode,
            'tokenCategory' => $tokenCategory
        ]);
    }

    public function update(Request $request, $id)
    {
        $tokenCode = TokenCode::find($id);
        $this->validate($request, [
            'tokenCategory' => 'required',
            'tokenCode' => ['required', 'unique:token_codes,tokenCode,' . $tokenCode->id],
        ]);
        $tokenCode->fill($request->all());
        $tokenCode->update();
        return redirect()->route('tokenCode.index')->with('success_message', 'Token Code Update Successufll');
    }

    public function destroy($id)
    {
        $tokenCode = TokenCode::find($id);
        $tokenCode->delete();
        return redirect()->route('tokenCode.index');
    }
}
