<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ChartOfAccount; 
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; 

class AccountingCoaApiController extends Controller
{
    public function index(Request $request)
    {
        try {
            $user = $request->user();
            $query = ChartOfAccount::orderBy('code', 'asc');

            // PERBAIKAN ISOLASI CABANG:
            // Jika bukan owner, sembunyikan akun bank/kas yang secara spesifik dipetakan untuk cabang lain
            if ($user && $user->role !== 'owner') {
                $otherBranchesAccountIds = DB::table('branch_accounts')
                    ->where('branch_id', '!=', $user->branch_id)
                    ->pluck('account_id')
                    ->toArray();

                if (!empty($otherBranchesAccountIds)) {
                    $query->whereNotIn('id', $otherBranchesAccountIds);
                }
            }

            $coas = $query->get();
            return response()->json(['success' => true, 'data' => $coas]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function store(Request $request)
    {
        $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 menambah Master COA.'], 403);
        }

        $request->validate([
            'code' => 'required|string|unique:accounts,code|max:20',
            'name' => 'required|string|max:255',
            'category' => 'nullable|string|max:50',
            'group' => 'required|in:asset,liability,equity,revenue,expense',
            'is_active' => 'required|boolean'
        ]);

        try {
            $coa = ChartOfAccount::create($request->all());
            return response()->json(['success' => true, 'message' => 'Akun berhasil ditambahkan', 'data' => $coa]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    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 COA.'], 403);
        }

        $coa = ChartOfAccount::findOrFail($id);
        
        $request->validate([
            'code' => 'required|string|max:20|unique:accounts,code,' . $id,
            'name' => 'required|string|max:255',
            'category' => 'nullable|string|max:50',
            'group' => 'required|in:asset,liability,equity,revenue,expense',
            'is_active' => 'required|boolean'
        ]);

        try {
            $coa->update($request->all());
            return response()->json(['success' => true, 'message' => 'Akun berhasil diperbarui']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    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 COA.'], 403);
        }

        try {
            $coa = ChartOfAccount::findOrFail($id);
            
            // 1. Pengecekan relasi transaksi (journal_items)
            $isUsedInJournal = DB::table('journal_items')->where('account_id', $id)->exists();
            if ($isUsedInJournal) {
                return response()->json(['success' => false, 'message' => 'Akun tidak dapat dihapus karena sudah memiliki riwayat jurnal transaksi.'], 400);
            }

            // 2. Pengecekan pemetaan cabang (branch_accounts)
            $isMappedToBranch = DB::table('branch_accounts')->where('account_id', $id)->exists();
            if ($isMappedToBranch) {
                return response()->json(['success' => false, 'message' => 'Akun tidak dapat dihapus karena sedang dipetakan sebagai kas/bank cabang.'], 400);
            }

            // 3. PERBAIKAN: Pengecekan pemetaan global (accounting_settings)
            $isMappedToSettings = DB::table('accounting_settings')->where('account_id', $id)->exists();
            if ($isMappedToSettings) {
                return response()->json(['success' => false, 'message' => 'Akun tidak dapat dihapus karena sedang digunakan dalam Konfigurasi Akuntansi Global Pusat.'], 400);
            }

            // 4. PERBAIKAN: Pengecekan pemetaan kategori biaya (expense_categories)
            $isMappedToExpense = DB::table('expense_categories')->where('account_id', $id)->exists();
            if ($isMappedToExpense) {
                return response()->json(['success' => false, 'message' => 'Akun tidak dapat dihapus karena sedang dipetakan sebagai default akun pada Master Kategori Biaya.'], 400);
            }
            
            $coa->delete();
            return response()->json(['success' => true, 'message' => 'Akun berhasil dihapus']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}