<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Backend\LinkRequest;
use App\Models\SettingManagement\Link;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Cache;

class LinkController extends Controller{

    public function __construct(){

        $this->middleware('permission:link-list')
            ->only(["index"]);

        $this->middleware('permission:link-show')
            ->only(["show"]);

        $this->middleware('permission:link-create')
            ->only(["store"]);

        $this->middleware('permission:link-update')
            ->only(['update',"edit"]);

        $this->middleware('permission:link-delete')
            ->only(['destroy']);

    }

    public function index(): View{
        $links = Link::latest()->paginate(5);
        return view('backend.links.index', compact('links'));
    }

    public function create(): View{
        return view('backend.links.create');
    }

    public function store(LinkRequest $request): RedirectResponse{
        Link::create($request->validated());
        Cache::forget('admin_side_menu');
        return redirect()->route('admin.links.index')->with([
            'message' => action_message("create"),
            'alert-type' => 'success'
        ]);
    }

    public function edit(Link $link): View{
        return view('backend.links.edit', compact('link'));
    }

    public function update(LinkRequest $request, Link $link): RedirectResponse{
        $link->update($request->validated());

        Cache::forget('admin_side_menu');

        return redirect()->route('admin.links.index')->with([
            'message' => action_message("update"),
            'alert-type' => 'success'
        ]);
    }

    public function destroy(Link $link): RedirectResponse{
        $link->delete();
        Cache::forget('admin_side_menu');

        return redirect()->route('admin.links.index')->with([
            'message' => action_message("delete"),
            'alert-type' => 'success'
        ]);
    }
}
