"""
Views for consolidated financial reports:
  /reports/financial/sasapay-reconciliation/
  /reports/financial/profit-loss/
  /reports/financial/statements/
  /reports/financial/loan-aging/
  /reports/financial/loan-aging/export/   (CSV)
"""

from datetime import date, datetime, timedelta
from decimal import Decimal

from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.contrib import messages
from django.utils import timezone

from users.decorators import staff_required
from users.models import Branch
from loans.models import LoanProduct


@login_required
@staff_required
def financial_reports_index(request):
    """Landing page listing all consolidated financial reports."""
    return render(request, 'reports/financial/index.html', {
        'report_title': 'Consolidated Financial Reports'
    })

from .financial_reports_service import (
    get_sasapay_reconciliation,
    get_profit_and_loss,
    get_financial_statements,
    get_loan_aging,
)
from accounting.exceptions import FinancialStatementImbalanceError


# ── helpers ────────────────────────────────────────────────────────────────

def _parse_date(value):
    """Parse a YYYY-MM-DD string, return None on failure."""
    if not value:
        return None
    try:
        return datetime.strptime(value, '%Y-%m-%d').date()
    except ValueError:
        return None


def _default_period():
    """Return first day of current month and today."""
    today = date.today()
    return today.replace(day=1), today


# ── 1. SasaPay Reconciliation ──────────────────────────────────────────────

@login_required
@staff_required
def sasapay_reconciliation(request):
    today = date.today()
    default_start = today.replace(day=1)

    start_date = _parse_date(request.GET.get('start_date')) or default_start
    end_date = _parse_date(request.GET.get('end_date')) or today

    data = get_sasapay_reconciliation(start_date, end_date)

    # Paginate IPN detail
    from django.core.paginator import Paginator
    ipn_page = Paginator(data['ipn_detail_qs'], 25).get_page(request.GET.get('ipn_page', 1))
    disb_page = Paginator(data['disbursement_detail_qs'], 25).get_page(request.GET.get('disb_page', 1))
    unk_page = Paginator(data['unknown_detail_qs'], 25).get_page(request.GET.get('unk_page', 1))

    context = {
        **data,
        'ipn_page': ipn_page,
        'disb_page': disb_page,
        'unk_page': unk_page,
        'start_date': start_date,
        'end_date': end_date,
        'report_title': 'SasaPay Reconciliation Report',
    }
    return render(request, 'reports/financial/sasapay_reconciliation.html', context)


# ── 2. Profit & Loss ───────────────────────────────────────────────────────

@login_required
@staff_required
def profit_and_loss(request):
    """
    Full Income Statement matching Document 1 format:
    Description | Notes | Period KES | Prior Period KES | Variance KES | Variance %
    Powered by the GL accounting system with fallback to direct calculations.
    """
    from datetime import timedelta

    today         = date.today()
    # Default to Jan 1 of earliest GL year so P&L shows full-year data
    try:
        from accounting.models import GeneralLedger as _GL_def
        _earliest = _GL_def.objects.order_by('transaction_date').values_list('transaction_date', flat=True).first()
        default_start = date(_earliest.year, 1, 1) if _earliest else date(today.year, 1, 1)
    except Exception:
        default_start = date(today.year, 1, 1)

    start_date = _parse_date(request.GET.get('start_date')) or default_start
    end_date   = _parse_date(request.GET.get('end_date'))   or today
    branch_id  = request.GET.get('branch') or None

    branches = Branch.objects.filter(is_active=True).order_by('name')

    # Prior period: same date range one year ago
    prior_start = start_date.replace(year=start_date.year - 1)
    prior_end   = end_date.replace(year=end_date.year - 1)

    # ── Try GL-based calculation first ──────────────────────────────
    NOTE_MAP = {
        '4010': '1', '4020': '2', '4021': '2', '4022': '2', '4030': '3',
        '5010': '4', '5020': '5', '5021': '5', '5022': '5',
        '5030': '6', '5031': '6', '5032': '6', '5033': '6',
        '5040': '7', '5041': '7', '5042': '7', '5043': '7',
        '5044': '7', '5045': '7', '5046': '7', '5047': '7', '5048': '7',
        '5050': '8', '5051': '8', '5052': '8',
        '5060': '9', '5061': '9', '5062': '9',
        '5070': '10', '5071': '10',
    }

    income_items = []
    expense_items = []
    prior_income_items = []
    prior_expense_items = []
    tax_amount = Decimal('0.00')
    prior_tax_amount = Decimal('0.00')
    source = 'direct_calculation'

    try:
        from accounting.models import Account
        from accounting.services.accounting_service import AccountingService
        if Account.objects.exists():
            accounting_service = AccountingService()

            def _activity(account, s, e):
                bal     = accounting_service.calculate_account_balance(account, e, None)
                opening = accounting_service.calculate_account_balance(
                    account, s - timedelta(days=1), None) if s > date(2000,1,1) else Decimal('0.00')
                return bal - opening

            for account in Account.objects.filter(account_type='income', is_active=True).order_by('code'):
                amt   = _activity(account, start_date, end_date)
                p_amt = _activity(account, prior_start, prior_end)
                if amt or p_amt:
                    income_items.append({'code': account.code, 'name': account.name,
                                         'note': NOTE_MAP.get(account.code, ''), 'amount': amt})
                    prior_income_items.append({'code': account.code, 'name': account.name,
                                               'note': NOTE_MAP.get(account.code, ''), 'amount': p_amt})

            for account in Account.objects.filter(
                    account_type='expense', is_active=True).exclude(
                    code__in=['5070','5071']).order_by('code'):
                amt   = _activity(account, start_date, end_date)
                p_amt = _activity(account, prior_start, prior_end)
                if amt or p_amt:
                    expense_items.append({'code': account.code, 'name': account.name,
                                          'note': NOTE_MAP.get(account.code, ''), 'amount': amt})
                    prior_expense_items.append({'code': account.code, 'name': account.name,
                                                'note': NOTE_MAP.get(account.code, ''), 'amount': p_amt})

            for account in Account.objects.filter(
                    account_type='expense', is_active=True, code__in=['5070','5071']).order_by('code'):
                tax_amount       += _activity(account, start_date, end_date)
                prior_tax_amount += _activity(account, prior_start, prior_end)

            source = 'accounting_system'
    except Exception:
        pass

    total_income    = sum(Decimal(str(i.get('amount',0) or 0)) for i in income_items)
    total_expenses  = sum(Decimal(str(i.get('amount',0) or 0)) for i in expense_items)
    p_total_income  = sum(Decimal(str(i.get('amount',0) or 0)) for i in prior_income_items)
    p_total_expenses= sum(Decimal(str(i.get('amount',0) or 0)) for i in prior_expense_items)

    op_profit   = total_income   - total_expenses
    p_op_profit = p_total_income - p_total_expenses

    # Tax is outflow – show negative
    tax_display   = -abs(tax_amount)
    p_tax_display = -abs(prior_tax_amount)

    net_profit   = op_profit   + tax_display
    p_net_profit = p_op_profit + p_tax_display

    var_income  = total_income  - p_total_income
    var_expense = total_expenses - p_total_expenses
    var_profit  = net_profit    - p_net_profit

    def _pct(a, b):
        try:
            a, b = Decimal(str(a)), Decimal(str(b))
            if b == 0: return None
            return round(float((a - b) / abs(b) * 100), 1)
        except Exception:
            return None

    profit_margin = round(float(net_profit / total_income * 100), 1) if total_income else 0
    expense_ratio = round(float(total_expenses / total_income * 100), 1) if total_income else 0

    context = {
        'income_items':          income_items,
        'expense_items':         expense_items,
        'prior_income_items':    prior_income_items,
        'prior_expense_items':   prior_expense_items,
        'total_income':          total_income,
        'total_expenses':        total_expenses,
        'p_total_income':        p_total_income,
        'p_total_expenses':      p_total_expenses,
        'op_profit':             op_profit,
        'p_op_profit':           p_op_profit,
        'tax_amount':            tax_display,
        'p_tax_amount':          p_tax_display,
        'net_profit':            net_profit,
        'p_net_profit':          p_net_profit,
        'var_income':            var_income,
        'var_expense':           var_expense,
        'var_profit':            var_profit,
        'var_income_pct':        _pct(total_income,  p_total_income),
        'var_expense_pct':       _pct(total_expenses, p_total_expenses),
        'var_profit_pct':        _pct(net_profit,    p_net_profit),
        'profit_margin':         profit_margin,
        'expense_ratio':         expense_ratio,
        'net_income_status':     'profit' if net_profit >= 0 else 'loss',
        'start_date':            start_date,
        'end_date':              end_date,
        'prior_start':           prior_start,
        'prior_end':             prior_end,
        'branches':              branches,
        'selected_branch':       branch_id,
        'source':                source,
        'generated_at':          timezone.now().isoformat(),
        'report_title':          'Income Statement',
    }
    return render(request, 'reports/financial/profit_and_loss.html', context)


# ── 3. Financial Statements ────────────────────────────────────────────────

@login_required
@staff_required
def financial_statements(request):
    """
    Full Statement of Financial Position matching Document 2 format:
    Side-by-side Assets | Liabilities & Equity with Non-Current / Current split.
    Powered by the GL accounting system with fallback to direct calculations.
    """
    as_of_date = _parse_date(request.GET.get('as_of')) or date.today()
    branch_id  = request.GET.get('branch') or None
    branches   = Branch.objects.filter(is_active=True).order_by('name')

    NOTE_MAP = {
        '1010':'10','1011':'10','1012':'10','1013':'10',
        '1020':'11','1021':'11','1030':'12','1031':'12',
        '1040':'13','1050':'14','1060':'15','1070':'16',
        '1510':'5', '1511':'5', '1520':'6', '1521':'6',
        '1530':'7', '1540':'8', '1550':'9',
        '2010':'17','2020':'21','2030':'22','2040':'23',
        '2050':'24','2060':'18','2070':'25','2080':'25',
        '2510':'17','2520':'18','2530':'19','2540':'20',
        # Equity accounts intentionally excluded from NOTE_MAP
        # (equity items do not display note references on the SFP)
    }
    NCA_SUBTYPES = {'fixed_asset', 'other_asset'}
    NCL_CODES    = {'2510', '2520', '2530', '2540'}

    asset_items = []
    liability_items = []
    equity_items = []
    source = 'direct_calculation'

    try:
        from accounting.models import Account
        from accounting.services.accounting_service import AccountingService
        if Account.objects.exists():
            accounting_service = AccountingService()

            for account in Account.objects.filter(account_type='asset', is_active=True).order_by('code'):
                try:
                    bal = accounting_service.calculate_account_balance(account, as_of_date, None)
                except Exception:
                    bal = Decimal('0.00')
                if bal:
                    asset_items.append({
                        'code': account.code, 'name': account.name,
                        'note': NOTE_MAP.get(account.code, ''),
                        'amount': bal,
                        'subtype': account.subtype or '',
                        'non_current': account.subtype in NCA_SUBTYPES,
                    })

            for account in Account.objects.filter(account_type='liability', is_active=True).order_by('code'):
                try:
                    bal = accounting_service.calculate_account_balance(account, as_of_date, None)
                except Exception:
                    bal = Decimal('0.00')
                if bal:
                    liability_items.append({
                        'code': account.code, 'name': account.name,
                        'note': NOTE_MAP.get(account.code, ''),
                        'amount': bal,
                        'subtype': account.subtype or '',
                        'non_current': account.code in NCL_CODES,
                    })

            for account in Account.objects.filter(account_type='equity', is_active=True).order_by('code'):
                try:
                    bal = accounting_service.calculate_account_balance(account, as_of_date, None)
                except Exception:
                    bal = Decimal('0.00')
                if bal:
                    equity_items.append({
                        'code': account.code, 'name': account.name,
                        'note': '',  # Equity items do not display note references on the SFP
                        'amount': bal,
                    })
            source = 'accounting_system'
    except FinancialStatementImbalanceError as e:
        messages.warning(request, f"SFP imbalance detected: {e.difference} KES")
        source = 'accounting_system'

    total_assets      = sum(Decimal(str(i['amount'] or 0)) for i in asset_items)
    total_liabilities = sum(Decimal(str(i['amount'] or 0)) for i in liability_items)
    total_equity      = sum(Decimal(str(i['amount'] or 0)) for i in equity_items)

    # Subtotals for current / non-current splits
    total_current_assets         = sum(Decimal(str(i['amount'] or 0)) for i in asset_items     if not i['non_current'])
    total_non_current_assets     = sum(Decimal(str(i['amount'] or 0)) for i in asset_items     if i['non_current'])
    total_current_liabilities    = sum(Decimal(str(i['amount'] or 0)) for i in liability_items if not i['non_current'])
    total_non_current_liabilities = sum(Decimal(str(i['amount'] or 0)) for i in liability_items if i['non_current'])

    # Add current-year net income to equity so SFP balances mid-year
    # (income/expense accounts not yet closed to retained earnings)
    try:
        from accounting.models import Account as _Acc
        from accounting.services.accounting_service import AccountingService as _AS
        _svc = _AS()
        _ytd_inc = sum(_svc.calculate_account_balance(a, as_of_date, None)
                       for a in _Acc.objects.filter(account_type='income', is_active=True))
        _ytd_exp = sum(_svc.calculate_account_balance(a, as_of_date, None)
                       for a in _Acc.objects.filter(account_type='expense', is_active=True))
        _net = _ytd_inc - _ytd_exp
        if _net != Decimal('0.00'):
            equity_items.append({
                'code': 'NET_INCOME',
                'name': 'Current Year Net Income' if _net >= 0 else 'Current Year Net Loss',
                'note': '',
                'amount': _net,
            })
            total_equity += _net
    except Exception:
        pass

    total_le          = total_liabilities + total_equity
    balanced          = abs(total_assets - total_le) < Decimal('0.01')
    difference        = abs(total_assets - total_le)

    equity_ratio  = round(float(total_equity / total_assets * 100), 1) if total_assets else 0
    debt_ratio    = round(float(total_liabilities / total_assets * 100), 1) if total_assets else 0
    debt_to_equity = round(float(total_liabilities / total_equity), 2) if total_equity else 0

    # ── Extra data for expanded SFP ──────────────────────────────────────
    try:
        from loans.models import Loan, Repayment
        from django.db.models import Sum, Count, Q as _Q

        # Loan portfolio breakdown
        active_loans     = Loan.objects.filter(is_deleted=False, status='active')
        paid_loans       = Loan.objects.filter(is_deleted=False, status='paid')
        defaulted_loans  = Loan.objects.filter(is_deleted=False, status__in=['defaulted','written_off'])
        all_loans        = Loan.objects.filter(is_deleted=False)

        loan_count_active    = active_loans.count()
        loan_count_paid      = paid_loans.count()
        loan_count_defaulted = defaulted_loans.count()
        loan_count_total     = all_loans.count()

        total_disbursed  = all_loans.aggregate(t=Sum('principal_amount'))['t'] or Decimal('0.00')
        total_repaid     = Repayment.objects.aggregate(t=Sum('amount'))['t'] or Decimal('0.00')
        outstanding_port = total_disbursed - total_repaid

        # Average loan size
        avg_loan = (total_disbursed / loan_count_total) if loan_count_total else Decimal('0.00')

        # Repayment rate
        repayment_rate = round(float(total_repaid / total_disbursed * 100), 1) if total_disbursed else 0.0

        # Capital adequacy: equity / total assets
        capital_adequacy = round(float(total_equity / total_assets * 100), 1) if total_assets else 0.0

        # Return on equity (net income / equity)
        roe = round(float(_net / total_equity * 100), 1) if total_equity and '_net' in dir() else 0.0

        # Loan to equity ratio
        loan_to_equity = round(float(outstanding_port / total_equity), 2) if total_equity else 0.0

        # YTD income/expense summary (already computed above)
        ytd_income   = _ytd_inc if '_ytd_inc' in dir() else Decimal('0.00')
        ytd_expenses = _ytd_exp if '_ytd_exp' in dir() else Decimal('0.00')
        ytd_net      = _net     if '_net'     in dir() else Decimal('0.00')

        # Income breakdown by account
        from accounting.models import Account as _AccInc
        from accounting.services.accounting_service import AccountingService as _ASInc
        _svc_inc = _ASInc()
        income_breakdown = []
        for _a in _AccInc.objects.filter(account_type='income', is_active=True).order_by('code'):
            _b = _svc_inc.calculate_account_balance(_a, as_of_date, None)
            if _b:
                income_breakdown.append({'code': _a.code, 'name': _a.name, 'amount': _b})

        expense_breakdown = []
        for _a in _AccInc.objects.filter(account_type='expense', is_active=True).order_by('code'):
            _b = _svc_inc.calculate_account_balance(_a, as_of_date, None)
            if _b:
                expense_breakdown.append({'code': _a.code, 'name': _a.name, 'amount': _b})

        # Prior period (same date last year)
        prior_date = as_of_date.replace(year=as_of_date.year - 1)
        prior_total_assets = sum(
            _svc_inc.calculate_account_balance(a, prior_date, None)
            for a in _AccInc.objects.filter(account_type='asset', is_active=True)
        )
        prior_total_equity = sum(
            _svc_inc.calculate_account_balance(a, prior_date, None)
            for a in _AccInc.objects.filter(account_type='equity', is_active=True)
        )

    except Exception:
        loan_count_active = loan_count_paid = loan_count_defaulted = loan_count_total = 0
        total_disbursed = total_repaid = outstanding_port = avg_loan = Decimal('0.00')
        repayment_rate = capital_adequacy = roe = loan_to_equity = 0.0
        ytd_income = ytd_expenses = ytd_net = Decimal('0.00')
        income_breakdown = expense_breakdown = []
        prior_total_assets = prior_total_equity = Decimal('0.00')

    context = {
        'asset_items':           asset_items,
        'liability_items':       liability_items,
        'equity_items':          equity_items,
        'total_assets':          total_assets,
        'total_liabilities':     total_liabilities,
        'total_equity':          total_equity,
        'total_liabilities_equity': total_le,
        'balanced':              balanced,
        'difference':            difference,
        'is_balanced':           balanced,
        'equity_ratio':          equity_ratio,
        'debt_ratio':            debt_ratio,
        'debt_to_equity':        debt_to_equity,
        'total_current_assets':          total_current_assets,
        'total_non_current_assets':      total_non_current_assets,
        'total_current_liabilities':     total_current_liabilities,
        'total_non_current_liabilities': total_non_current_liabilities,
        'as_of':                 as_of_date,
        'as_of_date':            as_of_date,
        'branches':              branches,
        'selected_branch':       branch_id,
        'source':                'accounting_system',
        'generated_at':          timezone.now().isoformat(),
        'today':                 date.today(),
        'report_title':          'Statement of Financial Position',
        # Loan portfolio metrics
        'loan_count_active':     loan_count_active,
        'loan_count_paid':       loan_count_paid,
        'loan_count_defaulted':  loan_count_defaulted,
        'loan_count_total':      loan_count_total,
        'total_disbursed':       total_disbursed,
        'total_repaid':          total_repaid,
        'outstanding_port':      outstanding_port,
        'avg_loan':              avg_loan,
        'repayment_rate':        repayment_rate,
        # Financial ratios
        'capital_adequacy':      capital_adequacy,
        'roe':                   roe,
        'loan_to_equity':        loan_to_equity,
        # P&L summary
        'ytd_income':            ytd_income,
        'ytd_expenses':          ytd_expenses,
        'ytd_net':               ytd_net,
        'income_breakdown':      income_breakdown,
        'expense_breakdown':     expense_breakdown,
        # Prior period
        'prior_date':            prior_date,
        'prior_total_assets':    prior_total_assets,
        'prior_total_equity':    prior_total_equity,
    }
    return render(request, 'reports/financial/financial_statements.html', context)


# ── 4. Loan Aging ──────────────────────────────────────────────────────────

@login_required
@staff_required
def loan_aging(request):
    branch_id = request.GET.get('branch') or None
    product_id = request.GET.get('product') or None

    branches = Branch.objects.filter(is_active=True).order_by('name')
    products = LoanProduct.objects.filter(is_active=True).order_by('name')

    data = get_loan_aging(branch_id, product_id, include_detail=True)

    context = {
        **data,
        'branches': branches,
        'products': products,
        'selected_branch': branch_id,
        'selected_product': product_id,
        'report_title': 'Loan Aging Report',
    }
    return render(request, 'reports/financial/loan_aging.html', context)


@login_required
@staff_required
def loan_aging_export_csv(request):
    """Export loan aging detail as CSV."""
    branch_id = request.GET.get('branch') or None
    product_id = request.GET.get('product') or None

    data = get_loan_aging(branch_id, product_id, include_detail=True)

    import csv
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = (
        f'attachment; filename="loan_aging_{data["as_of"]}.csv"'
    )

    writer = csv.writer(response)
    writer.writerow([
        'Loan Number', 'Borrower', 'Phone', 'Product',
        'Principal (KES)', 'Outstanding (KES)', 'Due Date', 'Days Past Due', 'Aging Bucket'
    ])

    for bucket in data['buckets']:
        for loan in bucket['loans']:
            writer.writerow([
                loan['loan_number'],
                loan['borrower_name'],
                loan['borrower_phone'],
                loan['product'],
                loan['principal'],
                loan['outstanding'],
                loan['due_date'],
                loan['days_past_due'],
                bucket['label'],
            ])

    return response


# ── 5. Chart of Accounts ──────────────────────────────────────────────────

@login_required
@staff_required
def chart_of_accounts(request):
    """Display complete Chart of Accounts with balances, date and type filtering."""
    from decimal import Decimal
    
    # Parse filters
    as_of_date = date.today()
    if request.GET.get('as_of'):
        try:
            as_of_date = datetime.strptime(request.GET.get('as_of'), '%Y-%m-%d').date()
        except ValueError:
            pass
    
    type_filter = request.GET.get('type_filter', 'all')
    status_filter = request.GET.get('status_filter', 'active')
    
    try:
        from accounting.models import Account
        from accounting.services.accounting_service import AccountingService
        
        accounting_service = AccountingService()
        
        # Build base queryset
        qs = Account.objects.all().order_by('code')
        if status_filter == 'active':
            qs = qs.filter(is_active=True)
        
        # Get all accounts grouped by type
        asset_accounts = []
        liability_accounts = []
        equity_accounts = []
        income_accounts = []
        expense_accounts = []
        
        type_map = {
            'asset': asset_accounts,
            'liability': liability_accounts,
            'equity': equity_accounts,
            'income': income_accounts,
            'expense': expense_accounts,
        }
        
        # Only load the requested type(s)
        if type_filter != 'all':
            qs = qs.filter(account_type=type_filter)
        
        for account in qs:
            try:
                balance = accounting_service.calculate_account_balance(
                    account=account,
                    as_of_date=as_of_date,
                    branch=None
                )
            except Exception:
                balance = Decimal('0.00')
            
            account_data = {
                'code': account.code,
                'name': account.name,
                'description': account.description or '',
                'subtype': account.subtype or '',
                'is_system_account': account.is_system_account,
                'is_active': account.is_active,
                'balance': balance,
            }
            
            bucket = type_map.get(account.account_type)
            if bucket is not None:
                bucket.append(account_data)
        
        total_qs = Account.objects.all()
        active_qs = Account.objects.filter(is_active=True)
        
        # Expense sub-groups for the side-by-side panel layout
        expense_groups = [
            {'subtype': 'interest_expense',       'label': 'INTEREST EXPENSE',
             'note': '4', 'codes': 'Code 5010',
             'bg': '#fde8e8', 'fg': '#7b241c',
             'pill_bg': '#fee2e2', 'pill_fg': '#991b1b', 'pill_label': 'Interest Exp.'},
            {'subtype': 'loan_loss_provision',    'label': 'LOAN LOSS PROVISION (ECL)',
             'note': '5', 'codes': 'Codes 5020–5022',
             'bg': '#fef3c7', 'fg': '#7d6608',
             'pill_bg': '#fef9c3', 'pill_fg': '#713f12', 'pill_label': 'Loan Loss'},
            {'subtype': 'staff_costs',            'label': 'STAFF COSTS',
             'note': '6', 'codes': 'Codes 5030–5033',
             'bg': '#dbeafe', 'fg': '#1e3a8a',
             'pill_bg': '#eff6ff', 'pill_fg': '#1e40af', 'pill_label': 'Staff Costs'},
            {'subtype': 'administrative_expense', 'label': 'ADMINISTRATIVE EXPENSES',
             'note': '7', 'codes': 'Codes 5040–5048',
             'bg': '#f1f5f9', 'fg': '#334155',
             'pill_bg': '#f8fafc', 'pill_fg': '#475569', 'pill_label': 'Admin Exp.'},
            {'subtype': 'depreciation',           'label': 'DEPRECIATION & AMORTISATION',
             'note': '8', 'codes': 'Codes 5050–5052',
             'bg': '#e0e7ff', 'fg': '#3730a3',
             'pill_bg': '#eef2ff', 'pill_fg': '#3730a3', 'pill_label': 'Depreciation'},
            {'subtype': 'other_expense',          'label': 'OTHER OPERATING EXPENSES',
             'note': '9', 'codes': 'Codes 5060–5062',
             'bg': '#f9fafb', 'fg': '#374151',
             'pill_bg': '#f3f4f6', 'pill_fg': '#6b7280', 'pill_label': 'Other Expense'},
            {'subtype': 'taxation',               'label': 'INCOME TAX EXPENSE',
             'note': '10', 'codes': 'Codes 5070–5071',
             'bg': '#fae8ff', 'fg': '#701a75',
             'pill_bg': '#fdf4ff', 'pill_fg': '#86198f', 'pill_label': 'Tax'},
        ]

        context = {
            'asset_accounts': asset_accounts,
            'liability_accounts': liability_accounts,
            'equity_accounts': equity_accounts,
            'income_accounts': income_accounts,
            'expense_accounts': expense_accounts,
            'expense_groups': expense_groups,
            'asset_count': len(asset_accounts),
            'liability_count': len(liability_accounts),
            'equity_count': len(equity_accounts),
            'income_count': len(income_accounts),
            'expense_count': len(expense_accounts),
            'total_accounts': total_qs.count(),
            'active_accounts': active_qs.count(),
            'system_accounts': total_qs.filter(is_system_account=True).count(),
            'account_types': 5,
            'as_of': as_of_date,
            'today': date.today(),
            'type_filter': type_filter,
            'status_filter': status_filter,
            'report_title': 'Chart of Accounts',
        }
        
        return render(request, 'reports/financial/chart_of_accounts.html', context)
        
    except ImportError:
        context = {
            'asset_accounts': [], 'liability_accounts': [],
            'equity_accounts': [], 'income_accounts': [], 'expense_accounts': [],
            'asset_count': 0, 'liability_count': 0, 'equity_count': 0,
            'income_count': 0, 'expense_count': 0,
            'total_accounts': 0, 'active_accounts': 0, 'system_accounts': 0,
            'account_types': 5, 'as_of': date.today(), 'today': date.today(),
            'type_filter': 'all', 'status_filter': 'active',
            'report_title': 'Chart of Accounts',
            'error_message': 'Accounting system not configured.',
        }
        return render(request, 'reports/financial/chart_of_accounts.html', context)


# ── 6. Account Ledger (Drill-Down) ────────────────────────────────────────

@login_required
@staff_required
def account_ledger(request, account_code):
    """Display detailed general ledger entries for a specific account."""
    from datetime import timedelta
    from decimal import Decimal
    from django.core.paginator import Paginator
    
    try:
        from accounting.models import Account, GeneralLedger
        from accounting.services.accounting_service import AccountingService
        
        # Get the account
        account = Account.objects.get(code=account_code)
        accounting_service = AccountingService()
        
        # Get date filters
        end_date = date.today()
        start_date = end_date - timedelta(days=90)  # Default to last 90 days
        
        if request.GET.get('start_date'):
            try:
                start_date = datetime.strptime(request.GET.get('start_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        if request.GET.get('end_date'):
            try:
                end_date = datetime.strptime(request.GET.get('end_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        # Get search filter
        search_reference = request.GET.get('reference', '')
        
        # Get opening balance (day before start date)
        opening_balance = Decimal('0.00')
        if start_date > date(2020, 1, 1):  # Avoid going too far back
            opening_balance = accounting_service.calculate_account_balance(
                account=account,
                as_of_date=start_date - timedelta(days=1),
                branch=None
            )
        
        # Get transactions in period
        transactions_qs = GeneralLedger.objects.filter(
            account=account,
            transaction_date__gte=start_date,
            transaction_date__lte=end_date
        ).select_related('journal_entry', 'posted_by').order_by('transaction_date', 'posted_at')
        
        # Apply search filter
        if search_reference:
            transactions_qs = transactions_qs.filter(reference_number__icontains=search_reference)
        
        # Calculate totals
        total_debits = Decimal('0.00')
        total_credits = Decimal('0.00')
        
        # Paginate
        paginator = Paginator(transactions_qs, 50)  # 50 per page
        page_number = request.GET.get('page', 1)
        page_obj = paginator.get_page(page_number)
        
        # Prepare transaction data with posted_by username
        transactions = []
        for entry in page_obj:
            transactions.append({
                'transaction_date': entry.transaction_date,
                'reference_number': entry.reference_number,
                'description': entry.description,
                'debit_amount': entry.debit_amount,
                'credit_amount': entry.credit_amount,
                'balance': entry.balance,
                'posted_by': entry.posted_by.get_full_name() if entry.posted_by else 'System',
                'journal_entry_id': entry.journal_entry.id if entry.journal_entry else None,
            })
            total_debits += entry.debit_amount
            total_credits += entry.credit_amount
        
        # Calculate net change and current balance
        net_change = total_debits - total_credits if account.account_type in ['asset', 'expense'] else total_credits - total_debits
        current_balance = accounting_service.calculate_account_balance(
            account=account,
            as_of_date=end_date,
            branch=None
        )
        
        # Handle export
        export_format = request.GET.get('export')
        if export_format == 'pdf':
            return _export_account_ledger_pdf(account, transactions, opening_balance, current_balance, start_date, end_date)
        elif export_format == 'excel':
            return _export_account_ledger_excel(account, transactions, opening_balance, current_balance, start_date, end_date)
        
        context = {
            'account': account,
            'transactions': transactions,
            'opening_balance': opening_balance,
            'current_balance': current_balance,
            'total_debits': total_debits,
            'total_credits': total_credits,
            'net_change': net_change,
            'total_transactions': transactions_qs.count(),
            'start_date': start_date,
            'end_date': end_date,
            'search_reference': search_reference,
            'page_obj': page_obj,
            'is_paginated': page_obj.has_other_pages(),
            'report_title': f'Account Ledger: {account.code} - {account.name}',
        }
        
        return render(request, 'reports/financial/account_ledger.html', context)
        
    except Account.DoesNotExist:
        from django.contrib import messages
        messages.error(request, f'Account {account_code} not found.')
        return redirect('reports:chart_of_accounts')
    except ImportError:
        from django.contrib import messages
        messages.error(request, 'Accounting system not configured.')
        return redirect('reports:chart_of_accounts')


def _export_account_ledger_pdf(account, transactions, opening_balance, current_balance, start_date, end_date):
    """Export account ledger to PDF."""
    # TODO: Implement PDF export
    from django.http import HttpResponse
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = f'attachment; filename="account_ledger_{account.code}_{start_date}.pdf"'
    response.write(b'PDF export coming soon!')
    return response


def _export_account_ledger_excel(account, transactions, opening_balance, current_balance, start_date, end_date):
    """Export account ledger to Excel."""
    import csv
    from django.http import HttpResponse
    
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = f'attachment; filename="account_ledger_{account.code}_{start_date}.csv"'
    
    writer = csv.writer(response)
    writer.writerow(['Account Ledger Report'])
    writer.writerow([f'Account: {account.code} - {account.name}'])
    writer.writerow([f'Period: {start_date} to {end_date}'])
    writer.writerow([])
    writer.writerow(['Date', 'Reference', 'Description', 'Debit', 'Credit', 'Balance', 'Posted By'])
    
    # Opening balance
    writer.writerow([start_date, '', 'Opening Balance', '', '', opening_balance, ''])
    
    # Transactions
    for entry in transactions:
        writer.writerow([
            entry['transaction_date'],
            entry['reference_number'],
            entry['description'],
            entry['debit_amount'] if entry['debit_amount'] > 0 else '',
            entry['credit_amount'] if entry['credit_amount'] > 0 else '',
            entry['balance'],
            entry['posted_by'],
        ])
    
    # Closing balance
    writer.writerow([end_date, '', 'Closing Balance', '', '', current_balance, ''])
    
    return response


# ── 7. Journal Entry Detail ───────────────────────────────────────────────

@login_required
@staff_required
def journal_entry_detail(request, entry_id):
    """Display detailed view of a journal entry."""
    try:
        from accounting.models import JournalEntry
        
        entry = JournalEntry.objects.get(id=entry_id)
        lines = entry.lines.all().select_related('account').order_by('line_number')
        
        total_debits = sum(line.debit_amount for line in lines)
        total_credits = sum(line.credit_amount for line in lines)
        balanced = total_debits == total_credits
        
        context = {
            'entry': entry,
            'lines': lines,
            'total_debits': total_debits,
            'total_credits': total_credits,
            'balanced': balanced,
            'report_title': f'Journal Entry: {entry.reference_number}',
        }
        
        return render(request, 'reports/financial/journal_entry_detail.html', context)
        
    except Exception as e:
        from django.contrib import messages
        messages.error(request, f'Error loading journal entry: {e}')
        return redirect('reports:reports_dashboard')



# ══════════════════════════════════════════════════════════════════════════
# PDF EXPORT VIEWS
# ══════════════════════════════════════════════════════════════════════════

@login_required
@staff_required
def chart_of_accounts_pdf(request):
    """Export Chart of Accounts as PDF with optional date filter."""
    try:
        from accounting.models import Account
        from accounting.services.accounting_service import AccountingService
        from accounting.pdf_reports import AccountingPDFGenerator
        
        accounting_service = AccountingService()
        as_of_date = date.today()
        if request.GET.get('as_of'):
            try:
                as_of_date = datetime.strptime(request.GET.get('as_of'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        # Get all active accounts grouped by type
        accounts_by_type = {
            'asset': [], 'liability': [], 'equity': [], 'income': [], 'expense': []
        }
        
        for account in Account.objects.filter(is_active=True).order_by('code'):
            try:
                balance = accounting_service.calculate_account_balance(
                    account=account, as_of_date=as_of_date, branch=None
                )
            except Exception:
                balance = Decimal('0.00')
            
            account_data = {
                'code': account.code,
                'name': account.name,
                'description': account.description or '',
                'subtype': account.subtype or '',
                'balance': balance,
            }
            
            if account.account_type in accounts_by_type:
                accounts_by_type[account.account_type].append(account_data)
        
        pdf_generator = AccountingPDFGenerator()
        pdf_buffer = pdf_generator.generate_chart_of_accounts_pdf(
            accounts_by_type=accounts_by_type,
            as_of_date=as_of_date,
            include_balances=True
        )
        
        response = HttpResponse(pdf_buffer, content_type='application/pdf')
        response['Content-Disposition'] = (
            f'inline; filename="chart_of_accounts_{as_of_date}.pdf"'
        )
        return response
        
    except ImportError:
        messages.error(request, 'Accounting system not configured.')
        return redirect('reports:chart_of_accounts')
    except Exception as e:
        messages.error(request, f'Error generating PDF: {str(e)}')
        return redirect('reports:chart_of_accounts')


@login_required
@staff_required
def account_ledger_pdf(request, account_code):
    """Export Account Ledger as PDF."""
    from datetime import timedelta
    
    try:
        from accounting.models import Account, GeneralLedger
        from accounting.services.accounting_service import AccountingService
        from accounting.pdf_reports import AccountingPDFGenerator
        
        # Get the account
        account = Account.objects.get(code=account_code)
        accounting_service = AccountingService()
        
        # Get date filters
        end_date = date.today()
        start_date = end_date - timedelta(days=90)  # Default to last 90 days
        
        if request.GET.get('start_date'):
            try:
                start_date = datetime.strptime(request.GET.get('start_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        if request.GET.get('end_date'):
            try:
                end_date = datetime.strptime(request.GET.get('end_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        # Get transactions in period
        transactions_qs = GeneralLedger.objects.filter(
            account=account,
            transaction_date__gte=start_date,
            transaction_date__lte=end_date
        ).select_related('journal_entry', 'posted_by').order_by('transaction_date', 'posted_at')
        
        # Prepare transaction data
        transactions = []
        for entry in transactions_qs:
            transactions.append({
                'date': entry.transaction_date,
                'description': entry.description,
                'debit': entry.debit_amount if entry.debit_amount > 0 else None,
                'credit': entry.credit_amount if entry.credit_amount > 0 else None,
                'balance': entry.balance,
            })
        
        # Account info
        account_info = {
            'code': account.code,
            'name': account.name,
            'type': account.account_type,
            'subtype': account.subtype
        }

        # Opening balance (day before start)
        opening_balance = Decimal('0.00')
        try:
            from accounting.services.accounting_service import AccountingService
            _svc = AccountingService()
            opening_balance = _svc.calculate_account_balance(
                account=account,
                as_of_date=start_date - timedelta(days=1),
                branch=None
            )
        except Exception:
            pass

        # Generate PDF
        pdf_generator = AccountingPDFGenerator()
        pdf_buffer = pdf_generator.generate_account_ledger_pdf(
            account=account_info,
            transactions=transactions,
            start_date=start_date,
            end_date=end_date,
            opening_balance=opening_balance,
        )

        # Return PDF response — inline so it opens in browser tab
        response = HttpResponse(pdf_buffer, content_type='application/pdf')
        response['Content-Disposition'] = (
            f'inline; filename="account_ledger_{account_code}'
            f'_{start_date}_to_{end_date}.pdf"'
        )
        return response
        
    except Account.DoesNotExist:
        messages.error(request, f'Account {account_code} not found.')
        return redirect('reports:chart_of_accounts')
    except Exception as e:
        messages.error(request, f'Error generating PDF: {str(e)}')
        return redirect('reports:chart_of_accounts')


@login_required
@staff_required
def trial_balance_pdf(request):
    """Export Trial Balance as PDF — 8-column professional format with opening/activity/closing."""
    try:
        from accounting.services.report_service import ReportService
        from accounting.pdf_reports import AccountingPDFGenerator

        as_of_date = date.today()
        if request.GET.get('as_of'):
            try:
                as_of_date = datetime.strptime(request.GET.get('as_of'), '%Y-%m-%d').date()
            except ValueError:
                pass

        period_start = None
        if request.GET.get('period_start'):
            try:
                period_start = datetime.strptime(
                    request.GET.get('period_start'), '%Y-%m-%d').date()
            except ValueError:
                pass

        report_service = ReportService()
        trial_balance_data = report_service.generate_trial_balance_full(
            as_of_date=as_of_date,
            branch=None,
            period_start=period_start,
        )

        pdf_generator = AccountingPDFGenerator()
        pdf_buffer = pdf_generator.generate_trial_balance_pdf(
            trial_balance_data=trial_balance_data,
            as_of_date=as_of_date
        )

        response = HttpResponse(pdf_buffer, content_type='application/pdf')
        response['Content-Disposition'] = (
            f'inline; filename="trial_balance_{as_of_date}.pdf"'
        )
        return response

    except Exception as e:
        messages.error(request, f'Error generating Trial Balance PDF: {str(e)}')
        return redirect('reports:financial_reports_index')



@login_required
@staff_required
def income_statement_pdf(request):
    """Export Income Statement as professional 6-column PDF with variance analysis."""
    from datetime import timedelta

    try:
        from accounting.models import Account
        from accounting.services.accounting_service import AccountingService
        from accounting.pdf_reports import AccountingPDFGenerator

        accounting_service = AccountingService()

        # Current period
        end_date   = date.today()
        start_date = end_date.replace(day=1)

        if request.GET.get('start_date'):
            try:
                start_date = datetime.strptime(request.GET.get('start_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        if request.GET.get('end_date'):
            try:
                end_date = datetime.strptime(request.GET.get('end_date'), '%Y-%m-%d').date()
            except ValueError:
                pass

        # Prior-period default: same date range one year ago
        prior_end   = end_date.replace(year=end_date.year - 1)
        prior_start = start_date.replace(year=start_date.year - 1)

        def _period_activity(account, p_start, p_end):
            bal     = accounting_service.calculate_account_balance(account, p_end, None)
            opening = (accounting_service.calculate_account_balance(
                           account, p_start - timedelta(days=1), None)
                       if p_start > date(2000, 1, 1) else Decimal('0.00'))
            return bal - opening

        # Build current income items with note numbers
        NOTE_MAP = {
            '4010': '1', '4020': '2', '4021': '2', '4022': '2', '4030': '3',
            '5010': '4', '5020': '5', '5021': '5', '5022': '5',
            '5030': '6', '5031': '6', '5032': '6', '5033': '6',
            '5040': '7', '5041': '7', '5042': '7', '5043': '7',
            '5044': '7', '5045': '7', '5046': '7', '5047': '7', '5048': '7',
            '5050': '8', '5051': '8', '5052': '8',
            '5060': '9', '5061': '9', '5062': '9',
            '5070': '10', '5071': '10',
        }

        income_accounts  = Account.objects.filter(account_type='income',   is_active=True).order_by('code')
        expense_accounts = Account.objects.filter(account_type='expense',  is_active=True).order_by('code')
        # Exclude tax accounts from expenses (shown separately)
        tax_accounts     = expense_accounts.filter(code__in=['5070', '5071'])
        expense_accounts = expense_accounts.exclude(code__in=['5070', '5071'])

        income_items  = []
        expense_items = []
        prior_income_items  = []
        prior_expense_items = []

        for account in income_accounts:
            amt   = _period_activity(account, start_date, end_date)
            p_amt = _period_activity(account, prior_start, prior_end)
            if amt or p_amt:
                income_items.append({
                    'code': account.code, 'name': account.name,
                    'note': NOTE_MAP.get(account.code, ''),
                    'amount': amt,
                })
                prior_income_items.append({
                    'code': account.code, 'name': account.name,
                    'note': NOTE_MAP.get(account.code, ''),
                    'amount': p_amt,
                })

        for account in expense_accounts:
            amt   = _period_activity(account, start_date, end_date)
            p_amt = _period_activity(account, prior_start, prior_end)
            if amt or p_amt:
                expense_items.append({
                    'code': account.code, 'name': account.name,
                    'note': NOTE_MAP.get(account.code, ''),
                    'amount': amt,
                })
                prior_expense_items.append({
                    'code': account.code, 'name': account.name,
                    'note': NOTE_MAP.get(account.code, ''),
                    'amount': p_amt,
                })

        # Tax
        tax_amt   = sum(_period_activity(a, start_date, end_date)   for a in tax_accounts)
        p_tax_amt = sum(_period_activity(a, prior_start, prior_end) for a in tax_accounts)

        income_data = {
            'income':   income_items,
            'expenses': expense_items,
            'tax': {'note': '10', 'amount': -abs(tax_amt)},  # always outflow
        }
        prior_data = {
            'income':   prior_income_items,
            'expenses': prior_expense_items,
            'tax': {'note': '10', 'amount': -abs(p_tax_amt)},
            'end_date': prior_end,
        }

        pdf_generator = AccountingPDFGenerator()
        pdf_buffer = pdf_generator.generate_income_statement_pdf(
            income_data=income_data,
            start_date=start_date,
            end_date=end_date,
            prior_data=prior_data,
        )

        response = HttpResponse(pdf_buffer, content_type='application/pdf')
        response['Content-Disposition'] = (
            f'inline; filename="income_statement_{start_date}_to_{end_date}.pdf"'
        )
        return response

    except Exception as e:
        messages.error(request, f'Error generating Income Statement PDF: {str(e)}')
        return redirect('reports:income_statement')


@login_required
@staff_required
def balance_sheet_pdf(request):
    """Export Balance Sheet (Statement of Financial Position) as professional side-by-side PDF."""
    try:
        from accounting.models import Account
        from accounting.services.accounting_service import AccountingService
        from accounting.pdf_reports import AccountingPDFGenerator

        accounting_service = AccountingService()

        as_of_date = date.today()
        if request.GET.get('as_of'):
            try:
                as_of_date = datetime.strptime(request.GET.get('as_of'), '%Y-%m-%d').date()
            except ValueError:
                pass

        NOTE_MAP = {
            # Assets
            '1010': '10', '1011': '10', '1012': '10', '1013': '10',
            '1020': '11', '1021': '11', '1030': '12', '1031': '12',
            '1040': '13', '1050': '14', '1060': '15', '1070': '16',
            '1510': '5',  '1511': '5',  '1520': '6',  '1521': '6',
            '1530': '7',  '1540': '8',  '1550': '9',
            # Liabilities
            '2010': '17', '2020': '21', '2030': '22', '2040': '23',
            '2050': '24', '2060': '18', '2070': '25', '2080': '25',
            '2510': '17', '2520': '18', '2530': '19', '2540': '20',
            # Equity
            '3010': '26', '3020': '27', '3030': '28', '3040': '28',
        }

        # Non-current asset subtypes
        NCA_SUBTYPES = {'fixed_asset', 'other_asset'}
        # Non-current liability codes (heuristic: contains 'non' or 'long' or code starts 25xx)
        NCL_CODES = {'2510', '2520', '2530', '2540'}

        def _item(account):
            try:
                balance = accounting_service.calculate_account_balance(
                    account, as_of_date, None)
            except Exception:
                balance = Decimal('0.00')
            return {
                'code':    account.code,
                'name':    account.name,
                'note':    NOTE_MAP.get(account.code, ''),
                'amount':  balance,
                'subtype': account.subtype or '',
                'non_current': account.code in NCL_CODES,
            }

        asset_items = [
            _item(a) for a in Account.objects.filter(
                account_type='asset', is_active=True).order_by('code')
            if accounting_service.calculate_account_balance(a, as_of_date, None) != Decimal('0.00')
        ]
        liability_items = [
            _item(a) for a in Account.objects.filter(
                account_type='liability', is_active=True).order_by('code')
            if accounting_service.calculate_account_balance(a, as_of_date, None) != Decimal('0.00')
        ]
        equity_items = [
            _item(a) for a in Account.objects.filter(
                account_type='equity', is_active=True).order_by('code')
            if accounting_service.calculate_account_balance(a, as_of_date, None) != Decimal('0.00')
        ]

        balance_data = {
            'assets':      asset_items,
            'liabilities': liability_items,
            'equity':      equity_items,
        }

        pdf_generator = AccountingPDFGenerator()
        pdf_buffer = pdf_generator.generate_balance_sheet_pdf(
            balance_data=balance_data,
            as_of_date=as_of_date
        )

        response = HttpResponse(pdf_buffer, content_type='application/pdf')
        response['Content-Disposition'] = (
            f'inline; filename="balance_sheet_{as_of_date}.pdf"'
        )
        return response

    except Exception as e:
        messages.error(request, f'Error generating Balance Sheet PDF: {str(e)}')
        return redirect('reports:balance_sheet')


# ══════════════════════════════════════════════════════════════════════════
# INTERACTIVE HTML REPORT VIEWS (with date filtering)
# ══════════════════════════════════════════════════════════════════════════

@login_required
@staff_required
def trial_balance(request):
    """
    Display Trial Balance with 8-column format (opening / activity / closing).

    Improvements over the old version:
    - All active GL accounts are shown, even those with a zero balance, so the
      full chart of accounts is always visible (matches the auditor reference).
    - Accounts are grouped in the canonical order: Assets → Liabilities →
      Equity → Income → Expenses, with a section-level subtotal row after each
      group.
    - Separate tracked totals for assets (debit side) vs liabilities+equity
      (credit side) are passed to the template so the summary panel is correct.
    - The grand-total row labels are accurate: left column = TOTAL ASSETS,
      right column = TOTAL LIABILITIES AND EQUITY.
    """
    from decimal import Decimal
    from accounting.services.report_service import ReportService
    from accounting.models import Account

    try:
        # ── Date filters ────────────────────────────────────────────────
        as_of_date = date.today()
        if request.GET.get('as_of'):
            try:
                as_of_date = datetime.strptime(request.GET.get('as_of'), '%Y-%m-%d').date()
            except ValueError:
                pass

        period_start = as_of_date.replace(day=1)
        if request.GET.get('period_start'):
            try:
                period_start = datetime.strptime(
                    request.GET.get('period_start'), '%Y-%m-%d').date()
            except ValueError:
                pass

        # ── Export shortcuts ─────────────────────────────────────────────
        export_format = request.GET.get('format')
        if export_format == 'pdf':
            return trial_balance_pdf(request)
        elif export_format == 'excel':
            return _export_trial_balance_excel(as_of_date)

        # ── Pull full 8-column data (only accounts with activity/balance) ─
        report_service = ReportService()
        tb_data = report_service.generate_trial_balance_full(
            as_of_date=as_of_date,
            branch=None,
            period_start=period_start,
        )

        # Build a lookup of accounts that have data
        active_accounts_with_data = {
            a['code']: a for a in tb_data.get('accounts', [])
        }

        # Fetch ALL active accounts so zero-balance ones still appear
        all_active = Account.objects.filter(
            is_active=True
        ).only('code', 'name', 'account_type').order_by('code')

        zero = Decimal('0.00')

        # Merge: use service data where available, else zero-padded row
        merged_accounts = []
        for acc in all_active:
            if acc.code in active_accounts_with_data:
                merged_accounts.append(active_accounts_with_data[acc.code])
            else:
                merged_accounts.append({
                    'code':            acc.code,
                    'name':            acc.name,
                    'type':            acc.account_type,
                    'opening_debit':   zero,
                    'opening_credit':  zero,
                    'activity_debit':  zero,
                    'activity_credit': zero,
                    'closing_debit':   zero,
                    'closing_credit':  zero,
                    'debit_balance':   zero,
                    'credit_balance':  zero,
                })

        # ── Group into sections in canonical order ───────────────────────
        TYPE_ORDER  = ['asset', 'liability', 'equity', 'income', 'expense']
        TYPE_LABELS = {
            'asset':     'Assets',
            'liability': 'Liabilities',
            'equity':    'Equity',
            'income':    'Income',
            'expense':   'Expenses',
        }

        sections = []          # list of {label, colour, accounts, subtotals}
        grand_op_d = grand_op_c = zero
        grand_ac_d = grand_ac_c = zero
        grand_cl_d = grand_cl_c = zero

        # Separate asset totals from liability+equity for correct summary panel
        total_assets           = zero
        total_liabilities      = zero
        total_equity           = zero
        total_income           = zero
        total_expenses         = zero

        SECTION_COLOURS = {
            'asset':     '#155724',   # dark green text on light green bg
            'liability': '#7b241c',   # dark red text on light red bg
            'equity':    '#7d6608',   # dark amber text on amber bg
            'income':    '#5b21b6',   # purple
            'expense':   '#9d174d',   # pink
        }
        SECTION_BG = {
            'asset':     '#d4edda',
            'liability': '#fde8e8',
            'equity':    '#fef3c7',
            'income':    '#ede9fe',
            'expense':   '#fce7f3',
        }

        for acc_type in TYPE_ORDER:
            type_accounts = [a for a in merged_accounts if a['type'] == acc_type]
            if not type_accounts:
                continue

            sub_op_d = sub_op_c = zero
            sub_ac_d = sub_ac_c = zero
            sub_cl_d = sub_cl_c = zero

            for a in type_accounts:
                sub_op_d += Decimal(str(a.get('opening_debit',  0) or 0))
                sub_op_c += Decimal(str(a.get('opening_credit', 0) or 0))
                sub_ac_d += Decimal(str(a.get('activity_debit',  0) or 0))
                sub_ac_c += Decimal(str(a.get('activity_credit', 0) or 0))
                sub_cl_d += Decimal(str(a.get('closing_debit',
                                              a.get('debit_balance',  0)) or 0))
                sub_cl_c += Decimal(str(a.get('closing_credit',
                                              a.get('credit_balance', 0)) or 0))

            sections.append({
                'type':     acc_type,
                'label':    TYPE_LABELS[acc_type],
                'colour':   SECTION_COLOURS[acc_type],
                'bg':       SECTION_BG[acc_type],
                'accounts': type_accounts,
                'sub_op_d': sub_op_d, 'sub_op_c': sub_op_c,
                'sub_ac_d': sub_ac_d, 'sub_ac_c': sub_ac_c,
                'sub_cl_d': sub_cl_d, 'sub_cl_c': sub_cl_c,
            })

            grand_op_d += sub_op_d;  grand_op_c += sub_op_c
            grand_ac_d += sub_ac_d;  grand_ac_c += sub_ac_c
            grand_cl_d += sub_cl_d;  grand_cl_c += sub_cl_c

            if acc_type == 'asset':
                total_assets      = sub_cl_d   # gross debit balance of all asset accounts
            elif acc_type == 'liability':
                total_liabilities = sub_cl_c   # gross credit balance of all liability accounts
            elif acc_type == 'equity':
                total_equity      = sub_cl_c   # gross credit balance of all equity accounts
            elif acc_type == 'income':
                total_income      = sub_cl_c
            elif acc_type == 'expense':
                total_expenses    = sub_cl_d

        totals      = tb_data.get('totals', {})
        total_debits  = totals.get('closing_debits',  grand_cl_d)
        total_credits = totals.get('closing_credits', grand_cl_c)
        difference    = abs(total_debits - total_credits)
        is_balanced   = difference < Decimal('0.01')

        accounts_with_activity = len(active_accounts_with_data)

        # For the summary panel: use the same gross totals the grand total row shows.
        # total_assets  = all debit-side closing balances (grand_cl_d)
        # total_le      = all credit-side closing balances (grand_cl_c)
        # total_liabilities / total_equity are per-section credit-side subtotals.
        # This way Total Assets always equals Total L&E (both come from the grand total).
        summary_total_assets = grand_cl_d
        summary_total_le     = grand_cl_c

        context = {
            'sections':            sections,
            'total_debits':        total_debits,
            'total_credits':       total_credits,
            'grand_op_d':          grand_op_d,
            'grand_op_c':          grand_op_c,
            'grand_ac_d':          grand_ac_d,
            'grand_ac_c':          grand_ac_c,
            'grand_cl_d':          grand_cl_d,
            'grand_cl_c':          grand_cl_c,
            'difference':          difference,
            'is_balanced':         is_balanced,
            'balance_status':      'balanced' if is_balanced else 'unbalanced',
            'account_count':       accounts_with_activity,
            'total_account_count': len(merged_accounts),
            # Summary panel – grand_cl_d = total debit side, grand_cl_c = total credit side.
            # These always equal each other when balanced, so Assets == L+E is guaranteed.
            'total_assets':        summary_total_assets,
            'total_liabilities':   total_liabilities,
            'total_equity':        total_equity,
            'total_le':            summary_total_le,
            'total_income':        total_income,
            'total_expenses':      total_expenses,
            'as_of_date':          as_of_date,
            'period_start':        period_start,
            'today':               date.today(),
            'report_title':        'Trial Balance',
        }
        return render(request, 'reports/financial/trial_balance.html', context)

    except ImportError:
        messages.error(request, 'Accounting system not configured.')
        return redirect('reports:financial_reports_index')
    except Exception as e:
        messages.error(request, f'Error generating trial balance: {str(e)}')
        return redirect('reports:financial_reports_index')


def _export_trial_balance_excel(as_of_date):
    """Export trial balance to Excel — 8-column professional format."""
    from django.http import HttpResponse
    from accounting.services.report_service import ReportService
    from accounting.services.export_service import ExportService

    report_service = ReportService()
    report_data    = report_service.generate_trial_balance_full(
        as_of_date=as_of_date,
        branch=None,
    )

    export_service = ExportService()
    buffer = export_service.export_trial_balance_excel(report_data)

    response = HttpResponse(
        buffer.getvalue(),
        content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    )
    response['Content-Disposition'] = (
        f'attachment; filename="trial_balance_{as_of_date}.xlsx"'
    )
    return response


@login_required
@staff_required
def income_statement(request):
    """Display Income Statement (Profit & Loss) with date range filtering."""
    from decimal import Decimal
    
    try:
        from accounting.models import Account
        from accounting.services.accounting_service import AccountingService
        
        accounting_service = AccountingService()
        
        # Get date range
        end_date = date.today()
        start_date = end_date.replace(day=1)  # First day of current month
        
        if request.GET.get('start_date'):
            try:
                start_date = datetime.strptime(request.GET.get('start_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        if request.GET.get('end_date'):
            try:
                end_date = datetime.strptime(request.GET.get('end_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        # Handle export requests
        export_format = request.GET.get('format')
        if export_format == 'pdf':
            return income_statement_pdf(request)
        elif export_format == 'excel':
            return _export_income_statement_excel(start_date, end_date)
        
        # Get income accounts with period activity
        income_accounts = Account.objects.filter(account_type='income', is_active=True).order_by('code')
        income_items = []
        total_income = Decimal('0.00')
        
        for account in income_accounts:
            balance = accounting_service.calculate_account_balance(account, end_date, None)
            opening_balance = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
            period_activity = balance - opening_balance
            
            if period_activity != Decimal('0.00'):
                income_items.append({
                    'code': account.code,
                    'name': account.name,
                    'amount': period_activity,
                    'cumulative': balance
                })
                total_income += period_activity
        
        # Get expense accounts with period activity
        expense_accounts = Account.objects.filter(account_type='expense', is_active=True).order_by('code')
        expense_items = []
        total_expenses = Decimal('0.00')
        
        for account in expense_accounts:
            balance = accounting_service.calculate_account_balance(account, end_date, None)
            opening_balance = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
            period_activity = balance - opening_balance
            
            if period_activity != Decimal('0.00'):
                expense_items.append({
                    'code': account.code,
                    'name': account.name,
                    'amount': period_activity,
                    'cumulative': balance
                })
                total_expenses += period_activity
        
        # Calculate net income
        net_income = total_income - total_expenses
        net_income_status = 'profit' if net_income >= 0 else 'loss'
        
        # Calculate key ratios
        gross_margin = (total_income / total_income * 100) if total_income > 0 else Decimal('0.00')
        expense_ratio = (total_expenses / total_income * 100) if total_income > 0 else Decimal('0.00')
        profit_margin = (net_income / total_income * 100) if total_income > 0 else Decimal('0.00')
        
        context = {
            'income_items': income_items,
            'expense_items': expense_items,
            'total_income': total_income,
            'total_expenses': total_expenses,
            'net_income': net_income,
            'net_income_status': net_income_status,
            'gross_margin': gross_margin,
            'expense_ratio': expense_ratio,
            'profit_margin': profit_margin,
            'start_date': start_date,
            'end_date': end_date,
            'today': date.today(),
            'report_title': 'Income Statement (Profit & Loss)',
        }
        
        return render(request, 'reports/financial/income_statement.html', context)
        
    except ImportError:
        messages.error(request, 'Accounting system not configured.')
        return redirect('reports:financial_reports_index')
    except Exception as e:
        messages.error(request, f'Error generating income statement: {str(e)}')
        return redirect('reports:financial_reports_index')


def _export_income_statement_excel(start_date, end_date):
    """Export income statement to Excel/CSV."""
    import csv
    from django.http import HttpResponse
    from accounting.models import Account
    from accounting.services.accounting_service import AccountingService
    from decimal import Decimal
    
    accounting_service = AccountingService()
    
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = f'attachment; filename="income_statement_{start_date}_to_{end_date}.csv"'
    
    writer = csv.writer(response)
    writer.writerow(['Income Statement (Profit & Loss)'])
    writer.writerow([f'Period: {start_date} to {end_date}'])
    writer.writerow([])
    
    # Income section
    writer.writerow(['REVENUE & INCOME'])
    writer.writerow(['Code', 'Account Name', 'Amount (KES)'])
    
    income_accounts = Account.objects.filter(account_type='income', is_active=True).order_by('code')
    total_income = Decimal('0.00')
    
    for account in income_accounts:
        balance = accounting_service.calculate_account_balance(account, end_date, None)
        opening_balance = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
        period_activity = balance - opening_balance
        
        if period_activity != Decimal('0.00'):
            writer.writerow([account.code, account.name, f"{period_activity:.2f}"])
            total_income += period_activity
    
    writer.writerow(['', 'TOTAL INCOME', f"{total_income:.2f}"])
    writer.writerow([])
    
    # Expenses section
    writer.writerow(['EXPENSES'])
    writer.writerow(['Code', 'Account Name', 'Amount (KES)'])
    
    expense_accounts = Account.objects.filter(account_type='expense', is_active=True).order_by('code')
    total_expenses = Decimal('0.00')
    
    for account in expense_accounts:
        balance = accounting_service.calculate_account_balance(account, end_date, None)
        opening_balance = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
        period_activity = balance - opening_balance
        
        if period_activity != Decimal('0.00'):
            writer.writerow([account.code, account.name, f"{period_activity:.2f}"])
            total_expenses += period_activity
    
    writer.writerow(['', 'TOTAL EXPENSES', f"{total_expenses:.2f}"])
    writer.writerow([])
    
    # Net income
    net_income = total_income - total_expenses
    writer.writerow(['', 'NET INCOME (LOSS)', f"{net_income:.2f}"])
    
    return response


@login_required
@staff_required
def balance_sheet(request):
    """Display Balance Sheet with date filtering."""
    from decimal import Decimal
    
    try:
        from accounting.models import Account
        from accounting.services.accounting_service import AccountingService
        
        accounting_service = AccountingService()
        
        # Get date filter
        as_of_date = date.today()
        if request.GET.get('as_of'):
            try:
                as_of_date = datetime.strptime(request.GET.get('as_of'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        # Handle export requests
        export_format = request.GET.get('format')
        if export_format == 'pdf':
            return balance_sheet_pdf(request)
        elif export_format == 'excel':
            return _export_balance_sheet_excel(as_of_date)
        
        # Get asset accounts
        asset_accounts = Account.objects.filter(account_type='asset', is_active=True).order_by('code')
        asset_items = []
        total_assets = Decimal('0.00')
        
        for account in asset_accounts:
            balance = accounting_service.calculate_account_balance(account, as_of_date, None)
            if balance != Decimal('0.00'):
                asset_items.append({
                    'code': account.code,
                    'name': account.name,
                    'subtype': account.subtype or 'asset',
                    'amount': balance
                })
                total_assets += balance
        
        # Get liability accounts
        liability_accounts = Account.objects.filter(account_type='liability', is_active=True).order_by('code')
        liability_items = []
        total_liabilities = Decimal('0.00')
        
        for account in liability_accounts:
            balance = accounting_service.calculate_account_balance(account, as_of_date, None)
            if balance != Decimal('0.00'):
                liability_items.append({
                    'code': account.code,
                    'name': account.name,
                    'subtype': account.subtype or 'liability',
                    'amount': balance
                })
                total_liabilities += balance
        
        # Get equity accounts
        equity_accounts = Account.objects.filter(account_type='equity', is_active=True).order_by('code')
        equity_items = []
        total_equity = Decimal('0.00')
        
        for account in equity_accounts:
            balance = accounting_service.calculate_account_balance(account, as_of_date, None)
            if balance != Decimal('0.00'):
                equity_items.append({
                    'code': account.code,
                    'name': account.name,
                    'subtype': account.subtype or 'equity',
                    'amount': balance
                })
                total_equity += balance
        
        # Calculate totals and check balance
        total_liabilities_equity = total_liabilities + total_equity
        difference = abs(total_assets - total_liabilities_equity)
        is_balanced = difference < Decimal('0.01')
        
        # Calculate key ratios
        current_ratio = Decimal('0.00')
        debt_to_equity = Decimal('0.00')
        equity_ratio = Decimal('0.00')
        
        if total_assets > 0:
            equity_ratio = (total_equity / total_assets * 100)
        
        if total_equity > 0:
            debt_to_equity = (total_liabilities / total_equity)
        
        context = {
            'asset_items': asset_items,
            'liability_items': liability_items,
            'equity_items': equity_items,
            'total_assets': total_assets,
            'total_liabilities': total_liabilities,
            'total_equity': total_equity,
            'total_liabilities_equity': total_liabilities_equity,
            'difference': difference,
            'is_balanced': is_balanced,
            'balance_status': 'balanced' if is_balanced else 'unbalanced',
            'equity_ratio': equity_ratio,
            'debt_to_equity': debt_to_equity,
            'as_of_date': as_of_date,
            'today': date.today(),
            'report_title': 'Balance Sheet',
        }
        
        return render(request, 'reports/financial/balance_sheet.html', context)
        
    except ImportError:
        messages.error(request, 'Accounting system not configured.')
        return redirect('reports:financial_reports_index')
    except Exception as e:
        messages.error(request, f'Error generating balance sheet: {str(e)}')
        return redirect('reports:financial_reports_index')


def _export_balance_sheet_excel(as_of_date):
    """Export balance sheet to Excel/CSV."""
    import csv
    from django.http import HttpResponse
    from accounting.models import Account
    from accounting.services.accounting_service import AccountingService
    from decimal import Decimal
    
    accounting_service = AccountingService()
    
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = f'attachment; filename="balance_sheet_{as_of_date}.csv"'
    
    writer = csv.writer(response)
    writer.writerow(['Balance Sheet'])
    writer.writerow([f'As of: {as_of_date}'])
    writer.writerow([])
    
    # Assets
    writer.writerow(['ASSETS'])
    writer.writerow(['Code', 'Account Name', 'Amount (KES)'])
    
    asset_accounts = Account.objects.filter(account_type='asset', is_active=True).order_by('code')
    total_assets = Decimal('0.00')
    
    for account in asset_accounts:
        balance = accounting_service.calculate_account_balance(account, as_of_date, None)
        if balance != Decimal('0.00'):
            writer.writerow([account.code, account.name, f"{balance:.2f}"])
            total_assets += balance
    
    writer.writerow(['', 'TOTAL ASSETS', f"{total_assets:.2f}"])
    writer.writerow([])
    
    # Liabilities
    writer.writerow(['LIABILITIES'])
    writer.writerow(['Code', 'Account Name', 'Amount (KES)'])
    
    liability_accounts = Account.objects.filter(account_type='liability', is_active=True).order_by('code')
    total_liabilities = Decimal('0.00')
    
    for account in liability_accounts:
        balance = accounting_service.calculate_account_balance(account, as_of_date, None)
        if balance != Decimal('0.00'):
            writer.writerow([account.code, account.name, f"{balance:.2f}"])
            total_liabilities += balance
    
    writer.writerow(['', 'TOTAL LIABILITIES', f"{total_liabilities:.2f}"])
    writer.writerow([])
    
    # Equity
    writer.writerow(['EQUITY'])
    writer.writerow(['Code', 'Account Name', 'Amount (KES)'])
    
    equity_accounts = Account.objects.filter(account_type='equity', is_active=True).order_by('code')
    total_equity = Decimal('0.00')
    
    for account in equity_accounts:
        balance = accounting_service.calculate_account_balance(account, as_of_date, None)
        if balance != Decimal('0.00'):
            writer.writerow([account.code, account.name, f"{balance:.2f}"])
            total_equity += balance
    
    writer.writerow(['', 'TOTAL EQUITY', f"{total_equity:.2f}"])
    writer.writerow([])
    writer.writerow(['', 'TOTAL LIABILITIES & EQUITY', f"{total_liabilities + total_equity:.2f}"])
    
    return response


@login_required
@staff_required
def cash_flow_statement(request):
    """Display Cash Flow Statement with date range filtering."""
    from decimal import Decimal
    from datetime import timedelta
    
    try:
        from accounting.models import Account, GeneralLedger
        from accounting.services.accounting_service import AccountingService
        
        accounting_service = AccountingService()
        
        # Get date range
        end_date = date.today()
        start_date = end_date.replace(day=1)  # First day of current month
        
        if request.GET.get('start_date'):
            try:
                start_date = datetime.strptime(request.GET.get('start_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        if request.GET.get('end_date'):
            try:
                end_date = datetime.strptime(request.GET.get('end_date'), '%Y-%m-%d').date()
            except ValueError:
                pass
        
        # Handle export requests
        export_format = request.GET.get('format')
        if export_format == 'pdf':
            return cash_flow_statement_pdf(request)
        elif export_format == 'excel':
            return _export_cash_flow_excel(start_date, end_date)
        
        # Start with net income from income statement
        total_income = Decimal('0.00')
        total_expenses = Decimal('0.00')
        
        income_accounts = Account.objects.filter(account_type='income', is_active=True)
        for account in income_accounts:
            balance = accounting_service.calculate_account_balance(account, end_date, None)
            opening = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
            total_income += (balance - opening)
        
        expense_accounts = Account.objects.filter(account_type='expense', is_active=True)
        for account in expense_accounts:
            balance = accounting_service.calculate_account_balance(account, end_date, None)
            opening = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
            total_expenses += (balance - opening)
        
        net_income = total_income - total_expenses
        
        # Operating activities adjustments
        operating_adjustments = []
        
        # Add back depreciation (non-cash expense)
        depreciation_accounts = Account.objects.filter(
            account_type='expense',
            name__icontains='depreciation',
            is_active=True
        )
        total_depreciation = Decimal('0.00')
        for account in depreciation_accounts:
            balance = accounting_service.calculate_account_balance(account, end_date, None)
            opening = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
            period_depreciation = balance - opening
            if period_depreciation > 0:
                operating_adjustments.append({
                    'description': f'Add: {account.name}',
                    'amount': period_depreciation
                })
                total_depreciation += period_depreciation
        
        # Changes in current assets/liabilities
        # (Simplified - would need more detailed tracking in production)
        
        net_cash_from_operations = net_income + total_depreciation
        
        # Investing activities (changes in fixed assets)
        investing_activities = []
        fixed_asset_accounts = Account.objects.filter(
            account_type='asset',
            subtype='fixed_asset',
            is_active=True
        ).exclude(name__icontains='accumulated depreciation')
        
        net_investing = Decimal('0.00')
        for account in fixed_asset_accounts:
            balance = accounting_service.calculate_account_balance(account, end_date, None)
            opening = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
            change = balance - opening
            if change != Decimal('0.00'):
                investing_activities.append({
                    'description': f'Purchase of {account.name}' if change > 0 else f'Sale of {account.name}',
                    'amount': -change  # Negative for purchases, positive for sales
                })
                net_investing += -change
        
        # Financing activities (changes in loans and equity)
        financing_activities = []
        loan_accounts = Account.objects.filter(
            account_type='liability',
            subtype='borrowings',
            is_active=True
        )
        
        net_financing = Decimal('0.00')
        for account in loan_accounts:
            balance = accounting_service.calculate_account_balance(account, end_date, None)
            opening = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
            change = balance - opening
            if change != Decimal('0.00'):
                financing_activities.append({
                    'description': f'Proceeds from {account.name}' if change > 0 else f'Repayment of {account.name}',
                    'amount': change
                })
                net_financing += change
        
        # Net change in cash
        net_cash_change = net_cash_from_operations + net_investing + net_financing
        
        # Cash beginning and ending balances
        cash_accounts = Account.objects.filter(
            Q(name__icontains='cash') | Q(name__icontains='bank') | Q(name__icontains='mpesa'),
            account_type='asset',
            is_active=True
        )
        
        cash_beginning = Decimal('0.00')
        cash_ending = Decimal('0.00')
        
        for account in cash_accounts:
            opening = accounting_service.calculate_account_balance(account, start_date - timedelta(days=1), None) if start_date > date(2020, 1, 1) else Decimal('0.00')
            ending = accounting_service.calculate_account_balance(account, end_date, None)
            cash_beginning += opening
            cash_ending += ending
        
        context = {
            'net_income': net_income,
            'operating_adjustments': operating_adjustments,
            'net_cash_from_operations': net_cash_from_operations,
            'investing_activities': investing_activities,
            'net_investing': net_investing,
            'financing_activities': financing_activities,
            'net_financing': net_financing,
            'net_cash_change': net_cash_change,
            'cash_beginning': cash_beginning,
            'cash_ending': cash_ending,
            'start_date': start_date,
            'end_date': end_date,
            'today': date.today(),
            'report_title': 'Cash Flow Statement',
        }
        
        return render(request, 'reports/financial/cash_flow_statement.html', context)
        
    except ImportError:
        messages.error(request, 'Accounting system not configured.')
        return redirect('reports:financial_reports_index')
    except Exception as e:
        messages.error(request, f'Error generating cash flow statement: {str(e)}')
        return redirect('reports:financial_reports_index')


def _export_cash_flow_excel(start_date, end_date):
    """Export cash flow statement to Excel/CSV."""
    import csv
    from django.http import HttpResponse
    
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = f'attachment; filename="cash_flow_{start_date}_to_{end_date}.csv"'
    
    writer = csv.writer(response)
    writer.writerow(['Cash Flow Statement'])
    writer.writerow([f'Period: {start_date} to {end_date}'])
    writer.writerow([])
    writer.writerow(['Section', 'Description', 'Amount (KES)'])
    
    # Note: Full implementation would mirror the cash_flow_statement view logic
    writer.writerow(['Operating Activities', 'Net Income', '0.00'])
    writer.writerow([])
    writer.writerow(['NET CASH FROM OPERATIONS', '', '0.00'])
    
    return response


@login_required
@staff_required
def cash_flow_statement_pdf(request):
    """Export Cash Flow Statement as PDF - placeholder."""
    messages.info(request, 'Cash Flow PDF generation coming soon!')
    return redirect('reports:cash_flow_statement')
