<?php

namespace App\Http\Controllers\Admin;

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

class EPaperController extends Controller
{
    public function index()
    {
        $epapers = EPaper::latest('date')->paginate(20);
        return view('admin.epapers.index', compact('epapers'));
    }

    public function create()
    {
        return view('admin.epapers.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'title'      => 'required|string|max:255',
            'pdf_file'   => 'required|mimes:pdf|max:20480',
            'date'       => 'required|date',
        ]);

        $path = $request->file('pdf_file')->store('epapers', 'public');

        EPaper::create([
            'title'    => $request->title,
            'pdf_path' => $path,
            'date'     => $request->date,
        ]);

        return redirect()->route('admin.e-papers.index')->with('success', 'E-Paper uploaded successfully.');
    }

    public function destroy(EPaper $e_paper)
    {
        Storage::disk('public')->delete($e_paper->pdf_path);
        $e_paper->delete();
        return redirect()->route('admin.e-papers.index')->with('success', 'E-Paper deleted.');
    }
}
