<?php

namespace App\Http\Controllers\AdminBackend;

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

class AdminMateriController extends Controller
{
    public function index()
    {
        $materi = DB::table('materi')->get();
        return view('admin_backend.admin_materi', compact('materi'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'id_style'    => 'required|integer',
            'konten'      => 'nullable|file|mimes:jpeg,jpg,png,mp4,mov|max:10240',
            'audio'       => 'nullable|file|mimes:mp3,wav|max:10240',
            'teks'        => 'nullable|string',
            'kodesoal'    => 'nullable|string',
            'outputkode'  => 'nullable|string',
        ]);

        // Data dasar
        $data = $request->only(['id_style', 'teks', 'kodesoal', 'outputkode']);

        // Upload konten (gambar/video) ke storage/app/public/materi
        if ($request->hasFile('konten')) {
            $data['konten'] = $request->file('konten')->store('materi', 'public');
        }

        // Upload audio ke storage/app/public/audio
        if ($request->hasFile('audio')) {
            $data['audio'] = $request->file('audio')->store('audio', 'public');
        }

        // Auto-increment manual id_materi per id_style
        $maxId = \App\Models\Materi::where('id_style', $data['id_style'])->max('id_materi');
        $data['id_materi'] = $maxId ? $maxId + 1 : 1;

        \App\Models\Materi::create($data);

        return redirect()->route('adminmateri.index')->with('success', 'Materi berhasil ditambah');
    }

    public function edit($id_style, $id_materi)
    {
        $item = DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->first();

        return response()->json($item);
    }

    public function update(Request $request, $id_style, $id_materi)
    {
        $request->validate([
            'konten'   => 'nullable|file|mimes:jpg,jpeg,png,mp4,mov|max:10240',
            'audio'    => 'nullable|file|mimes:mp3,wav,mpeg|max:10240',
            'teks'     => 'nullable|string',
            'kodesoal' => 'nullable|string',
            'outputkode' => 'nullable|string',
        ]);

        if (!$request->hasFile('konten') && !$request->hasFile('audio') && empty($request->teks) && empty($request->kodesoal) && empty($request->outputkode)) {
            return back()->withErrors(['konten' => 'Minimal salah satu konten, audio, teks, kodesoal, atau outputkode harus diisi.'])->withInput();
        }

        $materi = DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->first();

        if (!$materi) {
            return back()->with('error', 'Data tidak ditemukan.');
        }

        $data = [
            'teks' => $request->teks,
            'kodesoal' => $request->kodesoal,
            'outputkode' => $request->outputkode,
        ];

        if ($request->hasFile('konten')) {
            if ($materi->konten && Storage::disk('public')->exists($materi->konten)) {
                Storage::disk('public')->delete($materi->konten);
            }
            $data['konten'] = $request->file('konten')->store('materi', 'public');
        }

        if ($request->hasFile('audio')) {
            if ($materi->audio && Storage::disk('public')->exists($materi->audio)) {
                Storage::disk('public')->delete($materi->audio);
            }
            $data['audio'] = $request->file('audio')->store('audio', 'public');
        }

        DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->update($data);

        return redirect()->route('adminmateri.index')->with('success', 'Materi berhasil diperbarui.');
    }

    public function destroy($id_style, $id_materi)
    {
        $materi = DB::table('materi')
            ->where('id_style', $id_style)
            ->where('id_materi', $id_materi)
            ->first();

        if ($materi) {
            if ($materi->konten && Storage::disk('public')->exists($materi->konten)) {
                Storage::disk('public')->delete($materi->konten);
            }

            if ($materi->audio && Storage::disk('public')->exists($materi->audio)) {
                Storage::disk('public')->delete($materi->audio);
            }

            DB::table('materi')
                ->where('id_style', $id_style)
                ->where('id_materi', $id_materi)
                ->delete();

            return redirect()->route('adminmateri.index')->with('success', 'Materi berhasil dihapus.');
        }

        return redirect()->route('adminmateri.index')->with('error', 'Materi tidak ditemukan.');
    }

}
