<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Resource;
use App\Models\ResourceCategory;
use Illuminate\Http\Request;

class ResourceController extends Controller
{
    public function index() {
        $resources = Resource::with('category')->orderBy('category_id')->orderBy('sort_order')->get();
        return view('admin.pages.resources.index', compact('resources'));
    }
    public function create() {
        $categories = ResourceCategory::orderBy('sort_order')->get();
        return view('admin.pages.resources.form', compact('categories'));
    }
    public function store(Request $request) {
        $request->validate(['title'=>'required','category_id'=>'required']);
        $data = $request->only(['title','description','category_id','resource_type','external_url','youtube_embed_id','sort_order','is_active']);
        if ($request->hasFile('file_path'))
            $data['file_path'] = basename($request->file('file_path')->store('brochures','public'));
        Resource::create($data);
        return redirect()->route('admin.resources.index')->with('success','Resource saved.');
    }
    public function edit(Resource $resource) {
        $categories = ResourceCategory::orderBy('sort_order')->get();
        return view('admin.pages.resources.form', compact('resource','categories'));
    }
    public function update(Request $request, Resource $resource) {
        $request->validate(['title'=>'required','category_id'=>'required']);
        $data = $request->only(['title','description','category_id','resource_type','external_url','youtube_embed_id','sort_order','is_active']);
        if ($request->hasFile('file_path'))
            $data['file_path'] = basename($request->file('file_path')->store('brochures','public'));
        $resource->update($data);
        return redirect()->route('admin.resources.index')->with('success','Resource updated.');
    }
    public function destroy(Resource $resource) {
        $resource->delete();
        return redirect()->route('admin.resources.index')->with('success','Resource deleted.');
    }
}
