<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Bookmark;
use Illuminate\Support\Facades\Auth;

class BookmarkController extends Controller
{
    public function index()
    {
        $bookmarks = Bookmark::where('user_id', Auth::id())->get();
        return view('bookmarks.bookmarks', compact('bookmarks'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'nullable|string|max:255',
            'url' => 'required|url|max:500',
            'category' => 'nullable|string|max:100',
            'description' => 'nullable|string',
        ], [
            'url.required' => 'URL tidak boleh kosong.',
            'url.url' => 'URL harus dalam format yang valid.',
        ]);

        Bookmark::create([
            'user_id' => Auth::id(),
            'title' => $request->title,
            'url' => $request->url,
            'category' => $request->category,
            'description' => $request->description,
        ]);

        return redirect()->route('bookmarks.index')->with('success', 'Link berhasil disimpan!');
    }

    public function destroy($id)
    {
        $bookmark = Bookmark::where('user_id', Auth::id())->findOrFail($id);
        $bookmark->delete();

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