<?php

namespace App\Http\Controllers\Api;

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

class AccountingMappingApiController extends Controller
{
    // --- 1. Ambil Semua Master COA yang Aktif ---
    public function getActiveCoas(Request $request)
    {
        try {
            // PERBAIKAN: Tambahan Proteksi Keamanan.
            // Halaman mapping ini krusial, pastikan hanya pusat yang bisa menarik daftar master utuh dari sini.
            $user = $request->user();
            if ($user && $user->role !== 'owner') {
                return response()->json(['success' => false, 'message' => 'Akses ditolak.'], 403);
            }

            // Tembak langsung ke tabel 'accounts' TANPA filter is_active
            // untuk memastikan data benar-benar bisa ditarik
            $coas = DB::table('accounts')
                        ->orderBy('code', 'asc')
                        ->get();
                        
            return response()->json(['success' => true, 'data' => $coas]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // --- 2. Ambil Mapping yang Sedang Tersimpan (Global/Pusat) ---
    public function getMappings(Request $request)
    {
        try {
            $user = $request->user();
            if ($user && $user->role !== 'owner') {
                return response()->json(['success' => false, 'message' => 'Akses ditolak.'], 403);
            }

            // Tembak langsung ke tabel 'accounting_settings'
            $mappings = DB::table('accounting_settings')->get()->toArray();
            
            // =========================================================================
            // INJEKSI PINTAR UNTUK MODUL PABRIKASI
            // Memastikan key 'btkl_dibebankan' dan 'bop_dibebankan' selalu terdeteksi
            // oleh frontend (Next.js) meskipun belum ada di database.
            // =========================================================================
            $existingKeys = array_column($mappings, 'setting_key');
            $fabricationKeys = ['btkl_dibebankan', 'bop_dibebankan'];
            
            foreach ($fabricationKeys as $key) {
                if (!in_array($key, $existingKeys)) {
                    $mappings[] = (object) [
                        'setting_key' => $key,
                        'account_id' => null, // Dibiarkan null agar admin memilih dari dropdown
                    ];
                }
            }
            // =========================================================================
            
            return response()->json(['success' => true, 'data' => $mappings]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // --- 3. Simpan/Update Mapping Massal dari Next.js (Global/Pusat) ---
    public function updateMappings(Request $request)
    {
        // PENAMBAHAN: Proteksi Hak Akses Pusat (Enterprise Security)
        // Mencegah admin cabang merusak routing jurnal akuntansi nasional
        $user = $request->user();
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Owner/Pusat yang berhak mengubah Konfigurasi Mapping Akun (GL).'
            ], 403);
        }

        // Tangkap langsung tanpa validasi ketat agar tidak ditolak otomatis oleh Laravel
        $mappings = $request->input('mappings');

        if (!$mappings || !is_array($mappings)) {
            return response()->json(['success' => false, 'message' => 'Format data tidak valid.'], 400);
        }

        DB::beginTransaction();
        try {
            foreach ($mappings as $map) {
                $settingKey = $map['setting_key'] ?? null;
                $accountId = !empty($map['account_id']) ? (int) $map['account_id'] : null;

                if (!$settingKey) continue;

                $exists = DB::table('accounting_settings')
                            ->where('setting_key', $settingKey)
                            ->first();

                if ($exists) {
                    // Update
                    DB::table('accounting_settings')
                        ->where('setting_key', $settingKey)
                        ->update([
                            'account_id' => $accountId,
                            'updated_at' => now()->toDateTimeString(), // Pastikan dikonversi ke String
                        ]);
                } else {
                    // Insert
                    DB::table('accounting_settings')->insert([
                        'setting_key' => $settingKey,
                        'account_id' => $accountId,
                        'created_at' => now()->toDateTimeString(),
                        'updated_at' => now()->toDateTimeString(),
                    ]);
                }
            }
            
            DB::commit();
            return response()->json([
                'success' => true, 
                'message' => 'Konfigurasi Mapping Akun (GL) berhasil disimpan!'
            ]);
            
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false, 
                'message' => 'Error SQL: ' . $e->getMessage() // Menampilkan error asli database
            ], 500);
        }
    }

    // --- 4. PERBAIKAN: Ambil Mapping Rekening Spesifik Per Cabang (Branch Mapping) ---
    public function getBranchMappings(Request $request, $branchId)
    {
        try {
            $user = $request->user();
            
            // Isolasi Cabang: Pastikan cabang hanya bisa melihat mapping cabangnya sendiri
            if ($user && $user->role !== 'owner' && $user->branch_id != $branchId) {
                return response()->json([
                    'success' => false, 
                    'message' => 'Akses ditolak: Anda tidak dapat melihat mapping rekening milik cabang lain.'
                ], 403);
            }

            $mappings = DB::table('branch_accounts')
                ->where('branch_id', $branchId)
                ->get();
                
            return response()->json(['success' => true, 'data' => $mappings]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    // --- 5. PERBAIKAN: Simpan/Update Mapping Rekening Spesifik Per Cabang ---
    public function updateBranchMappings(Request $request, $branchId)
    {
        $user = $request->user();
        
        // Proteksi Ketat: HANYA Owner yang boleh mengatur rute pergerakan uang/rekening di masing-masing cabang
        if ($user && $user->role !== 'owner') {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Pusat/Owner yang berhak mengatur pemetaan rekening bank cabang.'
            ], 403);
        }

        $mappings = $request->input('mappings'); // Format expected: [['type' => 'kas_kecil', 'account_id' => 1], ...]

        if (!$mappings || !is_array($mappings)) {
            return response()->json(['success' => false, 'message' => 'Format data tidak valid.'], 400);
        }

        DB::beginTransaction();
        try {
            foreach ($mappings as $map) {
                $type = $map['type'] ?? null;
                $accountId = !empty($map['account_id']) ? (int) $map['account_id'] : null;

                if (!$type) continue;

                // Validasi input enum dengan tabel branch_accounts
                if (!in_array($type, ['kas_kecil', 'kas_besar', 'bank_utama', 'bank_operasional', 'rk_pusat', 'rk_cabang'])) {
                    continue; 
                }

                $exists = DB::table('branch_accounts')
                            ->where('branch_id', $branchId)
                            ->where('type', $type)
                            ->first();

                if ($exists) {
                    DB::table('branch_accounts')
                        ->where('id', $exists->id)
                        ->update([
                            'account_id' => $accountId,
                            'updated_at' => now()->toDateTimeString(),
                        ]);
                } else {
                    DB::table('branch_accounts')->insert([
                        'branch_id'  => $branchId,
                        'type'       => $type,
                        'account_id' => $accountId,
                        'is_active'  => 1,
                        'created_at' => now()->toDateTimeString(),
                        'updated_at' => now()->toDateTimeString(),
                    ]);
                }
            }
            
            DB::commit();
            return response()->json([
                'success' => true, 
                'message' => 'Konfigurasi Rekening Cabang berhasil disimpan!'
            ]);
            
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => 'Error SQL: ' . $e->getMessage()], 500);
        }
    }
}