<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;
use App\Models\Setting;
use Illuminate\Support\Facades\Storage;

class CategoryController extends Controller
{
    public function index(Request $request)
    {
        $query = Category::with(['parent', 'children']);

        // Filter berdasarkan jenis kategori
        if ($request->filled('filter')) {
            if ($request->filter === 'parent') {
                $query->whereNull('parent_id');
            } elseif ($request->filter === 'child') {
                $query->whereNotNull('parent_id');
            }
        }

        // Cek apakah ada input pencarian
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('type', 'like', "%{$search}%");
            });
        }

        $itemsPerPage = (int) Setting::get('items_per_page', 10);
        $categories = $query->orderBy('parent_id')->orderBy('name')->paginate($itemsPerPage)->withQueryString();

        // Ambil semua parent categories untuk dropdown
        $parentCategories = Category::whereNull('parent_id')->orderBy('name')->get();

        // Tetap bawa query pencarian agar pagination tidak hilang
        $categories->appends($request->only('search', 'filter'));

        return view('admin.categories.index', compact('categories', 'parentCategories'));
    }

    public function create()
    {
        // Ambil semua kategori besar (parent) untuk dropdown
        $parentCategories = Category::whereNull('parent_id')->orderBy('name')->get();
        return view('admin.categories.create', compact('parentCategories'));
    }

    public function store(Request $request)
    {
        // Validasi dasar
        $rules = [
            'name' => 'required|string|max:255',
            'type' => 'required|in:service',
            'parent_id' => 'nullable|exists:categories,id',
        ];

        // Jika parent_id ada (sub kategori), gambar wajib
        // Jika parent_id null (kategori besar), gambar opsional
        if ($request->filled('parent_id')) {
            $rules['image'] = 'required|image|mimes:jpeg,png,jpg,gif,webp,svg';
        } else {
            $rules['image'] = 'nullable|image|mimes:jpeg,png,jpg,gif,webp,svg';
        }

        $request->validate($rules);

        $data = $request->only(['name', 'type', 'parent_id']);

        // Jika parent_id kosong, set ke null
        if (empty($data['parent_id'])) {
            $data['parent_id'] = null;
        }

        // Untuk sub kategori, gambar wajib
        if ($request->hasFile('image')) {
            $imagePath = $request->file('image')->store('categories', 'uploads');
            $data['image'] = $imagePath;
        } elseif ($data['parent_id']) {
            // Jika sub kategori tapi tidak ada gambar, return error
            return redirect()->back()
                ->withErrors(['image' => 'Gambar wajib diisi untuk sub kategori karena akan ditampilkan di halaman depan.'])
                ->withInput();
        }

        Category::create($data);

        $message = $data['parent_id'] ? 'Sub kategori berhasil ditambahkan!' : 'Kategori berhasil ditambahkan!';
        return redirect()->route('admin.categories.index')
            ->with('add_message', $message);
    }

    public function edit($id)
    {
        $category = Category::findOrFail($id);
        // Ambil semua kategori besar (parent) untuk dropdown, kecuali kategori yang sedang diedit
        $parentCategories = Category::whereNull('parent_id')
            ->where('id', '!=', $id)
            ->orderBy('name')
            ->get();
        return view('admin.categories.edit', compact('category', 'parentCategories'));
    }

    public function update(Request $request, $id)
    {
        $category = Category::findOrFail($id);

        // Validasi dasar
        $rules = [
            'name' => 'required|string|max:255',
            'type' => 'required|string|in:service',
            'parent_id' => 'nullable|exists:categories,id',
        ];

        // Jika parent_id ada (sub kategori), gambar wajib (kecuali sudah ada gambar sebelumnya)
        // Jika parent_id null (kategori besar), gambar opsional
        $finalParentId = $request->filled('parent_id') ? $request->parent_id : null;
        if ($finalParentId) {
            // Jika menjadi sub kategori, wajib ada gambar (baru atau yang sudah ada)
            if (!$request->hasFile('image') && !$category->image) {
                $rules['image'] = 'required|image|mimes:jpeg,png,jpg,gif,webp,svg';
            } else {
                $rules['image'] = 'nullable|image|mimes:jpeg,png,jpg,gif,webp,svg';
            }
        } else {
            $rules['image'] = 'nullable|image|mimes:jpeg,png,jpg,gif,webp,svg';
        }

        $validated = $request->validate($rules);

        // Validasi: parent_id tidak boleh sama dengan id kategori yang sedang diedit
        if ($validated['parent_id'] == $id) {
            return redirect()->back()
                ->withErrors(['parent_id' => 'Kategori tidak dapat menjadi parent dari dirinya sendiri.'])
                ->withInput();
        }

        // Jika parent_id kosong, set ke null
        if (empty($validated['parent_id'])) {
            $validated['parent_id'] = null;
        }

        // Validasi: jika menjadi sub kategori, harus ada gambar
        if ($validated['parent_id'] && !$request->hasFile('image') && !$category->image) {
            return redirect()->back()
                ->withErrors(['image' => 'Gambar wajib diisi untuk sub kategori karena akan ditampilkan di halaman depan.'])
                ->withInput();
        }

        // Jika ada gambar baru, hapus gambar lama
        if ($request->hasFile('image')) {
            if ($category->image && Storage::disk('uploads')->exists($category->image)) {
                Storage::disk('uploads')->delete($category->image);
            }

            $validated['image'] = $request->file('image')->store('categories', 'uploads');
        } else {
            // Jika tidak ada gambar baru, pertahankan gambar lama
            $validated['image'] = $category->image;
        }

        $category->update($validated);

        $message = $validated['parent_id'] ? 'Sub kategori berhasil diperbarui!' : 'Kategori berhasil diperbarui!';
        return redirect()->route('admin.categories.index')
            ->with('add_message', $message);
    }

    public function destroy($id)
    {
        $category = Category::findOrFail($id);

        // Langsung pakai nama file yang tersimpan di database (sudah termasuk folder "categories/")
        if ($category->image && Storage::disk('uploads')->exists($category->image)) {
            Storage::disk('uploads')->delete($category->image);
        }

        $category->delete();

        return redirect()->route('admin.categories.index')
            ->with('add_message', 'Kategori dan gambar berhasil dihapus!');
    }

    public function bulkDestroy(Request $request)
    {
        // Handle JSON string from form
        $ids = $request->ids;
        if (is_string($ids)) {
            $ids = json_decode($ids, true);
        }

        $request->merge(['ids' => $ids]);

        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'exists:categories,id'
        ]);

        $deletedCount = 0;

        foreach ($ids as $id) {
            $category = Category::findOrFail($id);

            // Hapus gambar jika ada
            if ($category->image && Storage::disk('uploads')->exists($category->image)) {
                Storage::disk('uploads')->delete($category->image);
            }

            $category->delete();
            $deletedCount++;
        }

        $message = $deletedCount > 1 
            ? "{$deletedCount} kategori berhasil dihapus!" 
            : "Kategori berhasil dihapus!";

        return redirect()->route('admin.categories.index')
            ->with('add_message', $message);
    }
}
