<?php

namespace App\Http\Controllers;

use App\Models\Mapel;
use App\Models\Materi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class MateriController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $materi = Materi::with('mata_pelajaran')->get();
        $mapel = Mapel::all();

        return view('materi.index', ['materi' => $materi, 'mapel' => $mapel]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'lampiran_materi' => 'required|mimes:pdf',
            'judul_materi' => 'required|unique:materi',
            'mata_pelajaran' => 'required',
            'keterangan' => 'required',
        ]);

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

        try {
            DB::beginTransaction();

            $lampiran_path = null;
            $file_path_lampiran = 'materi';

            if ($request->file('lampiran_materi')) {
                $file = $request->file('lampiran_materi');
                $filename = time() . '_' . $file->getClientOriginalName();
                $lampiran_path = $file->storeAs($file_path_lampiran, $filename, 'public');
            }

            $materi = new Materi();
            $materi->judul_materi = $request->judul_materi;
            $materi->keterangan = $request->keterangan;
            $materi->lampiran_materi = $lampiran_path;
            $materi->id_mapel = $request->mata_pelajaran;
            $materi->save();

            DB::commit();

            return redirect()->back()->with('success', 'Data materi berhasil ditambahkan.');
        } catch (\Exception $e) {
            DB::rollback();
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $validator = Validator::make($request->all(), [
            'lampiran_materi' => 'mimes:pdf',
            'judul_materi' => 'required|unique:materi,judul_materi,' . $id . ',id_materi',
            'mata_pelajaran' => 'required',
            'keterangan' => 'required',
        ]);

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

        try {
            $materi = Materi::find($id);

            if (!$materi) {
                throw new \Exception('Materi tidak ditemukan. Silahkan coba kembali.');
            }

            DB::beginTransaction();

            $lampiran_path = null;
            $file_path_lampiran = 'uploads/lampiran';

            if ($request->file('lampiran_materi')) {
                if ($lampiran_path) {
                    Storage::disk('public')->delete($lampiran_path);
                }

                $foto = $request->file('lampiran_materi');
                $lampiran_path = $foto->store($file_path_lampiran, 'public');
            }

            $materi->judul_materi = $request->judul_materi;
            $materi->keterangan = $request->keterangan;
            $materi->lampiran_materi = $lampiran_path;
            $materi->id_mapel = $request->mata_pelajaran;
            $materi->save();

            DB::commit();

            return redirect()->back()->with('success', 'Data materi berhasil diperbarui.');
        } catch (\Exception $e) {
            DB::rollback();
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $materi = Materi::findOrFail($id);
        $materi->delete();

        return redirect()->back()->with('success', 'Data materi berhasil dihapus.');
    }
}
