<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Artikel;

class ManagementArtikelControllers extends Controller
{
    public function index()
    {
        $artikels = Artikel::latest()->get();
        return view('admin.management-artikel.index', compact('artikels'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'judul' => 'required|string|max:255',
            'gambar' => 'required|image|mimes:jpeg,png,jpg|max:5120',
            'deskripsi' => 'required',
            'sumber' => 'required'
        ]);

        $pathGambar = null;

        if ($request->hasFile('gambar')) {
            $file = $request->file('gambar');
            
            $fileName = time() . '_artikel_' . uniqid() . '.' . $file->getClientOriginalExtension();
            
            $file->move(public_path('uploads/artikel'), $fileName);
            
            $pathGambar = 'uploads/artikel/' . $fileName;
        }

        Artikel::create([
            'judul' => $request->judul,
            'gambar' => $pathGambar,
            'deskripsi' => $request->deskripsi,
            'sumber' => $request->sumber
        ]);

        return back()->with('success', 'Artikel berhasil ditambahkan');
    }

    public function update(Request $request, $id)
    {
        $artikel = Artikel::findOrFail($id);

        $request->validate([
            'judul' => 'required|string|max:255',
            'deskripsi' => 'required',
            'sumber' => 'required',
            'gambar' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
        ]);

        $data = [
            'judul' => $request->judul,
            'deskripsi' => $request->deskripsi,
            'sumber' => $request->sumber
        ];

        if ($request->hasFile('gambar')) {
            if ($artikel->gambar && file_exists(public_path($artikel->gambar))) {
                @unlink(public_path($artikel->gambar));
            }

            $file = $request->file('gambar');
            $fileName = time() . '_artikel_' . uniqid() . '.' . $file->getClientOriginalExtension();
            
            $file->move(public_path('uploads/artikel'), $fileName);
            $data['gambar'] = 'uploads/artikel/' . $fileName;
        }

        $artikel->update($data);

        return back()->with('success', 'Artikel berhasil diupdate');
    }

    public function destroy($id)
    {
        $artikel = Artikel::findOrFail($id);

        if ($artikel->gambar && file_exists(public_path($artikel->gambar))) {
            @unlink(public_path($artikel->gambar));
        }

        $artikel->delete();

        return back()->with('success', 'Artikel berhasil dihapus');
    }
}