<?php

namespace App\Http\Controllers\BackendController;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Berita;
use HTMLPurifier;
use HTMLPurifier_Config;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\File;



class BeritaController extends Controller
{
    public function index()
    {
        $beritas = Berita::orderBy('tanggal_berita', 'desc')->paginate(10); // Use paginate, not get or all
        return view('admin.berita.index', compact('beritas'));
    }

    public function create()
    {
        $token = mt_rand(100000, 999999);
        $secret_key = config('app.secret_key'); // Add a secret key in config if needed
        return view('admin.berita.create', compact('token', 'secret_key'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'judul' => 'required|string|max:255',
            'ringkasan' => 'required|string',
            'content' => 'required|string',
            'tanggal_berita' => 'required|date',
            'file_foto' => 'nullable|mimes:webp|max:2048',
        ]);

        $config = HTMLPurifier_Config::createDefault();
        $config->set('HTML.Allowed', 'p,strong,em,a[href|title],ul,ol,li,br,img[src|alt|title]');
        $purifier = new HTMLPurifier($config);

        // Sanitasi konten
        $sanitizedContent = $purifier->purify($request->input('content'));

        // Siapkan data untuk disimpan
        $data = $request->all();
        $data['content'] = $sanitizedContent;
        $data['slug'] = Str::slug($request->input('judul')); // Generate slug dari judul
        $data['path'] = '';

        // Proses upload file jika ada
        if ($request->hasFile('file_foto')) {
            $file = $request->file('file_foto');
            $file->storeAs('public/berita', $file->hashName());
            $gambar = $file->hashName(); // Simpan nama hash dari file
            $data['file_foto'] = $gambar;
        }

        // Simpan data ke dalam model Berita
        Berita::create($data);

        // Redirect dengan pesan sukses
        return redirect()->route('berita')->with('message', 'Berita berhasil ditambahkan.')->with('alert-type', 'success');
    }

    public function edit($id)
    {
        $berita = Berita::findOrFail($id);
        $token = mt_rand(100000, 999999);
        $secret_key = config('app.secret_key');
        return view('admin.berita.edit', compact('berita', 'token', 'secret_key'));
    }

    public function update(Request $request, $id)
{
    $berita = Berita::findOrFail($id);

    $request->validate([
        'judul' => 'required|string|max:255',
        'ringkasan' => 'required|string',
        'content' => 'required|string',
        'tanggal_berita' => 'required|date',
        'file_foto' => 'nullable|mimes:webp|max:2048',
    ]);

    $config = HTMLPurifier_Config::createDefault();
    $config->set('HTML.Allowed', 'p,strong,em,a[href|title],ul,ol,li,br,img[src|alt|title]');
    $purifier = new HTMLPurifier($config);
    $sanitizedContent = $purifier->purify($request->input('content'));

    // Ambil data yang akan diupdate (tanpa file_foto dulu)
    $data = [
        'judul' => $request->input('judul'),
        'ringkasan' => $request->input('ringkasan'),
        'content' => $sanitizedContent,
        'tanggal_berita' => $request->input('tanggal_berita'),
    ];

    // Jika ada file foto baru
    if ($request->hasFile('file_foto')) {
        if ($berita->file_foto) {
            Storage::delete('public/berita/' . $berita->file_foto);
        }
        $file = $request->file('file_foto');
        $fileName = $file->hashName();
        $file->storeAs('public/berita', $fileName);
        $data['file_foto'] = $fileName;
    }

    $berita->update($data);

    return redirect()->route('berita')->with('message', 'Berita berhasil diperbarui.')->with('alert-type', 'success');
}

/**
 * Upload gambar dari Quill editor
 */
public function uploadImage(Request $request)
{
    // Validasi file
    $request->validate([
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:2048'
    ]);

    if ($request->hasFile('image')) {
        $file = $request->file('image');
        
        // Buat nama file unik
        $fileName = time() . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
        
        // Simpan ke storage/app/public/berita/content
        $path = $file->storeAs('public/berita/content', $fileName);
        
        // Generate URL yang bisa diakses publik
        $url = Storage::url('berita/content/' . $fileName);
        
        return response()->json([
            'success' => true,
            'url' => $url
        ]);
    }

    return response()->json([
        'success' => false,
        'message' => 'Tidak ada file yang diupload'
    ]);
}


public function destroy($id)
{
    $berita = Berita::findOrFail($id);

    if ($berita->file_foto) {
        $imagePath = 'public/berita/' . $berita->file_foto;
        if (Storage::exists($imagePath)) {
            Storage::delete($imagePath);
        }
    }

    $berita->delete();

    return redirect()->route('berita')->with('message', 'Berita berhasil dihapus.')->with('alert-type', 'success');
}

}
