<?php

namespace App\Http\Controllers\Api;

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

class BranchAccountController extends Controller
{
    /**
     * Mengambil daftar mapping akun yang sudah ada
     */
    public function index(Request $request)
    {
        try {
            $user = $request->user();
            $query = DB::table('branch_accounts');

            // PENAMBAHAN: Isolasi Data Cabang
            // Memastikan admin hanya bisa melihat konfigurasi akun untuk cabangnya sendiri
            if ($user && $user->role !== 'owner') {
                $query->where('branch_id', $user->branch_id);
            }

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

    /**
     * Menyimpan atau memperbarui mapping akun dari Frontend
     */
    public function sync(Request $request)
    {
        $user = $request->user();

        // Proteksi Hak Akses Pusat (Enterprise Financial Security)
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false,
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengatur Pemetaan Akun Finansial Cabang.'
            ], 403);
        }

        $request->validate([
            'mappings' => 'required|array',
            'mappings.*.branch_id' => 'required|integer|exists:branches,id',
            'mappings.*.type' => 'required|string|in:kas_kecil,kas_besar,bank_utama,bank_operasional,rk_pusat,rk_cabang',
            'mappings.*.account_id' => 'required|integer|exists:accounts,id',
        ]);

        DB::beginTransaction();
        try {
            // =========================================================================
            // PERBAIKAN VALIDASI ENTERPRISE: Pemisahan Proteksi Kas vs Rekening Koran
            // =========================================================================
            $cashAccountIds = [];
            $rkAccountIds = [];

            foreach ($request->mappings as $map) {
                if (empty($map['account_id'])) continue;

                if (in_array($map['type'], ['kas_kecil', 'kas_besar', 'bank_utama', 'bank_operasional'])) {
                    $cashAccountIds[] = $map['account_id'];
                } elseif (in_array($map['type'], ['rk_pusat', 'rk_cabang'])) {
                    $rkAccountIds[] = $map['account_id'];
                }
            }

            // 1. Validasi Ketat Khusus Akun Kas & Bank (Wajib Grup Asset & Kepala Kode 10)
            if (!empty($cashAccountIds)) {
                $invalidCash = DB::table('accounts')
                    ->whereIn('id', $cashAccountIds)
                    ->where(function($q) {
                        $q->where('group', '!=', 'asset')
                          ->orWhere('code', 'not like', '10%');
                    })
                    ->first();

                if ($invalidCash) {
                    throw new \Exception("Validasi Akuntansi Gagal: Akun '{$invalidCash->name}' ({$invalidCash->code}) tidak dapat dipetakan sebagai Kas/Bank cabang. Akun harus berada dalam kategori Aset dengan awalan kode 10.");
                }
            }

            // 2. Validasi Khusus Akun Rekening Koran (Wajib Grup Asset, Kepala Kode Bebas/Sesuai COA ERP)
            if (!empty($rkAccountIds)) {
                $invalidRk = DB::table('accounts')
                    ->whereIn('id', $rkAccountIds)
                    ->where('group', '!=', 'asset')
                    ->first();

                if ($invalidRk) {
                    throw new \Exception("Validasi Akuntansi Gagal: Akun '{$invalidRk->name}' ({$invalidRk->code}) tidak dapat dipetakan sebagai R/K Antar Kantor. Akun kliring ini wajib berada dalam klasifikasi kelompok HARTA (ASSET).");
                }
            }
            // =========================================================================

            // Loop Proses Penyimpanan Data Mapping ke Database
            foreach ($request->mappings as $map) {
                if (empty($map['account_id'])) continue;

                DB::table('branch_accounts')->updateOrInsert(
                    [
                        'branch_id' => $map['branch_id'], 
                        'type' => $map['type']
                    ],
                    [
                        'account_id' => $map['account_id'], 
                        'is_active' => 1,
                        'updated_at' => Carbon::now()
                    ]
                );
            }
            
            DB::commit();
            return response()->json(['success' => true, 'message' => 'Konfigurasi akun cabang berhasil disimpan!']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}