<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ExpenseCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\QueryException; // PENAMBAHAN: Standar ERP untuk menangkap error constraint database

class ExpenseCategoryApiController extends Controller
{
    // Mengambil semua data kategori
    public function index()
    {
        try {
            // Eager load relasi 'account' agar kode, nama COA bisa ditampilkan di tabel Next.js
            // Semua pengguna (termasuk admin cabang) berhak membaca data ini untuk keperluan input form
            $categories = ExpenseCategory::with('account')->orderBy('id', 'desc')->get();
            return response()->json(['success' => true, 'data' => $categories]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // Menyimpan kategori baru
    public function store(Request $request)
    {
        // PENAMBAHAN: Proteksi Hak Akses Pusat (Enterprise Accounting Security)
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menambah Master Kategori Biaya (COA).'
            ], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'account_id' => 'nullable|exists:accounts,id',
            'is_active' => 'nullable|boolean',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,svg|max:2048',
        ]);

        try {
            $category = new ExpenseCategory();
            $category->name = $request->name;
            $category->account_id = $request->account_id;
            $category->is_active = $request->has('is_active') ? $request->is_active : 1;

            // Logika Upload Icon jika ada
            if ($request->hasFile('image')) {
                $path = $request->file('image')->store('icons/expenses', 'public');
                $category->image_path = $path;
            }

            $category->save();

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

    // Memperbarui kategori
    public function update(Request $request, $id)
    {
        // PENAMBAHAN: Proteksi Hak Akses Pusat
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengubah Master Kategori Biaya (COA).'
            ], 403);
        }

        $request->validate([
            'name' => 'required|string|max:255',
            'account_id' => 'nullable|exists:accounts,id',
            'is_active' => 'nullable|boolean',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,svg|max:2048',
        ]);

        try {
            $category = ExpenseCategory::findOrFail($id);
            $category->name = $request->name;
            $category->account_id = $request->account_id;
            
            if ($request->has('is_active')) {
                $category->is_active = $request->is_active;
            }

            // Jika ada upload gambar baru, hapus gambar lama dari storage agar server tidak penuh
            if ($request->hasFile('image')) {
                if ($category->image_path) {
                    Storage::disk('public')->delete($category->image_path);
                }
                $path = $request->file('image')->store('icons/expenses', 'public');
                $category->image_path = $path;
            }

            $category->save();

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

    // Menghapus kategori
    public function destroy(Request $request, $id)
    {
        // PENAMBAHAN: Proteksi Hak Akses Pusat
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak menghapus Master Kategori Biaya (COA).'
            ], 403);
        }

        try {
            $category = ExpenseCategory::findOrFail($id);
            
            // Cek jika kategori masih dipakai di tabel expenses
            if ($category->expenses()->count() > 0) {
                return response()->json(['success' => false, 'message' => 'Kategori tidak bisa dihapus karena sedang digunakan oleh data pengeluaran.'], 400);
            }

            // Hapus file gambar dari server jika ada
            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) {
            // PENAMBAHAN ENTERPRISE: Menangkap error constraint violation dari level database
            if ($e->getCode() == "23000") {
                return response()->json([
                    'success' => false, 
                    'message' => 'Gagal dihapus: Kategori Biaya ini masih memiliki keterikatan relasi aktif di dalam database sistem. Silakan nonaktifkan statusnya saja.'
                ], 400);
            }
            return response()->json(['success' => false, 'message' => 'Database Error.'], 500);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}