<?php

namespace App\Http\Controllers\BackendController;

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

class KurikulumController extends Controller
{
    public function index()
    {
        $kurikulums = Kurikulum::paginate(8);
        return view('admin.kurikulum.index', compact('kurikulums'));
    }

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

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'jurusan' => 'required|string|max:255',
            'file' => 'required|file|mimes:pdf,jpeg,jpg,png,webp|max:2048',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $fileName = null;
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $fileName = $file->hashName();
            $file->storeAs('public/kurikulumFiles', $fileName);
        }

        Kurikulum::create([
            'jurusan' => $request->jurusan,
            'file' => $fileName,
        ]);

        return redirect()->route('kurikulum.index')->with('message', 'Kurikulum berhasil ditambahkan!')->with('alert-type', 'success');
    }

    public function edit($id)
    {
        $kurikulum = Kurikulum::findOrFail($id);
        return view('admin.kurikulum.edit', compact('kurikulum'));
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'jurusan' => 'required|string|max:255',
            'file' => 'nullable|file|mimes:pdf,jpeg,jpg,png,webp|max:2048',
        ]);

        $kurikulum = Kurikulum::findOrFail($id);

        if ($request->hasFile('file')) {
            if ($kurikulum->file && Storage::exists('public/kurikulumFiles/' . $kurikulum->file)) {
                Storage::delete('public/kurikulumFiles/' . $kurikulum->file);
            }

            $newFile = $request->file('file');
            $newFileName = $newFile->hashName();
            $newFile->storeAs('public/kurikulumFiles', $newFileName);
            $kurikulum->file = $newFileName;
        }

        $kurikulum->jurusan = $request->jurusan;
        $kurikulum->save();

        return redirect()->route('kurikulum.index')->with('message', 'Kurikulum berhasil diperbarui!')->with('alert-type', 'success');
    }

    public function destroy($id)
    {
        $kurikulum = Kurikulum::findOrFail($id);

        if ($kurikulum->file && Storage::exists('public/kurikulumFiles/' . $kurikulum->file)) {
            Storage::delete('public/kurikulumFiles/' . $kurikulum->file);
        }

        $kurikulum->delete();

        return redirect()->route('kurikulum.index')->with('message', 'Kurikulum berhasil dihapus!')->with('alert-type', 'success');
    }
}
