<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Materi;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class MateriController extends Controller
{
    public function index(Request $request)
    {
        $query = Materi::latest();

        if ($request->search) {
            $query->where('judul', 'like', "%{$request->search}%");
        }
        if ($request->kategori) {
            $query->where('kategori', $request->kategori);
        }

        return response()->json([
            'success' => true,
            'data'    => $query->paginate($request->per_page ?? 15),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'judul'        => 'required|string|max:255',
            'konten'       => 'required|string',
            'kategori'     => 'required|in:dasar,furudh,ashabah,mahjub,kondisi',
            'urutan'       => 'integer|min:0',
            'is_published' => 'boolean',
            'foto'         => 'nullable|image|max:2048',
        ]);

        $data = $request->only(['judul', 'konten', 'kategori', 'urutan', 'is_published']);
        $data['slug'] = Str::slug($request->judul);

        if ($request->hasFile('foto')) {
            $file     = $request->file('foto');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $folder   = public_path('uploads/materi');
            if (!is_dir($folder)) mkdir($folder, 0755, true);
            $file->move($folder, $filename);
            $data['foto'] = 'uploads/materi/' . $filename;
        }

        $materi = Materi::create($data);

        return response()->json([
            'success' => true,
            'message' => 'Materi berhasil ditambahkan.',
            'data'    => $materi,
        ], 201);
    }

    public function show($id)
    {
        return response()->json([
            'success' => true,
            'data'    => Materi::findOrFail($id),
        ]);
    }

    public function update(Request $request, $id)
    {
        $materi = Materi::findOrFail($id);

        $request->validate([
            'judul'        => 'required|string|max:255',
            'konten'       => 'required|string',
            'kategori'     => 'required|in:dasar,furudh,ashabah,mahjub,kondisi',
            'urutan'       => 'integer|min:0',
            'is_published' => 'boolean',
            'foto'         => 'nullable|image|max:2048',
        ]);

        $data = $request->only(['judul', 'konten', 'kategori', 'urutan', 'is_published']);

        if ($request->hasFile('foto')) {
            // Hapus foto lama
            if ($materi->foto && file_exists(public_path($materi->foto))) {
                unlink(public_path($materi->foto));
            }
            $file     = $request->file('foto');
            $filename = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
            $folder   = public_path('uploads/materi');
            if (!is_dir($folder)) mkdir($folder, 0755, true);
            $file->move($folder, $filename);
            $data['foto'] = 'uploads/materi/' . $filename;
        }

        $materi->update($data);

        return response()->json([
            'success' => true,
            'message' => 'Materi berhasil diperbarui.',
            'data'    => $materi->fresh(),
        ]);
    }

    public function destroy($id)
    {
        $materi = Materi::findOrFail($id);
        if ($materi->foto && file_exists(public_path($materi->foto))) {
            unlink(public_path($materi->foto));
        }
        $materi->delete();

        return response()->json([
            'success' => true,
            'message' => 'Materi berhasil dihapus.',
        ]);
    }
}
