<?php

namespace App\Http\Controllers\Api;

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

class LedgerController extends Controller
{
    /**
     * Mengambil daftar akun kas dan bank untuk dropdown filter.
     */
    public function getCashAccounts(Request $request) 
    {
        $user = $request->user();

        $query = DB::table('accounts')
            ->where('group', 'asset')
            // =========================================================================
            // PERBAIKAN: Filter Standar Akuntansi (Awalan Kode), bukan teks kategori
            // =========================================================================
            ->where(function($q) {
                $q->where('code', 'like', '10%')      // Tarik semua golongan Kas & Bank
                  ->orWhere('code', 'like', '11%');   // Tarik juga Rekening Koran (R/K)
            })
            ->where('is_active', 1)
            ->select('id', 'code', 'name')
            ->orderBy('code', 'asc');

        // =========================================================================
        // PERBAIKAN ENTERPRISE: Bypass Privilege untuk Owner/Pusat
        // Hanya Admin Cabang yang dibatasi oleh branch_accounts
        // =========================================================================
        if ($user && !in_array($user->role, ['owner', 'super_admin'])) {
            $mappedAccountIds = DB::table('branch_accounts')
                ->where('branch_id', $user->branch_id)
                ->where('is_active', 1) // Pastikan mapping tidak dibekukan
                ->pluck('account_id')
                ->toArray();

            // Jika admin cabang belum diberi mapping rekening oleh pusat, kosongkan dropdown
            if (empty($mappedAccountIds)) {
                return response()->json([
                    'success' => true, 
                    'data' => []
                ]);
            }

            $query->whereIn('id', $mappedAccountIds);
        }
        // =========================================================================

        $accounts = $query->get();
        
        return response()->json([
            'success' => true, 
            'data' => $accounts
        ]);
    }

    /**
     * Menghitung saldo awal otomatis dan menjabarkan rincian mutasi.
     */
    public function getCashMutations(Request $request)
    {
        $user = $request->user();
        $accountId = $request->account_id;
        $startDate = $request->start_date ?? date('Y-m-01');
        $endDate = $request->end_date ?? date('Y-m-d');

        if (!$accountId) {
            return response()->json(['success' => false, 'message' => 'Silakan pilih Akun Kas/Bank'], 400);
        }

        // =========================================================================
        // PERBAIKAN ENTERPRISE: Bypass Privilege untuk Owner/Pusat
        // Owner bebas melihat mutasi di rekening manapun
        // =========================================================================
        if ($user && !in_array($user->role, ['owner', 'super_admin'])) {
            $isMapped = DB::table('branch_accounts')
                ->where('branch_id', $user->branch_id)
                ->where('account_id', $accountId)
                ->where('is_active', 1)
                ->exists();

            if (!$isMapped) {
                return response()->json([
                    'success' => false, 
                    'message' => 'Akses ditolak: Rekening Kas/Bank ini tidak dipetakan untuk wewenang cabang Anda.'
                ], 403);
            }
        }
        // =========================================================================

        // 1. HITUNG SALDO AWAL OTOMATIS
        $saldoAwal = DB::table('journal_items')
            ->join('journal_entries', 'journal_items.journal_entry_id', '=', 'journal_entries.id')
            ->where('journal_items.account_id', $accountId)
            ->where('journal_entries.entry_date', '<', $startDate)
            ->selectRaw('COALESCE(SUM(debit) - SUM(credit), 0) as balance')
            ->value('balance') ?? 0;

        // 2. TARIK RINCIAN TRANSAKSI (Sesuai rentang tanggal)
        $mutations = DB::table('journal_items')
            ->join('journal_entries', 'journal_items.journal_entry_id', '=', 'journal_entries.id')
            ->where('journal_items.account_id', $accountId)
            ->whereBetween('journal_entries.entry_date', [$startDate, $endDate])
            ->select(
                'journal_entries.entry_date',
                'journal_entries.reference',
                'journal_entries.description',
                'journal_items.debit',
                'journal_items.credit'
            )
            ->orderBy('journal_entries.entry_date', 'asc')
            ->orderBy('journal_entries.id', 'asc')
            ->get();

        // 3. KALKULASI TOTAL AKHIR
        $totalMasuk = $mutations->sum('debit');
        $totalKeluar = $mutations->sum('credit');
        $saldoAkhir = $saldoAwal + $totalMasuk - $totalKeluar;

        return response()->json([
            'success' => true,
            'data' => [
                'saldo_awal' => (float) $saldoAwal,
                'mutations' => $mutations,
                'total_masuk' => (float) $totalMasuk,
                'total_keluar' => (float) $totalKeluar,
                'saldo_akhir' => (float) $saldoAkhir
            ]
        ]);
    }
}