<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Repositories\Interfaces\PaintingCategoryInterface;
use Illuminate\Http\Request;

class PaintingCategoryController extends Controller
{
    protected $categoryRepo;

    public function __construct(PaintingCategoryInterface $categoryRepo)
    {
        $this->categoryRepo = $categoryRepo;
    }

    // Display list view
    public function index(Request $request)
    {
        $categories = $this->categoryRepo->list($request);
        return view('Admin.PaintingCategory.list', compact('categories'));
    }

    // Store new category (AJAX)
    public function store(Request $request)
    {
        $request->validate([
            'name_en' => 'required|string|max:255',
            'is_show_in_home' => 'nullable|in:0,1',
            'status'  => 'nullable|in:0,1',
        ]);

        $data = [
            'name_en' => $request->name_en,
            'is_show_in_home' => $request->is_show_in_home ?? 0,
            'status'  => $request->status ?? 1,
        ];

        $category = $this->categoryRepo->store($data);
        return response()->json(['success' => true, 'category' => $category]);
    }

    // Get category data for editing (AJAX)
    public function edit($id)
    {
        $category = $this->categoryRepo->find($id);
        if (!$category) {
            return response()->json(['success' => false, 'message' => 'Category not found'], 404);
        }
        return response()->json(['success' => true, 'category' => $category]);
    }

    // Update category (AJAX)
    public function update(Request $request, $id)
    {
        $request->validate([
            'name_en' => 'required|string|max:255',
            'is_show_in_home' => 'nullable|in:0,1',
            'status'  => 'nullable|in:0,1',
        ]);

        $data = [
            'name_en' => $request->name_en,
            'is_show_in_home' => $request->is_show_in_home ?? 0,
            'status'  => $request->status ?? 1,
        ];

        $category = $this->categoryRepo->update($id, $data);
        if (!$category) {
            return response()->json(['success' => false, 'message' => 'Category not found'], 404);
        }
        return response()->json(['success' => true, 'category' => $category]);
    }

    // Soft delete category (AJAX)
    public function destroy($id)
    {
        $category = $this->categoryRepo->delete($id);
        if (!$category) {
            return response()->json(['success' => false, 'message' => 'Category not found'], 404);
        }
        return response()->json(['success' => true]);
    }
}
