<?php

namespace App\Http\Controllers\Instructor;

use App\Http\Controllers\Controller;
use App\Models\Resource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Auth;

class ResourceController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'role:instructor']);
    }

    /**
     * Display a listing of resources accessible to instructors.
     */
    public function index(Request $request)
    {
        $query = Resource::where('is_active', true)
            ->whereRaw('JSON_CONTAINS(accessible_by_roles, ?)', [json_encode('instructor')])
            ->with('uploader');

        // Search functionality
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%")
                  ->orWhere('resource_type', 'like', "%{$search}%");
            });
        }

        $resources = $query->orderBy('created_at', 'desc')->paginate(20);
        
        return view('instructor.resources.index', compact('resources'));
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $resource = Resource::where('is_active', true)
            ->whereRaw('JSON_CONTAINS(accessible_by_roles, ?)', [json_encode('instructor')])
            ->with('uploader')
            ->findOrFail($id);
            
        return view('instructor.resources.show', compact('resource'));
    }

    /**
     * Download the resource file.
     */
    public function download($id)
    {
        $resource = Resource::where('is_active', true)
            ->whereRaw('JSON_CONTAINS(accessible_by_roles, ?)', [json_encode('instructor')])
            ->findOrFail($id);

        if (!Storage::disk('public')->exists($resource->file_path)) {
            return redirect()->back()->with('error', 'File not found.');
        }

        $resource->incrementDownloadCount();

        return Storage::disk('public')->download($resource->file_path, $resource->file_name);
    }
}

