<?php

namespace App\Http\Controllers;

use App\Models\ImportantLink;
use Illuminate\Http\Request;

class ImportantLinkController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = ImportantLink::query();

        if ($request->filled('q')) {
            $q = $request->input('q');
            $query->where('name', 'like', "%{$q}%")
                  ->orWhere('link', 'like', "%{$q}%");
        }

        $links = $query->orderByDesc('created_at')->paginate(10)->appends($request->query());
        return view('important-links.index', compact('links'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('important-links.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'link' => 'required|url',
        ]);

        ImportantLink::create($request->all());

        return redirect()->route('important-links.index')->with('success', 'Link berhasil ditambahkan.');
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $link = ImportantLink::findOrFail($id);
        return view('important-links.edit', compact('link'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'link' => 'required|url',
        ]);

        $link = ImportantLink::findOrFail($id);
        $link->update($request->all());

        return redirect()->route('important-links.index')->with('success', 'Link berhasil diperbarui.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $link = ImportantLink::findOrFail($id);
        $link->delete();

        return redirect()->route('important-links.index')->with('success', 'Link berhasil dihapus.');
    }
}
