<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Category;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\QueryException; // PENAMBAHAN: Untuk menangkap error constraint database

class AdminCategoryController extends Controller
{
    // 1. Ambil Daftar Kategori (Read)
    public function index() {
        try {
            // Semua pengguna (termasuk admin cabang) diizinkan melihat daftar kategori
            $categories = Category::orderBy('name', 'asc')->get();
            return response()->json(['success' => true, 'data' => $categories]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // 2. Simpan Kategori Baru (Create)
    public function store(Request $request) {
        $user = $request->user();

        // PENAMBAHAN: Proteksi Hak Akses Pusat (Enterprise Data)
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menambah Master Kategori Produk.'
            ], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'image' => 'nullable|image|mimes:png,jpg,jpeg|max:1024'
        ]);

        try {
            $category = new Category();
            $category->name = $request->name;
            $category->is_active = $request->is_active ?? 1;

            if ($request->hasFile('image')) {
                $path = $request->file('image')->store('icons/categories', 'public');
                $category->image_path = $path;
            }

            $category->save();
            return response()->json(['success' => true, 'message' => 'Kategori berhasil dibuat!']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // 3. Update Kategori (Edit)
    public function update(Request $request, $id) {
        $user = $request->user();

        // PENAMBAHAN: Proteksi Hak Akses Pusat
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengubah Master Kategori Produk.'
            ], 403);
        }

        try {
            $category = Category::findOrFail($id);
            
            $request->validate([
                'name' => 'required|string|max:255',
                'image' => 'nullable|image|mimes:png,jpg,jpeg|max:1024'
            ]);

            $category->name = $request->name;
            // Hanya update status aktif jika dikirimkan dari frontend
            if ($request->has('is_active')) {
                 $category->is_active = $request->is_active;
            }

            if ($request->hasFile('image')) {
                // Hapus gambar lama jika ada
                if ($category->image_path) {
                    Storage::disk('public')->delete($category->image_path);
                }
                $path = $request->file('image')->store('icons/categories', 'public');
                $category->image_path = $path;
            }

            $category->save();
            return response()->json(['success' => true, 'message' => 'Kategori berhasil diperbarui!']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // 4. Toggle Status (Aktif/Non-Aktif dari Switch UI)
    public function toggleStatus(Request $request, $id) {
        $user = $request->user();

        // PENAMBAHAN: Proteksi Hak Akses Pusat
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengubah status Kategori Produk.'
            ], 403);
        }

        try {
            $category = Category::findOrFail($id);
            $category->is_active = !$category->is_active;
            $category->save();

            return response()->json([
                'success' => true,
                'message' => 'Status berhasil diubah',
                'is_active' => $category->is_active
            ]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // 5. Hapus Kategori (Delete)
    public function destroy(Request $request, $id) {
        $user = $request->user();

        // PENAMBAHAN: Proteksi Hak Akses Pusat
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menghapus Master Kategori Produk.'
            ], 403);
        }

        try {
            $category = Category::findOrFail($id);
            
            if ($category->image_path) {
                Storage::disk('public')->delete($category->image_path);
            }
            
            $category->delete();
            return response()->json(['success' => true, 'message' => 'Kategori berhasil dihapus!']);
        } catch (QueryException $e) {
            // PROTEKSI ENTERPRISE: Menangkap constraint violation (Kategori sudah terikat dengan produk)
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Kategori tidak dapat dihapus karena masih digunakan oleh satu atau lebih Produk. Silakan hapus atau pindahkan produk terkait terlebih dahulu.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Gagal menghapus kategori: Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Gagal menghapus kategori: ' . $e->getMessage()], 500);
        }
    }
}