<?php

namespace App\Http\Controllers\Admin;

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:admin']);
    }

    /**
     * Display a listing of resources.
     */
    public function index(Request $request)
    {
        $query = Resource::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}%");
            });
        }

        // Filter by active status
        if ($request->has('status')) {
            if ($request->status === 'active') {
                $query->where('is_active', true);
            } elseif ($request->status === 'inactive') {
                $query->where('is_active', false);
            }
        }

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

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

    /**
     * Store a newly created resource.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'resource_type' => 'nullable|string|max:255',
            'file' => 'required|file|max:102400', // 100MB max
            'accessible_by_roles' => 'required|array',
            'accessible_by_roles.*' => 'in:admin,instructor,student',
        ]);

        $file = $request->file('file');
        $originalName = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $originalName);
        $filePath = $file->storeAs('resources', $fileName, 'public');

        Resource::create([
            'title' => $validated['title'],
            'description' => $validated['description'] ?? null,
            'resource_type' => $validated['resource_type'] ?? null,
            'file_path' => $filePath,
            'file_name' => $originalName,
            'file_extension' => $extension,
            'file_size' => $file->getSize(),
            'mime_type' => $file->getMimeType(),
            'accessible_by_roles' => $validated['accessible_by_roles'],
            'uploaded_by' => Auth::id(),
            'is_active' => true,
        ]);

        return redirect()->route('admin.resources.index')
            ->with('success', 'Resource uploaded successfully!');
    }

    /**
     * Display the specified resource.
     */
    public function show($id)
    {
        $resource = Resource::with('uploader')->findOrFail($id);
        return view('admin.resources.show', compact('resource'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $resource = Resource::findOrFail($id);
        return view('admin.resources.edit', compact('resource'));
    }

    /**
     * Update the specified resource.
     */
    public function update(Request $request, $id)
    {
        $resource = Resource::findOrFail($id);

        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'resource_type' => 'nullable|string|max:255',
            'file' => 'nullable|file|max:102400', // 100MB max
            'accessible_by_roles' => 'required|array',
            'accessible_by_roles.*' => 'in:admin,instructor,student',
            'is_active' => 'boolean',
        ]);

        // Update file if new one is uploaded
        if ($request->hasFile('file')) {
            // Delete old file
            if ($resource->file_path && Storage::disk('public')->exists($resource->file_path)) {
                Storage::disk('public')->delete($resource->file_path);
            }

            $file = $request->file('file');
            $originalName = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $fileName = time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $originalName);
            $filePath = $file->storeAs('resources', $fileName, 'public');

            $resource->file_path = $filePath;
            $resource->file_name = $originalName;
            $resource->file_extension = $extension;
            $resource->file_size = $file->getSize();
            $resource->mime_type = $file->getMimeType();
        }

        $resource->title = $validated['title'];
        $resource->description = $validated['description'] ?? null;
        $resource->resource_type = $validated['resource_type'] ?? null;
        $resource->accessible_by_roles = $validated['accessible_by_roles'];
        $resource->is_active = $request->has('is_active') ? $validated['is_active'] : $resource->is_active;
        $resource->save();

        return redirect()->route('admin.resources.index')
            ->with('success', 'Resource updated successfully!');
    }

    /**
     * Remove the specified resource.
     */
    public function destroy($id)
    {
        $resource = Resource::findOrFail($id);

        // Delete file from storage
        if ($resource->file_path && Storage::disk('public')->exists($resource->file_path)) {
            Storage::disk('public')->delete($resource->file_path);
        }

        $resource->delete();

        return redirect()->route('admin.resources.index')
            ->with('success', 'Resource deleted successfully!');
    }

    /**
     * Download the resource file.
     */
    public function download($id)
    {
        $resource = Resource::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);
    }
}

