<?php

namespace App\Http\Controllers\Admin;

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

class ProdukController extends Controller
{
    public function index(Request $request)
    {
        // 1. Logika Statistik (Tetap sama)
        $jumlahBulanIni = \App\Models\Produk::whereMonth('created_at', date('m'))
            ->whereYear('created_at', date('Y'))->count();

        $totalProduk = \App\Models\Produk::count();

        $jumlahBulanLalu = \App\Models\Produk::whereMonth('created_at', date('m', strtotime('first day of last month')))
            ->whereYear('created_at', date('Y', strtotime('first day of last month')))->count();

        if ($jumlahBulanLalu > 0) {
            $pertumbuhan = (($jumlahBulanIni - $jumlahBulanLalu) / $jumlahBulanLalu) * 100;
        } else {
            $pertumbuhan = $jumlahBulanIni > 0 ? 100 : 0;
        }

        // 2. Logika Pencarian (Baru)
        // Mulai query dari model
        $query = \App\Models\Produk::query();

        if ($request->has('search') && $request->search != '') {
            $search = $request->search;
            $query->where('nama_produk', 'LIKE', "%{$search}%")
                ->orWhere('id_produk', 'LIKE', "%{$search}%");
        }

        $produk = $query->paginate(5)->withQueryString();

        // Jika permintaan datang dari AJAX, kembalikan hanya view tabelnya saja
        if ($request->ajax()) {
            return view('admin.partials.tabel-produk', compact('produk'))->render();
        }

        return view('admin.produk', compact('produk', 'totalProduk', 'pertumbuhan'));
    }

    public function store(Request $request)
    {
        // Ambil data selain gambar
        $data = $request->except('gambar');

        // Proses upload hanya jika ada file
        if ($request->hasFile('gambar')) {
            $file = $request->file('gambar');
            $namaFile = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('images/produk'), $namaFile);
            $data['gambar'] = 'images/produk/' . $namaFile;
        }

        // Simpan ke database tanpa mempedulikan status gambar
        \App\Models\Produk::create($data);
        return response()->json(['success' => true]);
    }

    public function update(Request $request, $id = null)
    {
        // Ambil id dari route param ATAU dari request body (untuk Flutter)
        $id = $id ?? $request->input('id');
        $produk = \App\Models\Produk::findOrFail($id);

        $data = $request->except(['gambar', 'id']);

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

            $file = $request->file('gambar');
            $namaFile = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('images/produk'), $namaFile);
            $data['gambar'] = 'images/produk/' . $namaFile;
        }

        $produk->update($data);

        // ✅ Return JSON agar Flutter bisa baca response-nya
        return response()->json(['success' => true, 'message' => 'Produk berhasil diupdate!']);
    }

    public function destroy($id)
    {
        $produk = \App\Models\Produk::findOrFail($id);

        // Hapus file gambar jika ada
        if ($produk->gambar && file_exists(public_path($produk->gambar))) {
            @unlink(public_path($produk->gambar));
        }

        $produk->delete();

        return redirect()->back()->with('success', 'Produk berhasil dihapus!');
    }
}
