<?php

namespace App\Http\Controllers\Api;

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

class InterbranchTransferController extends Controller
{
    /**
     * Membaca akun dinamis berdasarkan cabang dan tipe
     */
    private function getDynamicAccount($branchId, $type)
    {
        // PERBAIKAN ENTERPRISE: Pastikan mapping rekening berstatus Aktif (Strict Mapping)
        $accountId = DB::table('branch_accounts')
            ->where('branch_id', $branchId)
            ->where('type', $type)
            ->where('is_active', 1)
            ->value('account_id');

        if (!$accountId) {
            throw new \Exception("Mapping akun untuk tipe '{$type}' pada cabang ID {$branchId} belum diatur di sistem atau sedang dinonaktifkan.");
        }

        return $accountId;
    }

    /**
     * Cabang Mengajukan Transfer ke Pusat
     */
    public function store(Request $request)
    {
        $request->validate([
            'transfer_date' => 'required|date',
            'amount' => 'required|numeric|min:1',
            'note' => 'nullable|string',
        ]);

        DB::beginTransaction();
        try {
            $user = $request->user();
            $branchId = $user->branch_id ?? 1;

            // Dapatkan ID Akun secara Dinamis (No Hardcode)
            $bankOperasionalId = $this->getDynamicAccount($branchId, 'bank_operasional');
            $rkPusatId = $this->getDynamicAccount($branchId, 'rk_pusat');

            // 1. Catat ke tabel interbranch_transfers (Tabel penampung antrean transfer)
            $transferId = DB::table('interbranch_transfers')->insertGetId([
                'transfer_number' => 'TRF-HO-' . time(),
                'from_branch_id' => $branchId,
                'to_branch_id' => 0, // 0 asumsikan Pusat/Head Office
                'amount' => $request->amount,
                'status' => 'pending',
                'requested_by' => $user->id,
                'note' => $request->note,
                'transfer_date' => $request->transfer_date,
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ]);

            // 2. JURNAL SISI CABANG (Langsung terbentuk: Aset Bank Cabang berkurang, Piutang/RK Pusat bertambah)
            AccountingService::log([
                'branch_id'   => $branchId,
                'entry_date'  => $request->transfer_date,
                'description' => "Setoran Dana ke Pusat (Menunggu Konfirmasi): " . $request->note,
                'reference'   => "TRF-HO-" . $transferId,
                'source_type' => 'INTERBRANCH_TRANSFER_OUT',
                'user_id'     => $user->id,
                'items' => [
                    ['account_id' => $rkPusatId, 'debit' => $request->amount, 'credit' => 0],
                    ['account_id' => $bankOperasionalId, 'debit' => 0, 'credit' => $request->amount]
                ]
            ]);

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Pengajuan transfer berhasil, menunggu konfirmasi Pusat.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Pusat Mengkonfirmasi Penerimaan Dana dari Cabang
     */
    public function confirm(Request $request, $id)
    {
        // PERBAIKAN ENTERPRISE: Proteksi Hak Akses Konfirmasi Finansial (Segregation of Duties)
        $user = $request->user();
        if ($user && !in_array($user->role, ['owner', 'admin_finance'])) {
            return response()->json([
                'success' => false, 
                'message' => 'Akses ditolak: Hanya Pusat (Owner/Admin Finance) yang memiliki wewenang untuk mengkonfirmasi penerimaan dana.'
            ], 403);
        }

        DB::beginTransaction();
        try {
            $transfer = DB::table('interbranch_transfers')->where('id', $id)->first();
            if (!$transfer) throw new \Exception("Data transfer tidak ditemukan.");
            if ($transfer->status !== 'pending') throw new \Exception("Transfer ini sudah diproses sebelumnya.");

            // Dapatkan ID Akun secara Dinamis (Sisi Pusat)
            // Asumsi Pusat memiliki tabel branch_accounts dengan branch_id = 0, atau Anda mendefinisikannya di tabel accounting_settings
            $bankUtamaId = DB::table('accounting_settings')->where('setting_key', 'bank_bca_account')->value('account_id') 
                           ?? $this->getDynamicAccount(1, 'bank_utama'); // Fallback logic
            
            $rkCabangId = $this->getDynamicAccount($transfer->from_branch_id, 'rk_cabang');

            // 1. Update Status Transfer
            DB::table('interbranch_transfers')->where('id', $id)->update([
                'status' => 'completed',
                'confirmed_by' => $user->id,
                'updated_at' => Carbon::now(),
            ]);

            // 2. JURNAL SISI PUSAT (Baru terbentuk setelah dikonfirmasi: Aset Bank Pusat bertambah, RK Cabang terkait berkurang)
            AccountingService::log([
                'branch_id'   => 0, // Buku Besar Pusat
                'entry_date'  => Carbon::now()->toDateString(), // Tanggal aktual dana diterima
                'description' => "Terima Setoran Dana dari Cabang ID {$transfer->from_branch_id}: " . $transfer->note,
                'reference'   => $transfer->transfer_number,
                'source_type' => 'INTERBRANCH_TRANSFER_IN',
                'user_id'     => $user->id,
                'items' => [
                    ['account_id' => $bankUtamaId, 'debit' => $transfer->amount, 'credit' => 0],
                    ['account_id' => $rkCabangId, 'debit' => 0, 'credit' => $transfer->amount]
                ]
            ]);

            DB::commit();
            return response()->json(['success' => true, 'message' => 'Dana berhasil dikonfirmasi dan dijurnal ke Buku Besar Pusat.']);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function index(Request $request)
    {
        try {
            $user = $request->user();
            
            // Menggunakan query builder dengan join agar nama cabang dan user ikut terbawa
            $query = DB::table('interbranch_transfers as it')
                ->join('branches as b', 'it.from_branch_id', '=', 'b.id')
                ->join('users as u', 'it.requested_by', '=', 'u.id')
                ->leftJoin('users as c', 'it.confirmed_by', '=', 'c.id')
                ->select(
                    'it.*', 
                    'b.name as branch_name', 
                    'b.code as branch_code',
                    'u.name as requested_by_name',
                    'c.name as confirmed_by_name'
                )
                ->orderBy('it.created_at', 'desc');

            // Jika bukan Pusat/Owner, hanya bisa melihat transaksi cabang miliknya sendiri
            if ($user->role !== 'owner' && $user->role !== 'admin_finance') {
                $query->where('it.from_branch_id', $user->branch_id);
            }

            if ($request->filled('status') && $request->status !== 'all') {
                $query->where('it.status', $request->status);
            }

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