"""
Accounting PDF Report Generator
================================
Generates professional financial-statement PDFs for
Haven Grazuri Credit Solutions Ltd.

Reports match the exact format expected by an economic analyst / external auditor:
  1. Chart of Accounts
  2. Trial Balance  (GL Code | Description | Opening Dr/Cr | Activity Dr/Cr | Closing Dr/Cr)
  3. Income Statement / Comprehensive Income
     (Description | Notes | Period | Prior Period | Variance KES | Variance %)
  4. Statement of Financial Position  (side-by-side Assets vs Liabilities & Equity)
  5. Account Ledger

All reports include a three-panel bottom dashboard:
  Left  – System-Based Observations
  Middle – Conclusion paragraph
  Right  – Summary KES table
"""

from io import BytesIO
from datetime import date, datetime
from decimal import Decimal
from typing import Optional, List, Dict, Any

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch, mm
from reportlab.lib.enums import TA_CENTER, TA_RIGHT, TA_LEFT, TA_JUSTIFY
from reportlab.platypus import (
    SimpleDocTemplate, Table, TableStyle, Paragraph,
    Spacer, HRFlowable, KeepTogether,
)
from reportlab.pdfgen import canvas

# ── Colour palette ──────────────────────────────────────────────────────────
C_NAVY        = colors.HexColor('#0A2540')   # dark navy – header rows, titles
C_GREEN       = colors.HexColor('#1B7340')   # brand green – section headers, highlights
C_NAVY_LIGHT  = colors.HexColor('#1e3a5f')
C_GREEN_LIGHT = colors.HexColor('#d4edda')   # positive / profit highlight (light)
C_RED_LIGHT   = colors.HexColor('#fde8e8')   # negative / loss highlight
C_BLUE_LIGHT  = colors.HexColor('#e8f4fd')   # observations box bg
C_ROW_ALT     = colors.HexColor('#f7f9fc')
C_GREY_LINE   = colors.HexColor('#d0d7de')
C_TOTAL_BG    = colors.HexColor('#eef2f7')
C_WHITE       = colors.white
C_TEXT        = colors.HexColor('#1a1a2e')
C_SUBTEXT     = colors.HexColor('#5c6370')
C_PROFIT_FG   = colors.HexColor('#155724')
C_LOSS_FG     = colors.HexColor('#721c24')



class AccountingPDFGenerator:
    """Professional PDF generator for Haven Grazuri accounting reports."""

    COMPANY_NAME    = "Haven Grazuri Credit Solutions Ltd"
    COMPANY_TAGLINE = "Your Growth, Our Priority"
    SYSTEM_NAME     = "FINANCE SYSTEM (FINX)"
    PAGE_W, PAGE_H  = A4

    def __init__(self, logo_path: Optional[str] = None):
        self.logo_path = logo_path
        self.styles    = getSampleStyleSheet()
        self._setup_styles()

    # ── Style registry ──────────────────────────────────────────────────────

    def _setup_styles(self):
        add = self.styles.add
        add(ParagraphStyle('CoName', parent=self.styles['Normal'],
                           fontSize=14, textColor=C_GREEN, alignment=TA_LEFT,
                           fontName='Helvetica-Bold', spaceAfter=1))
        add(ParagraphStyle('CoTag', parent=self.styles['Normal'],
                           fontSize=8, textColor=C_SUBTEXT, alignment=TA_LEFT,
                           fontName='Helvetica-Oblique', spaceAfter=2))
        add(ParagraphStyle('RptTitle', parent=self.styles['Normal'],
                           fontSize=14, textColor=C_GREEN, alignment=TA_CENTER,
                           fontName='Helvetica-Bold', spaceAfter=2))
        add(ParagraphStyle('RptDate', parent=self.styles['Normal'],
                           fontSize=11, textColor=C_NAVY, alignment=TA_CENTER,
                           fontName='Helvetica-Bold', spaceAfter=6))
        add(ParagraphStyle('MetaRight', parent=self.styles['Normal'],
                           fontSize=7, textColor=C_SUBTEXT, alignment=TA_RIGHT))
        add(ParagraphStyle('SecHdr', parent=self.styles['Normal'],
                           fontSize=9, textColor=C_WHITE, fontName='Helvetica-Bold'))
        add(ParagraphStyle('SecHdrR', parent=self.styles['Normal'],
                           fontSize=9, textColor=C_WHITE, fontName='Helvetica-Bold',
                           alignment=TA_RIGHT))
        add(ParagraphStyle('Note', parent=self.styles['Normal'],
                           fontSize=7, textColor=C_SUBTEXT, alignment=TA_LEFT,
                           spaceAfter=3))
        add(ParagraphStyle('FootNote', parent=self.styles['Normal'],
                           fontSize=7, textColor=C_SUBTEXT, alignment=TA_CENTER,
                           fontName='Helvetica-Oblique'))
        add(ParagraphStyle('BoxTitle', parent=self.styles['Normal'],
                           fontSize=8, textColor=C_WHITE, fontName='Helvetica-Bold',
                           alignment=TA_CENTER))
        add(ParagraphStyle('BoxBody', parent=self.styles['Normal'],
                           fontSize=7.5, textColor=C_TEXT, leading=11))
        add(ParagraphStyle('BoxBodySmall', parent=self.styles['Normal'],
                           fontSize=7, textColor=C_TEXT, leading=10))
        add(ParagraphStyle('Italic7', parent=self.styles['Normal'],
                           fontSize=7, textColor=C_SUBTEXT,
                           fontName='Helvetica-Oblique', alignment=TA_CENTER))

    # ── Document factory ────────────────────────────────────────────────────

    def _doc(self, buffer: BytesIO, landscape_mode: bool = False) -> SimpleDocTemplate:
        ps = landscape(A4) if landscape_mode else A4
        return SimpleDocTemplate(
            buffer, pagesize=ps,
            topMargin=22*mm, bottomMargin=20*mm,
            leftMargin=13*mm, rightMargin=13*mm,
        )

    # ── Page callback (header + footer on every page) ──────────────────────

    def _make_header_footer(self, run_date: str, run_time: str):
        """Returns a closure suitable for onFirstPage / onLaterPages."""
        gen = self

        def _draw(canv: canvas.Canvas, doc):
            canv.saveState()
            W  = doc.width + doc.leftMargin + doc.rightMargin
            top = doc.bottomMargin + doc.height

            # Navy header stripe
            canv.setFillColor(C_NAVY)
            canv.rect(0, top + 3*mm, W, 10*mm, fill=1, stroke=0)

            # Company name (left) + tagline (left, smaller)
            canv.setFillColor(C_WHITE)
            canv.setFont('Helvetica-Bold', 9)
            canv.drawString(doc.leftMargin, top + 9.5*mm, gen.COMPANY_NAME)
            canv.setFont('Helvetica-Oblique', 6.5)
            canv.drawString(doc.leftMargin, top + 5.5*mm, gen.COMPANY_TAGLINE)

            # Run date/time (right)
            canv.setFont('Helvetica', 6.5)
            canv.drawRightString(W - doc.rightMargin, top + 9.5*mm,
                                 f'Run Date : {run_date}')
            canv.drawRightString(W - doc.rightMargin, top + 5.5*mm,
                                 f'Run Time : {run_time}')

            # Footer separator line
            canv.setStrokeColor(C_GREY_LINE)
            canv.line(doc.leftMargin, 10*mm, W - doc.rightMargin, 10*mm)
            canv.setFillColor(C_SUBTEXT)
            canv.setFont('Helvetica', 6)
            canv.drawString(doc.leftMargin, 6.5*mm, gen.SYSTEM_NAME)
            canv.drawCentredString(W/2, 6.5*mm,
                                   'CONFIDENTIAL — For Internal Use Only')
            canv.drawRightString(W - doc.rightMargin, 6.5*mm,
                                 f'Page {canv.getPageNumber()}')
            canv.restoreState()

        return _draw

    # ── Static helpers ──────────────────────────────────────────────────────

    @staticmethod
    def _fmt(amount: Any, parens: bool = True) -> str:
        """Format Decimal / number as comma-thousand with 2dp.
           Negative values shown in parentheses by default."""
        if amount is None:
            return '-'
        try:
            d = Decimal(str(amount))
        except Exception:
            return str(amount)
        if d == 0:
            return '-'
        abs_str = f"{abs(d):,.2f}"
        if d < 0 and parens:
            return f"({abs_str})"
        return abs_str

    @staticmethod
    def _pct(part: Any, total: Any) -> str:
        try:
            p, t = Decimal(str(part)), Decimal(str(total))
            if t == 0:
                return '-'
            return f"{(p / t * 100):.1f}%"
        except Exception:
            return '-'

    @staticmethod
    def _var_pct(current: Any, prior: Any) -> str:
        try:
            c, p = Decimal(str(current)), Decimal(str(prior))
            if p == 0:
                return '-'
            pct = ((c - p) / abs(p)) * 100
            sign = '+' if pct >= 0 else ''
            return f"{sign}{pct:.1f}%"
        except Exception:
            return '-'


    # ── Reusable table builder ──────────────────────────────────────────────

    def _std_table(self, data: list, col_widths: list,
                   hdr_rows: int = 1, accent: Any = C_NAVY) -> Table:
        t = Table(data, colWidths=col_widths, repeatRows=hdr_rows)
        base = [
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica'),
            ('FONTSIZE',      (0, 0), (-1, -1), 7.5),
            ('TOPPADDING',    (0, 0), (-1, -1), 3),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
            ('LEFTPADDING',   (0, 0), (-1, -1), 5),
            ('RIGHTPADDING',  (0, 0), (-1, -1), 5),
            ('ROWBACKGROUNDS', (0, hdr_rows), (-1, -1), [C_WHITE, C_ROW_ALT]),
            ('LINEBELOW',     (0, 0), (-1, -1), 0.25, C_GREY_LINE),
            ('VALIGN',        (0, 0), (-1, -1), 'MIDDLE'),
        ]
        if hdr_rows:
            base += [
                ('BACKGROUND',  (0, 0), (-1, hdr_rows - 1), accent),
                ('TEXTCOLOR',   (0, 0), (-1, hdr_rows - 1), C_WHITE),
                ('FONTNAME',    (0, 0), (-1, hdr_rows - 1), 'Helvetica-Bold'),
                ('FONTSIZE',    (0, 0), (-1, hdr_rows - 1), 7.5),
                ('LINEBELOW',   (0, hdr_rows - 1), (-1, hdr_rows - 1), 1, accent),
            ]
        t.setStyle(TableStyle(base))
        return t

    def _section_row(self, label: str, colour: Any,
                     n_cols: int = 6, right_label: str = '') -> Table:
        """Full-width coloured section header row."""
        row = [[Paragraph(label, self.styles['SecHdr'])] +
               [''] * (n_cols - 2) +
               [Paragraph(right_label, self.styles['SecHdrR'])]]
        t = Table(row, colWidths=['*'] * n_cols)
        t.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), colour),
            ('SPAN',          (0, 0), (n_cols - 2, 0)),
            ('TOPPADDING',    (0, 0), (-1, -1), 5),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
            ('LEFTPADDING',   (0, 0), (0, 0),   8),
        ]))
        return t

    def _totals_row(self, cells: list, col_widths: list,
                    bg: Any = C_TOTAL_BG, fg: Any = C_TEXT) -> Table:
        t = Table([cells], colWidths=col_widths)
        t.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), bg),
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE',      (0, 0), (-1, -1), 8),
            ('TEXTCOLOR',     (0, 0), (-1, -1), fg),
            ('TOPPADDING',    (0, 0), (-1, -1), 5),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
            ('LEFTPADDING',   (0, 0), (-1, -1), 5),
            ('RIGHTPADDING',  (0, 0), (-1, -1), 5),
            ('LINEABOVE',     (0, 0), (-1, -1), 1, C_NAVY),
        ]))
        return t

    # ── Three-panel bottom dashboard ────────────────────────────────────────

    def _bottom_dashboard(self,
                          observations: List[str],
                          conclusion: str,
                          summary_rows: List[List[str]],
                          summary_highlights: List[int] = None,
                          avail_width: float = 181*mm) -> Table:
        """
        Returns a 3-cell Table:
          [0] Observations (blue bg, bullet list)
          [1] Conclusion paragraph (white bg)
          [2] Summary KES table (white bg)
        """
        col_w = avail_width / 3

        # ── Left: observations ──
        obs_items = []
        for obs in observations:
            obs_items.append(
                Paragraph(f'<bullet color="#1B5E20">✔</bullet> {obs}',
                          self.styles['BoxBodySmall'])
            )
        obs_cell = [
            Table([[Paragraph('SYSTEM BASED OBSERVATIONS',
                              self.styles['BoxTitle'])]],
                  colWidths=[col_w - 4*mm]),
            Spacer(1, 2*mm),
            *obs_items,
        ]

        # ── Middle: conclusion ──
        conc_cell = [
            Table([[Paragraph('CONCLUSION', self.styles['BoxTitle'])]],
                  colWidths=[col_w - 4*mm]),
            Spacer(1, 2*mm),
            Paragraph(conclusion, self.styles['BoxBody']),
        ]

        # ── Right: summary table ──
        sum_data = []
        for row in summary_rows:
            sum_data.append([
                Paragraph(row[0], self.styles['BoxBodySmall']),
                Paragraph(row[1], ParagraphStyle('SumVal',
                          parent=self.styles['BoxBodySmall'],
                          alignment=TA_RIGHT)),
            ])
        sum_tbl = Table(sum_data, colWidths=[col_w * 0.55, col_w * 0.45 - 4*mm])
        sum_styles = [
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica'),
            ('FONTSIZE',      (0, 0), (-1, -1), 7),
            ('TOPPADDING',    (0, 0), (-1, -1), 2),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
            ('LINEBELOW',     (0, 0), (-1, -2), 0.2, C_GREY_LINE),
        ]
        if summary_highlights:
            for idx in summary_highlights:
                sum_styles += [
                    ('BACKGROUND', (0, idx), (-1, idx), C_GREEN_LIGHT),
                    ('FONTNAME',   (0, idx), (-1, idx), 'Helvetica-Bold'),
                    ('TEXTCOLOR',  (0, idx), (-1, idx), C_PROFIT_FG),
                ]
        sum_tbl.setStyle(TableStyle(sum_styles))

        sum_cell = [
            Table([[Paragraph('SUMMARY (KES)', self.styles['BoxTitle'])]],
                  colWidths=[col_w - 4*mm]),
            Spacer(1, 2*mm),
            sum_tbl,
        ]

        def _wrap(items, bg, title_bg=C_NAVY):
            inner = Table(
                [[item] for item in items],
                colWidths=[col_w - 4*mm]
            )
            inner.setStyle(TableStyle([
                ('BACKGROUND', (0, 0), (-1, 0),  title_bg),
                ('BACKGROUND', (0, 1), (-1, -1), bg),
                ('TOPPADDING',    (0, 0), (-1, -1), 3),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
                ('LEFTPADDING',   (0, 0), (-1, -1), 4),
                ('RIGHTPADDING',  (0, 0), (-1, -1), 4),
                ('BOX', (0, 0), (-1, -1), 0.5, C_GREY_LINE),
            ]))
            return inner

        obs_wrapped  = _wrap(obs_cell,  C_BLUE_LIGHT)
        conc_wrapped = _wrap(conc_cell, C_WHITE)
        sum_wrapped  = _wrap(sum_cell,  C_WHITE)

        dashboard = Table(
            [[obs_wrapped, conc_wrapped, sum_wrapped]],
            colWidths=[col_w, col_w, col_w]
        )
        dashboard.setStyle(TableStyle([
            ('VALIGN',       (0, 0), (-1, -1), 'TOP'),
            ('LEFTPADDING',  (0, 0), (-1, -1), 2),
            ('RIGHTPADDING', (0, 0), (-1, -1), 2),
        ]))
        return dashboard

    # ── Sign-off footer ─────────────────────────────────────────────────────

    def _signoff_row(self, avail_width: float = 181*mm) -> Table:
        cw = avail_width / 3
        data = [[
            Paragraph('PREPARED BY: ________________________',
                      self.styles['Note']),
            Paragraph('REVIEWED BY: ________________________',
                      ParagraphStyle('SF', parent=self.styles['Note'],
                                     alignment=TA_CENTER)),
            Paragraph('APPROVED BY: ________________________',
                      ParagraphStyle('SF', parent=self.styles['Note'],
                                     alignment=TA_RIGHT)),
        ]]
        t = Table(data, colWidths=[cw, cw, cw])
        t.setStyle(TableStyle([
            ('TOPPADDING', (0, 0), (-1, -1), 4),
            ('LINEABOVE',  (0, 0), (-1, -1), 0.5, C_GREY_LINE),
        ]))
        return t

    # ── Report header block (title, date, meta) ─────────────────────────────

    def _report_header_block(self, title: str, date_line: str,
                             run_date: str = '', run_time: str = '',
                             avail_width: float = 181*mm) -> List:
        """Returns flowable list: title, date, HR line."""
        elements = [
            Spacer(1, 2*mm),
            Paragraph(title, self.styles['RptTitle']),
            Paragraph(date_line, self.styles['RptDate']),
            HRFlowable(width='100%', thickness=1.5, color=C_NAVY),
            Spacer(1, 3*mm),
        ]
        return elements


    # ══════════════════════════════════════════════════════════════════════════
    # 1. CHART OF ACCOUNTS
    # ══════════════════════════════════════════════════════════════════════════

    def generate_chart_of_accounts_pdf(
        self,
        accounts_by_type: Dict[str, List[Dict]],
        as_of_date: date,
        include_balances: bool = True,
    ) -> BytesIO:
        buffer  = BytesIO()
        now     = datetime.now()
        rd, rt  = now.strftime('%d-%b-%Y').upper(), now.strftime('%I:%M:%S %p')
        doc     = self._doc(buffer)
        cb      = self._make_header_footer(rd, rt)
        W       = 181*mm
        elems   = []

        elems += self._report_header_block(
            'CHART OF ACCOUNTS',
            f'AS AT {as_of_date.strftime("%d %B %Y").upper()}',
            rd, rt
        )

        type_cfg = [
            ('asset',     'ASSETS',      C_GREEN),
            ('liability', 'LIABILITIES', C_NAVY),
            ('equity',    'EQUITY',      colors.HexColor('#6c3483')),
            ('income',    'INCOME',      colors.HexColor('#117a65')),
            ('expense',   'EXPENSES',    colors.HexColor('#922b21')),
        ]

        for acc_type, label, colour in type_cfg:
            accounts = accounts_by_type.get(acc_type, [])
            if not accounts:
                continue

            if include_balances:
                hdr = [['GL CODE', 'ACCOUNT NAME', 'SUBTYPE', 'BALANCE (KES)']]
                cw  = [22*mm, 98*mm, 35*mm, 26*mm]
            else:
                hdr = [['GL CODE', 'ACCOUNT NAME', 'SUBTYPE']]
                cw  = [22*mm, 110*mm, 49*mm]

            rows = []
            section_total = Decimal('0.00')
            for acc in accounts:
                bal = acc.get('balance', Decimal('0.00'))
                section_total += abs(bal)
                row = [
                    acc['code'],
                    acc['name'],
                    (acc.get('subtype') or '').replace('_', ' ').title(),
                ]
                if include_balances:
                    row.append(self._fmt(abs(bal)))
                rows.append(row)

            if include_balances:
                rows.append(['', f'SUBTOTAL – {label}', '', self._fmt(section_total)])

            elems.append(self._section_row(
                f'{label}  ({len(accounts)} accounts)', colour,
                n_cols=len(hdr[0])
            ))
            tbl = self._std_table(hdr + rows, cw, hdr_rows=1, accent=colour)
            tbl.setStyle(TableStyle([
                ('ALIGN',    (-1, 1), (-1, -1), 'RIGHT'),
                ('FONTNAME', (0, -1), (-1, -1), 'Helvetica-Bold'),
                ('BACKGROUND', (0, -1), (-1, -1), C_TOTAL_BG),
                ('LINEABOVE', (0, -1), (-1, -1), 1, colour),
            ]))
            elems += [tbl, Spacer(1, 4*mm)]

        elems.append(Paragraph(
            'Note: Balances are as at the report date from the General Ledger. '
            'System Account markers indicate accounts automatically managed by FINX.',
            self.styles['Note']
        ))

        doc.build(elems, onFirstPage=cb, onLaterPages=cb)
        buffer.seek(0)
        return buffer

    # ══════════════════════════════════════════════════════════════════════════
    # 2. TRIAL BALANCE  (8-column professional format)
    # ══════════════════════════════════════════════════════════════════════════

    def generate_trial_balance_pdf(
        self,
        trial_balance_data: Dict,
        as_of_date: date,
    ) -> BytesIO:
        """
        Columns:
          GL CODE | DESCRIPTION | Opening Dr | Opening Cr | Activity Dr | Activity Cr | Closing Dr | Closing Cr
        Grouped into ASSETS, LIABILITIES, EQUITY with section sub-totals.
        Bottom dashboard: System Observations | Conclusion | Summary KES.
        """
        buffer = BytesIO()
        now    = datetime.now()
        rd, rt = now.strftime('%d-%b-%Y').upper(), now.strftime('%I:%M:%S %p')

        # Use landscape for the 8-column layout
        doc = self._doc(buffer, landscape_mode=True)
        cb  = self._make_header_footer(rd, rt)
        W   = 267*mm   # landscape A4 usable width ≈ 267mm
        elems = []

        accounts = trial_balance_data.get('accounts', [])
        totals   = trial_balance_data.get('totals', {})
        td       = totals.get('total_debits',  Decimal('0.00'))
        tc       = totals.get('total_credits', Decimal('0.00'))
        balanced = totals.get('balanced', False)

        # ── Report header ────────────────────────────────────────────
        elems += self._report_header_block(
            'TRIAL BALANCE REPORT',
            f'AS AT {as_of_date.strftime("%d %B %Y").upper()}',
            rd, rt
        )

        # Balance indicator banner
        ind_bg = C_GREEN_LIGHT if balanced else C_RED_LIGHT
        ind_fg = C_PROFIT_FG if balanced else C_LOSS_FG
        msg    = ('Total Debits equal Total Credits. The books are mathematically accurate.'
                  if balanced else
                  f'OUT OF BALANCE — Difference: KES {self._fmt(abs(td - tc))}. '
                  'Please review journal entries.')
        ind_t = Table([[Paragraph(msg, ParagraphStyle(
            'Ind', parent=self.styles['Normal'],
            fontSize=8, textColor=ind_fg, fontName='Helvetica-Bold'))
        ]], colWidths=[W])
        ind_t.setStyle(TableStyle([
            ('BACKGROUND', (0, 0), (-1, -1), ind_bg),
            ('TOPPADDING', (0, 0), (-1, -1), 5),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
            ('LEFTPADDING', (0, 0), (-1, -1), 8),
            ('BOX', (0, 0), (-1, -1), 1, ind_fg),
        ]))
        elems += [ind_t, Spacer(1, 4*mm)]

        # ── Column headers (2-row merged header) ────────────────────
        # Row 1: GL CODE | DESCRIPTION | ←OPENING BALANCE→ | ←PERIOD ACTIVITY→ | ←CLOSING BALANCE→
        # Row 2: (blank) | (blank) | DEBIT | CREDIT | DEBIT | CREDIT | DEBIT | CREDIT
        cw = [18*mm, 72*mm, 22*mm, 22*mm, 22*mm, 22*mm, 22*mm, 22*mm]
        hdr1 = [
            Paragraph('GL CODE',     self.styles['SecHdr']),
            Paragraph('DESCRIPTION', self.styles['SecHdr']),
            Paragraph('OPENING BALANCE', self.styles['SecHdr']),
            '', '',
            Paragraph('PERIOD ACTIVITY', self.styles['SecHdr']),
            '', '',
        ]
        hdr1_fixed = [
            Paragraph('GL CODE',     self.styles['SecHdr']),
            Paragraph('DESCRIPTION', self.styles['SecHdr']),
            Paragraph('OPENING BALANCE', self.styles['SecHdr']),
            '', '',
            Paragraph('PERIOD ACTIVITY', self.styles['SecHdr']),
            '',
            Paragraph('CLOSING BALANCE', self.styles['SecHdr']),
        ]
        hdr2 = [
            '', '',
            Paragraph('DEBIT (KES)',  self.styles['SecHdr']),
            Paragraph('CREDIT (KES)', self.styles['SecHdr']),
            Paragraph('DEBIT (KES)',  self.styles['SecHdr']),
            Paragraph('CREDIT (KES)', self.styles['SecHdr']),
            Paragraph('DEBIT (KES)',  self.styles['SecHdr']),
            Paragraph('CREDIT (KES)', self.styles['SecHdr']),
        ]

        hdr_data = [hdr1_fixed, hdr2]
        hdr_tbl  = Table(hdr_data, colWidths=cw)
        hdr_tbl.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), C_NAVY),
            ('TEXTCOLOR',     (0, 0), (-1, -1), C_WHITE),
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE',      (0, 0), (-1, -1), 7.5),
            ('TOPPADDING',    (0, 0), (-1, -1), 3),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
            ('LEFTPADDING',   (0, 0), (-1, -1), 4),
            # Span "OPENING BALANCE" across cols 2-3
            ('SPAN', (2, 0), (3, 0)),
            # Span "PERIOD ACTIVITY" across cols 4-5
            ('SPAN', (4, 0), (5, 0)),
            # Span "CLOSING BALANCE" across cols 6-7
            ('SPAN', (6, 0), (7, 0)),
            # Span GL CODE and DESCRIPTION rows
            ('SPAN', (0, 0), (0, 1)),
            ('SPAN', (1, 0), (1, 1)),
            ('ALIGN', (2, 0), (-1, -1), 'CENTER'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('LINEBELOW', (0, 1), (-1, 1), 1.5, C_GREEN),
            ('GRID', (0, 0), (-1, -1), 0.3, colors.HexColor('#FFFFFF')),
        ]))
        elems.append(hdr_tbl)


        # ── Account rows grouped by type ─────────────────────────────
        type_order  = ['asset', 'liability', 'equity', 'income', 'expense']
        type_labels = {
            'asset': 'ASSETS', 'liability': 'LIABILITIES',
            'equity': 'EQUITY', 'income': 'INCOME', 'expense': 'EXPENSES',
        }
        type_colours = {
            'asset': C_GREEN, 'liability': C_NAVY,
            'equity': colors.HexColor('#6c3483'),
            'income': colors.HexColor('#117a65'),
            'expense': colors.HexColor('#922b21'),
        }

        by_type: Dict[str, list] = {t: [] for t in type_order}
        for acc in accounts:
            t = acc.get('type', acc.get('account_type', ''))
            if t in by_type:
                by_type[t].append(acc)

        # Also pull ALL active accounts so zero-balance ones appear in the PDF
        # (same logic as the HTML view — a full CoA is always visible to auditors)
        try:
            from accounting.models import Account as AccountModel
            all_active_codes = {
                a.code: {'code': a.code, 'name': a.name,
                         'type': a.account_type,
                         'opening_debit': Decimal('0.00'), 'opening_credit': Decimal('0.00'),
                         'activity_debit': Decimal('0.00'), 'activity_credit': Decimal('0.00'),
                         'closing_debit': Decimal('0.00'), 'closing_credit': Decimal('0.00')}
                for a in AccountModel.objects.filter(is_active=True).only('code', 'name', 'account_type')
            }
            # Merge: service data wins; add zero-rows for missing accounts
            for acc_data in accounts:
                all_active_codes[acc_data['code']] = acc_data
            # Rebuild by_type from the merged set
            by_type = {t: [] for t in type_order}
            for acc_data in sorted(all_active_codes.values(), key=lambda x: x['code']):
                t = acc_data.get('type', acc_data.get('account_type', ''))
                if t in by_type:
                    by_type[t].append(acc_data)
        except Exception:
            pass  # Fall back to service data only if DB unavailable

        grand_op_d = grand_op_c = Decimal('0.00')
        grand_ac_d = grand_ac_c = Decimal('0.00')
        grand_cl_d = grand_cl_c = Decimal('0.00')

        # Track per-category closing totals for the summary panel
        cat_cl: Dict[str, Decimal] = {t: Decimal('0.00') for t in type_order}

        for acc_type in type_order:
            accs = by_type[acc_type]
            if not accs:
                continue
            colour = type_colours[acc_type]
            label  = type_labels[acc_type]

            # Section label row
            sec = Table(
                [[Paragraph(label, self.styles['SecHdr']), '', '', '', '', '', '', '']],
                colWidths=cw
            )
            sec.setStyle(TableStyle([
                ('BACKGROUND',    (0, 0), (-1, -1), colour),
                ('SPAN',          (0, 0), (-1, 0)),
                ('TOPPADDING',    (0, 0), (-1, -1), 4),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
                ('LEFTPADDING',   (0, 0), (0, 0),   8),
            ]))
            elems.append(sec)

            rows = []
            sub_op_d = sub_op_c = Decimal('0.00')
            sub_ac_d = sub_ac_c = Decimal('0.00')
            sub_cl_d = sub_cl_c = Decimal('0.00')

            for acc in accs:
                op_d = Decimal(str(acc.get('opening_debit',  0) or 0))
                op_c = Decimal(str(acc.get('opening_credit', 0) or 0))
                ac_d = Decimal(str(acc.get('activity_debit', acc.get('debit_balance',  0)) or 0))
                ac_c = Decimal(str(acc.get('activity_credit', acc.get('credit_balance', 0)) or 0))
                cl_d = Decimal(str(acc.get('closing_debit',  0) or 0))
                cl_c = Decimal(str(acc.get('closing_credit', 0) or 0))

                # If only debit/credit balance provided (legacy), put in closing
                if cl_d == 0 and cl_c == 0:
                    cl_d = ac_d
                    cl_c = ac_c
                    ac_d = ac_c = Decimal('0.00')

                sub_op_d += op_d;  sub_op_c += op_c
                sub_ac_d += ac_d;  sub_ac_c += ac_c
                sub_cl_d += cl_d;  sub_cl_c += cl_c

                rows.append([
                    acc.get('code', ''),
                    acc.get('name', ''),
                    self._fmt(op_d) if op_d else '-',
                    self._fmt(op_c) if op_c else '-',
                    self._fmt(ac_d) if ac_d else '-',
                    self._fmt(ac_c) if ac_c else '-',
                    self._fmt(cl_d) if cl_d else '-',
                    self._fmt(cl_c) if cl_c else '-',
                ])

            # Sub-total row
            rows.append([
                '', f'TOTAL {label}',
                self._fmt(sub_op_d), self._fmt(sub_op_c),
                self._fmt(sub_ac_d), self._fmt(sub_ac_c),
                self._fmt(sub_cl_d), self._fmt(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

            # Track gross closing balance per category for summary panel
            if acc_type == 'asset':
                cat_cl['asset']     += sub_cl_d   # gross debit side
            elif acc_type == 'liability':
                cat_cl['liability'] += sub_cl_c   # gross credit side
            elif acc_type == 'equity':
                cat_cl['equity']    += sub_cl_c
            elif acc_type == 'income':
                cat_cl['income']    += sub_cl_c
            elif acc_type == 'expense':
                cat_cl['expense']   += sub_cl_d

            body_tbl = Table(rows, colWidths=cw)
            body_tbl.setStyle(TableStyle([
                ('FONTNAME',      (0, 0), (-1, -2), 'Helvetica'),
                ('FONTSIZE',      (0, 0), (-1, -1), 7.5),
                ('TOPPADDING',    (0, 0), (-1, -1), 2.5),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 2.5),
                ('LEFTPADDING',   (0, 0), (-1, -1), 4),
                ('ALIGN',         (2, 0), (-1, -1), 'RIGHT'),
                ('ROWBACKGROUNDS', (0, 0), (-1, -2), [C_WHITE, C_ROW_ALT]),
                ('LINEBELOW',     (0, 0), (-1, -2), 0.2, C_GREY_LINE),
                # Sub-total row
                ('FONTNAME',      (0, -1), (-1, -1), 'Helvetica-Bold'),
                ('BACKGROUND',    (0, -1), (-1, -1), C_TOTAL_BG),
                ('LINEABOVE',     (0, -1), (-1, -1), 1, colour),
                ('TEXTCOLOR',     (0, -1), (-1, -1), colour),
            ]))
            elems.append(body_tbl)

        # ── Grand total row ──────────────────────────────────────────
        # Label on description column = "TOTAL LIABILITIES AND EQUITY" which
        # matches the debit grand-total (Total Assets) = credit grand-total convention.
        gt = Table([[
            '', 'TOTAL LIABILITIES AND EQUITY',
            self._fmt(grand_op_d), self._fmt(grand_op_c),
            self._fmt(grand_ac_d), self._fmt(grand_ac_c),
            self._fmt(grand_cl_d), self._fmt(grand_cl_c),
        ]], colWidths=cw)
        gt.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), C_NAVY),
            ('TEXTCOLOR',     (0, 0), (-1, -1), C_WHITE),
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE',      (0, 0), (-1, -1), 8),
            ('ALIGN',         (2, 0), (-1, -1), 'RIGHT'),
            ('TOPPADDING',    (0, 0), (-1, -1), 6),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
            ('LEFTPADDING',   (0, 0), (-1, -1), 4),
        ]))
        elems += [gt, Spacer(1, 5*mm)]

        # ── Footnote ────────────────────────────────────────────────
        elems.append(Paragraph(
            'The accompanying notes on pages 1 to 25 form an integral part of these financial statements.',
            self.styles['FootNote']
        ))
        elems.append(Spacer(1, 4*mm))

        # ── Bottom dashboard ─────────────────────────────────────────
        observations = [
            f'Trial Balance generated from Finance System (FINX) as at '
            f'{as_of_date.strftime("%d %B %Y")}.',
            'Total Debits equal Total Credits. The books are mathematically accurate.',
            'All general ledger accounts agree with the subsidiary ledgers.',
            'No Suspense Account balance outstanding.',
            'Loan Portfolio balances agree with the Loan Management System.',
            'System date and period are locked and reconciled.',
        ]
        conclusion = (
            f'The Trial Balance report as at {as_of_date.strftime("%d %B %Y")} is complete, '
            'balanced and fairly presented in accordance with IPSAS (Accrual Basis of Accounting) '
            'and the requirements of the Companies Act, 2015 and Central Bank of Kenya (CBK) '
            'Prudential Guidelines for Digital Credit Providers.'
        )
        out_of_balance    = abs(grand_cl_d - grand_cl_c)
        # Per-section credit subtotals for Liabilities and Equity breakdown
        total_liabilities = cat_cl.get('liability', Decimal('0.00'))
        total_equity      = cat_cl.get('equity',    Decimal('0.00'))
        # grand_cl_d = total debit side (= Total Assets on a balanced TB)
        # grand_cl_c = total credit side (= Total L&E on a balanced TB)
        summary_rows = [
            ['Total Assets',      f'KES {self._fmt(grand_cl_d)}'],
            ['Total Liabilities', f'KES {self._fmt(total_liabilities)}'],
            ['Total Equity',      f'KES {self._fmt(total_equity)}'],
            ['Total L & E',       f'KES {self._fmt(grand_cl_c)}'],
            ['Out of Balance',    f'KES {self._fmt(out_of_balance) if out_of_balance else "0.00"}'],
        ]
        elems.append(self._bottom_dashboard(
            observations, conclusion, summary_rows,
            summary_highlights=[4],
            avail_width=W
        ))
        elems.append(Spacer(1, 6*mm))
        elems.append(self._signoff_row(avail_width=W))

        doc.build(elems, onFirstPage=cb, onLaterPages=cb)
        buffer.seek(0)
        return buffer


    # ══════════════════════════════════════════════════════════════════════════
    # 3. INCOME STATEMENT / STATEMENT OF COMPREHENSIVE INCOME
    # ══════════════════════════════════════════════════════════════════════════

    def generate_income_statement_pdf(
        self,
        income_data: Dict,
        start_date: date,
        end_date: date,
        prior_data: Optional[Dict] = None,
    ) -> BytesIO:
        """
        6-column layout:
          DESCRIPTION | NOTES | PERIOD (KES) | PRIOR PERIOD (KES) | VARIANCE KES | VARIANCE %

        income_data keys:
          income   – list of {code, name, note, amount}
          expenses – list of {code, name, note, amount}
          tax      – {note, amount}   (optional)

        prior_data: same shape as income_data but for the comparative period.
        """
        buffer = BytesIO()
        now    = datetime.now()
        rd, rt = now.strftime('%d-%b-%Y').upper(), now.strftime('%I:%M:%S %p')
        doc    = self._doc(buffer)
        cb     = self._make_header_footer(rd, rt)
        W      = 181*mm
        elems  = []

        period_label = f'PERIOD ENDED {end_date.strftime("%d %B %Y").upper()}'
        prior_end    = prior_data.get('end_date') if prior_data else None
        prior_label  = (f'PERIOD ENDED {prior_end.strftime("%d %B %Y").upper()}'
                        if prior_end else 'PRIOR PERIOD')

        elems += self._report_header_block(
            'INCOME STATEMENT', period_label, rd, rt
        )

        # ── Column widths and header ─────────────────────────────────
        # DESCRIPTION | NOTES | PERIOD KES | PRIOR KES | VAR KES | VAR %
        cw   = [72*mm, 12*mm, 29*mm, 29*mm, 24*mm, 15*mm]
        hdr1 = [
            Paragraph('DESCRIPTION',       self.styles['SecHdr']),
            Paragraph('NOTES',             self.styles['SecHdr']),
            Paragraph(period_label[:25],   self.styles['SecHdr']),
            Paragraph(prior_label[:25],    self.styles['SecHdr']),
            Paragraph('VARIANCE',          self.styles['SecHdr']),
            '',
        ]
        hdr2 = [
            '', '',
            Paragraph('KES',         self.styles['SecHdr']),
            Paragraph('KES',         self.styles['SecHdr']),
            Paragraph('KES',         self.styles['SecHdr']),
            Paragraph('%',           self.styles['SecHdr']),
        ]
        hdr_tbl = Table([hdr1, hdr2], colWidths=cw)
        hdr_tbl.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), C_NAVY),
            ('TEXTCOLOR',     (0, 0), (-1, -1), C_WHITE),
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE',      (0, 0), (-1, -1), 7.5),
            ('ALIGN',         (1, 0), (-1, -1), 'CENTER'),
            ('TOPPADDING',    (0, 0), (-1, -1), 3),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
            ('LEFTPADDING',   (0, 0), (0, 0),   6),
            ('SPAN',          (0, 0), (0, 1)),   # DESCRIPTION
            ('SPAN',          (1, 0), (1, 1)),   # NOTES
            ('SPAN',          (4, 0), (5, 0)),   # VARIANCE header
            ('VALIGN',        (0, 0), (-1, -1), 'MIDDLE'),
            ('LINEBELOW',     (0, 1), (-1, 1), 1.5, C_GREEN),
        ]))
        elems.append(hdr_tbl)

        # ── Helper: build one line ─────────────────────────────────────
        def _row(name, note, amount, prior_amount, indent=0, bold=False, bg=None):
            amt   = Decimal(str(amount   or 0))
            p_amt = Decimal(str(prior_amount or 0))
            var   = amt - p_amt
            pct   = self._var_pct(amt, p_amt)
            pad   = '    ' * indent
            style = 'Helvetica-Bold' if bold else 'Helvetica'
            cell  = Paragraph(pad + name,
                               ParagraphStyle('RI', parent=self.styles['Normal'],
                                              fontSize=7.5, fontName=style))
            return [cell, note or '', self._fmt(amt), self._fmt(p_amt),
                    self._fmt(var), pct], bg

        # ── Helper: flush rows as one Table ───────────────────────────
        def _flush_rows(row_list):
            if not row_list:
                return
            data = [r[0] for r in row_list]
            tbl  = Table(data, colWidths=cw)
            styles = [
                ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica'),
                ('FONTSIZE',      (0, 0), (-1, -1), 7.5),
                ('TOPPADDING',    (0, 0), (-1, -1), 2.5),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 2.5),
                ('LEFTPADDING',   (0, 0), (0, 0),   5),
                ('RIGHTPADDING',  (1, 0), (-1, -1), 5),
                ('ALIGN',         (1, 0), (-1, -1), 'RIGHT'),
                ('LINEBELOW',     (0, 0), (-1, -1), 0.2, C_GREY_LINE),
                ('ROWBACKGROUNDS', (0, 0), (-1, -1), [C_WHITE, C_ROW_ALT]),
            ]
            for i, (_, bg) in enumerate(row_list):
                if bg:
                    styles.append(('BACKGROUND', (0, i), (-1, i), bg))
            tbl.setStyle(TableStyle(styles))
            elems.append(tbl)

        # ── REVENUE section ──────────────────────────────────────────
        elems.append(self._section_row('REVENUE', C_GREEN, n_cols=6))
        income_items   = income_data.get('income', [])
        p_income_items = (prior_data or {}).get('income', [])
        p_income_map   = {i.get('code', i.get('name', '')): i for i in p_income_items}

        rows      = []
        tot_inc   = Decimal('0.00')
        p_tot_inc = Decimal('0.00')
        for item in income_items:
            key    = item.get('code', item.get('name', ''))
            p_item = p_income_map.get(key, {})
            amt    = Decimal(str(item.get('amount', 0) or 0))
            p_amt  = Decimal(str(p_item.get('amount', 0) or 0))
            tot_inc   += amt
            p_tot_inc += p_amt
            rows.append(_row(item.get('name', ''), item.get('note', ''),
                             amt, p_amt, indent=1))
        _flush_rows(rows)

        # Total Operating Income
        var_tot = tot_inc - p_tot_inc
        tot_row_data = [
            [Paragraph('TOTAL OPERATING INCOME', ParagraphStyle(
                'TR', parent=self.styles['Normal'],
                fontSize=8, fontName='Helvetica-Bold')),
             '', self._fmt(tot_inc), self._fmt(p_tot_inc),
             self._fmt(var_tot), self._var_pct(tot_inc, p_tot_inc)]
        ]
        tot_tbl = Table(tot_row_data, colWidths=cw)
        tot_tbl.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), C_TOTAL_BG),
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE',      (0, 0), (-1, -1), 8),
            ('ALIGN',         (1, 0), (-1, -1), 'RIGHT'),
            ('TOPPADDING',    (0, 0), (-1, -1), 5),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
            ('LEFTPADDING',   (0, 0), (0, 0),   5),
            ('LINEABOVE',     (0, 0), (-1, -1), 1, C_GREEN),
        ]))
        elems += [tot_tbl, Spacer(1, 3*mm)]

        # ── OPERATING EXPENSES section ────────────────────────────────
        elems.append(self._section_row('OPERATING EXPENSES', C_NAVY, n_cols=6))
        expense_items   = income_data.get('expenses', [])
        p_expense_items = (prior_data or {}).get('expenses', [])
        p_expense_map   = {i.get('code', i.get('name', '')): i for i in p_expense_items}

        rows      = []
        tot_exp   = Decimal('0.00')
        p_tot_exp = Decimal('0.00')
        for item in expense_items:
            key    = item.get('code', item.get('name', ''))
            p_item = p_expense_map.get(key, {})
            amt    = Decimal(str(item.get('amount', 0) or 0))
            p_amt  = Decimal(str(p_item.get('amount', 0) or 0))
            tot_exp   += amt
            p_tot_exp += p_amt
            rows.append(_row(item.get('name', ''), item.get('note', ''),
                             amt, p_amt, indent=1))
        _flush_rows(rows)

        # Total Operating Expenses
        var_exp = tot_exp - p_tot_exp
        exp_row_data = [
            [Paragraph('TOTAL OPERATING EXPENSES', ParagraphStyle(
                'TR', parent=self.styles['Normal'],
                fontSize=8, fontName='Helvetica-Bold')),
             '', self._fmt(tot_exp), self._fmt(p_tot_exp),
             self._fmt(var_exp), self._var_pct(tot_exp, p_tot_exp)]
        ]
        exp_tbl = Table(exp_row_data, colWidths=cw)
        exp_tbl.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), C_TOTAL_BG),
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE',      (0, 0), (-1, -1), 8),
            ('ALIGN',         (1, 0), (-1, -1), 'RIGHT'),
            ('TOPPADDING',    (0, 0), (-1, -1), 5),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
            ('LEFTPADDING',   (0, 0), (0, 0),   5),
            ('LINEABOVE',     (0, 0), (-1, -1), 1, C_NAVY),
        ]))
        elems += [exp_tbl, Spacer(1, 2*mm)]


        # ── Operating Profit Before Tax ──────────────────────────────
        op_profit   = tot_inc - tot_exp
        p_op_profit = p_tot_inc - p_tot_exp
        var_op      = op_profit - p_op_profit
        profit_bg   = C_GREEN_LIGHT if op_profit >= 0 else C_RED_LIGHT
        profit_fg   = C_PROFIT_FG   if op_profit >= 0 else C_LOSS_FG

        obpt_data = [
            [Paragraph('OPERATING PROFIT BEFORE TAX', ParagraphStyle(
                'PB', parent=self.styles['Normal'],
                fontSize=9, fontName='Helvetica-Bold', textColor=profit_fg)),
             '', self._fmt(op_profit), self._fmt(p_op_profit),
             self._fmt(var_op), self._var_pct(op_profit, p_op_profit)]
        ]
        obpt_tbl = Table(obpt_data, colWidths=cw)
        obpt_tbl.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), profit_bg),
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE',      (0, 0), (-1, -1), 9),
            ('ALIGN',         (1, 0), (-1, -1), 'RIGHT'),
            ('TOPPADDING',    (0, 0), (-1, -1), 6),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
            ('LEFTPADDING',   (0, 0), (0, 0),   5),
            ('LINEABOVE',     (0, 0), (-1, -1), 1.5, C_NAVY),
            ('LINEBELOW',     (0, 0), (-1, -1), 1.5, C_NAVY),
        ]))
        elems += [obpt_tbl, Spacer(1, 3*mm)]

        # ── Taxation section ─────────────────────────────────────────
        elems.append(self._section_row('TAXATION', colors.HexColor('#7d3c98'), n_cols=6))
        tax_item     = income_data.get('tax', {})
        p_tax_item   = (prior_data or {}).get('tax', {})
        tax_amt      = Decimal(str(tax_item.get('amount', 0) or 0))
        p_tax_amt    = Decimal(str(p_tax_item.get('amount', 0) or 0))
        # Tax is always an outflow – show in parens
        tax_display  = f'({self._fmt(abs(tax_amt))})' if tax_amt else '-'
        p_tax_display= f'({self._fmt(abs(p_tax_amt))})' if p_tax_amt else '-'
        var_tax      = tax_amt - p_tax_amt

        tax_data = [[
            Paragraph('Income Tax Expense', ParagraphStyle(
                'TI', parent=self.styles['Normal'], fontSize=7.5)),
            tax_item.get('note', '10'),
            tax_display, p_tax_display,
            self._fmt(var_tax), self._var_pct(tax_amt, p_tax_amt),
        ]]
        tax_tbl = Table(tax_data, colWidths=cw)
        tax_tbl.setStyle(TableStyle([
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica'),
            ('FONTSIZE',      (0, 0), (-1, -1), 7.5),
            ('ALIGN',         (1, 0), (-1, -1), 'RIGHT'),
            ('TOPPADDING',    (0, 0), (-1, -1), 3),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
            ('LEFTPADDING',   (0, 0), (0, 0),   12),
        ]))
        elems += [tax_tbl, Spacer(1, 2*mm)]

        # ── Net Profit for the Period ─────────────────────────────────
        net_profit   = op_profit + tax_amt  # tax_amt is negative
        p_net_profit = p_op_profit + p_tax_amt
        var_net      = net_profit - p_net_profit
        net_bg       = C_GREEN_LIGHT if net_profit >= 0 else C_RED_LIGHT
        net_fg       = C_PROFIT_FG   if net_profit >= 0 else C_LOSS_FG

        np_data = [
            [Paragraph('NET PROFIT FOR THE PERIOD', ParagraphStyle(
                'NP', parent=self.styles['Normal'],
                fontSize=9, fontName='Helvetica-Bold', textColor=net_fg)),
             '', self._fmt(net_profit), self._fmt(p_net_profit),
             self._fmt(var_net), self._var_pct(net_profit, p_net_profit)]
        ]
        np_tbl = Table(np_data, colWidths=cw)
        np_tbl.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), net_bg),
            ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE',      (0, 0), (-1, -1), 9),
            ('ALIGN',         (1, 0), (-1, -1), 'RIGHT'),
            ('TOPPADDING',    (0, 0), (-1, -1), 6),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 6),
            ('LEFTPADDING',   (0, 0), (0, 0),   5),
            ('LINEABOVE',     (0, 0), (-1, -1), 2, C_NAVY),
            ('LINEBELOW',     (0, 0), (-1, -1), 2, C_NAVY),
        ]))
        elems += [np_tbl, Spacer(1, 3*mm)]

        # ── Other Comprehensive Income ─────────────────────────────
        elems.append(self._section_row('OTHER COMPREHENSIVE INCOME', C_GREEN, n_cols=6))
        oci_items = income_data.get('oci', [])
        if oci_items:
            oci_rows = []
            for item in oci_items:
                p_item = {}
                oci_rows.append(_row(item.get('name', ''), item.get('note', '11'),
                                     item.get('amount', 0), p_item.get('amount', 0),
                                     indent=1))
            _flush_rows(oci_rows)
        else:
            # Placeholder rows matching document format
            for lbl in ['Items that will not be reclassified to Profit or Loss',
                        'Items that may be reclassified to Profit or Loss']:
                no_data = [[
                    Paragraph('    ' + lbl, ParagraphStyle(
                        'OCI', parent=self.styles['Normal'], fontSize=7.5)),
                    '11', '-', '-', '-', '-',
                ]]
                nt = Table(no_data, colWidths=cw)
                nt.setStyle(TableStyle([
                    ('FONTNAME',   (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE',   (0, 0), (-1, -1), 7.5),
                    ('ALIGN',      (1, 0), (-1, -1), 'RIGHT'),
                    ('TOPPADDING', (0, 0), (-1, -1), 3),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
                    ('LEFTPADDING', (0, 0), (0, 0), 5),
                ]))
                elems.append(nt)

        # Total OCI + Total Comprehensive Income
        tot_oci = sum(Decimal(str(i.get('amount', 0) or 0)) for i in oci_items)
        oci_tot_data = [[
            Paragraph('TOTAL OTHER COMPREHENSIVE INCOME',
                       ParagraphStyle('OT', parent=self.styles['Normal'],
                                      fontSize=7.5, fontName='Helvetica-Bold')),
            '', self._fmt(tot_oci) if tot_oci else '-',
            '-', '-', '-',
        ]]
        total_ci = net_profit + tot_oci
        p_total_ci = p_net_profit
        ci_data = [[
            Paragraph('TOTAL COMPREHENSIVE INCOME FOR THE PERIOD',
                       ParagraphStyle('CI', parent=self.styles['Normal'],
                                      fontSize=9, fontName='Helvetica-Bold',
                                      textColor=net_fg)),
            '', self._fmt(total_ci), self._fmt(p_total_ci),
            self._fmt(total_ci - p_total_ci),
            self._var_pct(total_ci, p_total_ci),
        ]]

        for row_data, bg, line_clr in [
            (oci_tot_data, C_TOTAL_BG, C_NAVY),
            (ci_data,      net_bg,     C_NAVY),
        ]:
            t = Table(row_data, colWidths=cw)
            t.setStyle(TableStyle([
                ('BACKGROUND',    (0, 0), (-1, -1), bg),
                ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica-Bold'),
                ('FONTSIZE',      (0, 0), (-1, -1), 8),
                ('ALIGN',         (1, 0), (-1, -1), 'RIGHT'),
                ('TOPPADDING',    (0, 0), (-1, -1), 5),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 5),
                ('LEFTPADDING',   (0, 0), (0, 0),   5),
                ('LINEABOVE',     (0, 0), (-1, -1), 1, line_clr),
            ]))
            elems.append(t)

        elems.append(Spacer(1, 4*mm))
        elems.append(Paragraph(
            'The accompanying notes on pages 1 to 25 form an integral part of these financial statements.',
            self.styles['FootNote']
        ))
        elems.append(Spacer(1, 5*mm))

        # ── Bottom dashboard ─────────────────────────────────────────
        observations = [
            f'The Income Statement was generated from Finance System (FINX) '
            f'for the period ended {end_date.strftime("%d %B %Y")}.',
            'All income and expenses are recorded on an accrual basis.',
            'All amounts agree with the Trial Balance and the supporting ledgers.',
            'Loan Loss Provision has been provided in accordance with IFRS 9.',
            'No material misstatements or unreconciled items were noted.',
        ]
        conclusion = (
            f'The Income Statement for the period ended {end_date.strftime("%d %B %Y")} '
            'presents fairly, in all material respects, the financial performance of '
            'Haven Grazuri Credit Solutions Ltd in accordance with IFRS for SMEs, the '
            'requirements of the Companies Act, 2015 and the Central Bank of Kenya (CBK) '
            'Prudential Guidelines for Digital Credit Providers.'
        )
        summary_rows = [
            ['Total Operating Income',    f'{self._fmt(tot_inc)}'],
            ['Total Operating Expenses',  f'({self._fmt(tot_exp)})'],
            ['Operating Profit Before Tax', f'{self._fmt(op_profit)}'],
            ['Income Tax Expense',         f'({self._fmt(abs(tax_amt))})'],
            ['Net Profit for the Period',  f'{self._fmt(net_profit)}'],
            ['Total Comprehensive Income', f'{self._fmt(total_ci)}'],
        ]
        highlights = [4, 5] if net_profit >= 0 else []
        elems.append(self._bottom_dashboard(
            observations, conclusion, summary_rows,
            summary_highlights=highlights,
            avail_width=W
        ))
        elems.append(Spacer(1, 6*mm))
        elems.append(self._signoff_row(avail_width=W))

        doc.build(elems, onFirstPage=cb, onLaterPages=cb)
        buffer.seek(0)
        return buffer


    # ══════════════════════════════════════════════════════════════════════════
    # 4. STATEMENT OF FINANCIAL POSITION  (side-by-side layout)
    # ══════════════════════════════════════════════════════════════════════════

    def generate_balance_sheet_pdf(
        self,
        balance_data: Dict,
        as_of_date: date,
    ) -> BytesIO:
        """
        Side-by-side layout:
          LEFT  HALF: ASSETS  (ITEM | NOTES | KES)
          RIGHT HALF: LIABILITIES AND EQUITY  (ITEM | NOTES | KES)

        balance_data keys:
          assets      – list of {name, note, amount, subtype}
          liabilities – list of {name, note, amount, subtype}
          equity      – list of {name, note, amount}
        """
        buffer = BytesIO()
        now    = datetime.now()
        rd, rt = now.strftime('%d-%b-%Y').upper(), now.strftime('%I:%M:%S %p')
        doc    = self._doc(buffer)
        cb     = self._make_header_footer(rd, rt)
        W      = 181*mm
        elems  = []

        asset_items     = balance_data.get('assets',      [])
        liability_items = balance_data.get('liabilities', [])
        equity_items    = balance_data.get('equity',      [])

        total_assets      = sum(Decimal(str(i.get('amount', 0) or 0)) for i in asset_items)
        total_liabilities = sum(Decimal(str(i.get('amount', 0) or 0)) for i in liability_items)
        total_equity      = sum(Decimal(str(i.get('amount', 0) or 0)) for i in equity_items)
        total_le          = total_liabilities + total_equity
        balanced          = abs(total_assets - total_le) < Decimal('0.01')

        elems += self._report_header_block(
            'STATEMENT OF FINANCIAL POSITION',
            f'AS AT {as_of_date.strftime("%d %B %Y").upper()}',
            rd, rt
        )

        # System info banner
        meta_rows = [[
            Paragraph(f'System : {self.SYSTEM_NAME}', self.styles['Note']),
            Paragraph(
                f'Run Date: {rd}  |  Run Time: {rt}  |  '
                f'{"A = L + E  ✓ BALANCED" if balanced else "⚠ OUT OF BALANCE"}',
                ParagraphStyle('MetaC', parent=self.styles['Note'], alignment=TA_RIGHT)
            ),
        ]]
        meta_tbl = Table(meta_rows, colWidths=[W/2, W/2])
        meta_tbl.setStyle(TableStyle([
            ('TOPPADDING',    (0, 0), (-1, -1), 2),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
        ]))
        elems += [meta_tbl, Spacer(1, 3*mm)]

        # ── Build left (Assets) and right (L&E) columns ──────────────
        # Each half uses 3 sub-columns: NAME | NOTES | KES
        half = W / 2 - 2*mm
        sub_cw = [half * 0.58, half * 0.10, half * 0.32]

        def _half_header(label: str, colour: Any) -> Table:
            t = Table([[
                Paragraph(label, self.styles['SecHdr']), '', '',
            ]], colWidths=sub_cw)
            t.setStyle(TableStyle([
                ('BACKGROUND',    (0, 0), (-1, -1), colour),
                ('SPAN',          (0, 0), (-1, 0)),
                ('TOPPADDING',    (0, 0), (-1, -1), 4),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
                ('LEFTPADDING',   (0, 0), (0, 0),   6),
            ]))
            return t

        def _sub_header(label: str, colour: Any) -> Table:
            t = Table([[
                Paragraph(label, ParagraphStyle('SH', parent=self.styles['Normal'],
                           fontSize=7.5, textColor=C_WHITE,
                           fontName='Helvetica-Bold')), '', '',
            ]], colWidths=sub_cw)
            t.setStyle(TableStyle([
                ('BACKGROUND',    (0, 0), (-1, -1), colour),
                ('SPAN',          (0, 0), (-1, 0)),
                ('TOPPADDING',    (0, 0), (-1, -1), 3),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
                ('LEFTPADDING',   (0, 0), (0, 0),   10),
            ]))
            return t

        def _item_rows(items: list, fg: Any = C_TEXT) -> list:
            """Returns list of [name, notes, amount] raw rows."""
            rows = []
            for item in items:
                amt = Decimal(str(item.get('amount', 0) or 0))
                rows.append([
                    item.get('name', ''),
                    str(item.get('note', '') or ''),
                    self._fmt(amt),
                ])
            return rows

        def _items_table(items: list) -> Table:
            rows = _item_rows(items)
            t = Table(rows, colWidths=sub_cw)
            t.setStyle(TableStyle([
                ('FONTNAME',      (0, 0), (-1, -1), 'Helvetica'),
                ('FONTSIZE',      (0, 0), (-1, -1), 7.5),
                ('TOPPADDING',    (0, 0), (-1, -1), 2.5),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 2.5),
                ('LEFTPADDING',   (0, 0), (0, 0),   10),
                ('LEFTPADDING',   (1, 0), (1, -1),  3),
                ('ALIGN',         (1, 0), (-1, -1), 'RIGHT'),
                ('LINEBELOW',     (0, 0), (-1, -1), 0.2, C_GREY_LINE),
                ('ROWBACKGROUNDS', (0, 0), (-1, -1), [C_WHITE, C_ROW_ALT]),
            ]))
            return t

        def _subtotal_table(label: str, amount: Decimal,
                            note: str = '', colour: Any = C_NAVY) -> Table:
            t = Table([[
                Paragraph(label, ParagraphStyle('ST', parent=self.styles['Normal'],
                           fontSize=8, fontName='Helvetica-Bold')),
                note,
                Paragraph(self._fmt(amount), ParagraphStyle('STR',
                           parent=self.styles['Normal'],
                           fontSize=8, fontName='Helvetica-Bold',
                           alignment=TA_RIGHT)),
            ]], colWidths=sub_cw)
            t.setStyle(TableStyle([
                ('BACKGROUND',    (0, 0), (-1, -1), C_TOTAL_BG),
                ('LINEABOVE',     (0, 0), (-1, -1), 1, colour),
                ('TOPPADDING',    (0, 0), (-1, -1), 4),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
                ('LEFTPADDING',   (0, 0), (0, 0),   6),
            ]))
            return t

        # ── Classify asset items into non-current / current ─────────
        nca = [i for i in asset_items if i.get('subtype', '') in
               ('fixed_asset', 'other_asset', 'right_of_use', 'deferred_tax')]
        ca  = [i for i in asset_items if i not in nca]

        total_nca = sum(Decimal(str(i.get('amount', 0) or 0)) for i in nca)
        total_ca  = sum(Decimal(str(i.get('amount', 0) or 0)) for i in ca)

        # ── Classify liabilities ──────────────────────────────────
        ncl = [i for i in liability_items if i.get('subtype', '') in
               ('borrowings', 'other_liability') and
               i.get('non_current', False)]
        cl  = [i for i in liability_items if i not in ncl]
        # Fallback: if no non_current flag, treat borrowings as split
        if not ncl:
            ncl = [i for i in liability_items if 'non' in i.get('name', '').lower()
                   or 'long' in i.get('name', '').lower()]
            cl  = [i for i in liability_items if i not in ncl]

        total_ncl = sum(Decimal(str(i.get('amount', 0) or 0)) for i in ncl)
        total_cl  = sum(Decimal(str(i.get('amount', 0) or 0)) for i in cl)

        # ── Build asset column elements ───────────────────────────
        asset_elems = [_half_header('ASSETS', C_GREEN)]
        if nca:
            asset_elems.append(_sub_header('NON-CURRENT ASSETS', colors.HexColor('#1a5276')))
            asset_elems.append(_items_table(nca))
            asset_elems.append(_subtotal_table('TOTAL NON-CURRENT ASSETS', total_nca, colour=C_GREEN))
        if ca:
            asset_elems.append(_sub_header('CURRENT ASSETS', colors.HexColor('#117a65')))
            asset_elems.append(_items_table(ca))
            asset_elems.append(_subtotal_table('TOTAL CURRENT ASSETS', total_ca, colour=C_GREEN))

        asset_elems.append(Spacer(1, 3*mm))
        total_a_data = [[
            Paragraph('TOTAL ASSETS', ParagraphStyle('TA', parent=self.styles['Normal'],
                       fontSize=10, fontName='Helvetica-Bold', textColor=C_WHITE)),
            '',
            Paragraph(self._fmt(total_assets), ParagraphStyle('TAR',
                       parent=self.styles['Normal'],
                       fontSize=10, fontName='Helvetica-Bold',
                       textColor=C_WHITE, alignment=TA_RIGHT)),
        ]]
        ta_tbl = Table(total_a_data, colWidths=sub_cw)
        ta_tbl.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), C_NAVY),
            ('TOPPADDING',    (0, 0), (-1, -1), 7),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 7),
            ('LEFTPADDING',   (0, 0), (0, 0),   6),
        ]))
        asset_elems.append(ta_tbl)

        # ── Build L&E column elements ─────────────────────────────
        le_elems = [_half_header('LIABILITIES AND EQUITY', C_NAVY)]
        if ncl:
            le_elems.append(_sub_header('NON-CURRENT LIABILITIES', colors.HexColor('#1a5276')))
            le_elems.append(_items_table(ncl))
            le_elems.append(_subtotal_table('TOTAL NON-CURRENT LIABILITIES', total_ncl))
        if cl:
            le_elems.append(_sub_header('CURRENT LIABILITIES', colors.HexColor('#5d6d7e')))
            le_elems.append(_items_table(cl))
            le_elems.append(_subtotal_table('TOTAL CURRENT LIABILITIES', total_cl))

        le_elems.append(_subtotal_table('TOTAL LIABILITIES', total_liabilities,
                                        colour=colors.HexColor('#922b21')))

        if equity_items:
            le_elems.append(Spacer(1, 2*mm))
            le_elems.append(_sub_header('EQUITY', colors.HexColor('#6c3483')))
            le_elems.append(_items_table(equity_items))
            le_elems.append(_subtotal_table('TOTAL EQUITY', total_equity,
                                             colour=colors.HexColor('#6c3483')))

        le_elems.append(Spacer(1, 3*mm))
        total_le_data = [[
            Paragraph('TOTAL LIABILITIES AND EQUITY', ParagraphStyle(
                'TLE', parent=self.styles['Normal'],
                fontSize=10, fontName='Helvetica-Bold', textColor=C_WHITE)),
            '',
            Paragraph(self._fmt(total_le), ParagraphStyle('TLER',
                       parent=self.styles['Normal'],
                       fontSize=10, fontName='Helvetica-Bold',
                       textColor=C_WHITE, alignment=TA_RIGHT)),
        ]]
        tle_tbl = Table(total_le_data, colWidths=sub_cw)
        bg_col = C_GREEN if balanced else colors.HexColor('#922b21')
        tle_tbl.setStyle(TableStyle([
            ('BACKGROUND',    (0, 0), (-1, -1), bg_col),
            ('TOPPADDING',    (0, 0), (-1, -1), 7),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 7),
            ('LEFTPADDING',   (0, 0), (0, 0),   6),
        ]))
        le_elems.append(tle_tbl)

        # ── Combine columns side-by-side ──────────────────────────
        from reportlab.platypus import KeepInFrame
        asset_frame = Table(
            [[e] for e in asset_elems],
            colWidths=[half]
        )
        asset_frame.setStyle(TableStyle([
            ('TOPPADDING',    (0, 0), (-1, -1), 0),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
            ('LEFTPADDING',   (0, 0), (-1, -1), 0),
            ('RIGHTPADDING',  (0, 0), (-1, -1), 2),
        ]))

        le_frame = Table(
            [[e] for e in le_elems],
            colWidths=[half]
        )
        le_frame.setStyle(TableStyle([
            ('TOPPADDING',    (0, 0), (-1, -1), 0),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
            ('LEFTPADDING',   (0, 0), (-1, -1), 2),
            ('RIGHTPADDING',  (0, 0), (-1, -1), 0),
        ]))

        side_by_side = Table(
            [[asset_frame, le_frame]],
            colWidths=[half + 2*mm, half + 2*mm]
        )
        side_by_side.setStyle(TableStyle([
            ('VALIGN',       (0, 0), (-1, -1), 'TOP'),
            ('LINEAFTER',    (0, 0), (0, -1),  0.5, C_GREY_LINE),
            ('TOPPADDING',   (0, 0), (-1, -1), 0),
            ('LEFTPADDING',  (0, 0), (-1, -1), 0),
            ('RIGHTPADDING', (0, 0), (-1, -1), 0),
        ]))
        elems.append(side_by_side)
        elems.append(Spacer(1, 4*mm))
        elems.append(Paragraph(
            'The accompanying notes on pages 1 to 25 form an integral part of these financial statements.',
            self.styles['FootNote']
        ))
        elems.append(Spacer(1, 5*mm))

        # ── Bottom dashboard ─────────────────────────────────────────
        observations = [
            f'The Statement of Financial Position was generated from Finance System (FINX) '
            f'as at {as_of_date.strftime("%d %B %Y")}.',
            'All balances agree with the Trial Balance and the subsidiary ledgers.',
            'The classification of assets and liabilities is in accordance with IFRS for SMEs.',
            'All non-current assets are supported by registers and documentation.',
            'No material misstatements or unreconciled items were noted.',
        ]
        conclusion = (
            f'The Statement of Financial Position as at {as_of_date.strftime("%d %B %Y")} '
            'presents fairly, in all material respects, the financial position of '
            'Haven Grazuri Credit Solutions Ltd in accordance with IFRS for SMEs and the '
            'requirements of the Companies Act, 2015 and the Central Bank of Kenya (CBK) '
            'Prudential Guidelines for Digital Credit Providers.'
        )
        summary_rows = [
            ['Total Assets',               self._fmt(total_assets)],
            ['Total Liabilities',          self._fmt(total_liabilities)],
            ['Total Equity',               self._fmt(total_equity)],
            ['Total Liabilities & Equity', self._fmt(total_le)],
        ]
        elems.append(self._bottom_dashboard(
            observations, conclusion, summary_rows,
            summary_highlights=[3],
            avail_width=W
        ))
        elems.append(Spacer(1, 6*mm))
        elems.append(self._signoff_row(avail_width=W))

        doc.build(elems, onFirstPage=cb, onLaterPages=cb)
        buffer.seek(0)
        return buffer


    # ══════════════════════════════════════════════════════════════════════════
    # 5. ACCOUNT LEDGER
    # ══════════════════════════════════════════════════════════════════════════

    def generate_account_ledger_pdf(
        self,
        account: Dict,
        transactions: List[Dict],
        start_date: Optional[date] = None,
        end_date:   Optional[date] = None,
        opening_balance: Decimal = Decimal('0.00'),
    ) -> BytesIO:
        buffer = BytesIO()
        now    = datetime.now()
        rd, rt = now.strftime('%d-%b-%Y').upper(), now.strftime('%I:%M:%S %p')
        doc    = self._doc(buffer)
        cb     = self._make_header_footer(rd, rt)
        W      = 181*mm
        elems  = []

        period_str = ''
        if start_date and end_date:
            period_str = (f'{start_date.strftime("%d %b %Y")}  →  '
                          f'{end_date.strftime("%d %b %Y")}')
        elif end_date:
            period_str = f'Up to {end_date.strftime("%d %b %Y")}'

        code     = account.get('code', '')
        acc_name = account.get('name', '')
        acc_type = account.get('type', '').title()

        elems += self._report_header_block(
            f'ACCOUNT LEDGER — {code} · {acc_name}',
            period_str or 'All Dates',
            rd, rt
        )

        # Summary bar
        total_d = sum(
            Decimal(str(tx.get('debit', tx.get('debit_amount', 0)) or 0))
            for tx in transactions
        )
        total_c = sum(
            Decimal(str(tx.get('credit', tx.get('credit_amount', 0)) or 0))
            for tx in transactions
        )
        closing_balance = opening_balance + total_d - total_c

        sum_data = [
            ['Account', f'{code} – {acc_name}', 'Type', acc_type],
            ['Opening Balance', self._fmt(opening_balance), 'Total Debits', self._fmt(total_d)],
            ['Closing Balance', self._fmt(closing_balance), 'Total Credits', self._fmt(total_c)],
            ['Transactions', str(len(transactions)), 'Net Movement', self._fmt(total_d - total_c)],
        ]
        sw = [35*mm, 40*mm, 35*mm, 40*mm]
        st = Table(sum_data, colWidths=sw)
        st.setStyle(TableStyle([
            ('FONTNAME',    (0, 0), (-1, -1), 'Helvetica'),
            ('FONTSIZE',    (0, 0), (-1, -1), 8),
            ('FONTNAME',    (1, 0), (1, -1),  'Helvetica-Bold'),
            ('FONTNAME',    (3, 0), (3, -1),  'Helvetica-Bold'),
            ('BACKGROUND',  (0, 0), (-1, -1), colors.HexColor('#eef6ff')),
            ('ALIGN',       (1, 0), (1, -1),  'LEFT'),
            ('ALIGN',       (3, 0), (3, -1),  'RIGHT'),
            ('TOPPADDING',  (0, 0), (-1, -1), 3),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 3),
            ('LEFTPADDING', (0, 0), (-1, -1), 5),
            ('LINEBELOW',   (0, 0), (-1, -2), 0.3, C_GREY_LINE),
            ('BOX',         (0, 0), (-1, -1), 0.5, C_NAVY),
        ]))
        elems += [st, Spacer(1, 4*mm)]

        # Transaction detail table
        cw  = [22*mm, 22*mm, 70*mm, 22*mm, 22*mm, 23*mm]
        hdr = [['DATE', 'REFERENCE', 'DESCRIPTION', 'DEBIT (KES)', 'CREDIT (KES)', 'BALANCE (KES)']]
        rows = [[
            start_date.strftime('%d %b %Y') if start_date else '—',
            '',
            'Opening Balance',
            '', '',
            self._fmt(opening_balance),
        ]]

        for tx in transactions:
            d_amt = Decimal(str(tx.get('debit',  tx.get('debit_amount',  0)) or 0))
            c_amt = Decimal(str(tx.get('credit', tx.get('credit_amount', 0)) or 0))
            bal   = tx.get('balance', Decimal('0.00'))
            tx_dt = tx.get('date', tx.get('transaction_date', ''))
            if hasattr(tx_dt, 'strftime'):
                tx_dt = tx_dt.strftime('%d %b %Y')
            rows.append([
                str(tx_dt),
                str(tx.get('reference_number', tx.get('reference', '')))[:15],
                str(tx.get('description', ''))[:60],
                self._fmt(d_amt) if d_amt else '-',
                self._fmt(c_amt) if c_amt else '-',
                self._fmt(bal),
            ])

        rows.append([
            end_date.strftime('%d %b %Y') if end_date else '—',
            '', 'Closing Balance',
            self._fmt(total_d), self._fmt(total_c), self._fmt(closing_balance),
        ])

        tbl = self._std_table(hdr + rows, cw, hdr_rows=1, accent=C_NAVY)
        tbl.setStyle(TableStyle([
            ('ALIGN',       (3, 0), (-1, -1), 'RIGHT'),
            ('FONTNAME',    (0, 1), (-1, 1),  'Helvetica-Bold'),   # opening row
            ('FONTNAME',    (0, -1), (-1, -1), 'Helvetica-Bold'),  # closing row
            ('BACKGROUND',  (0, 1),  (-1, 1),  colors.HexColor('#eef6ff')),
            ('BACKGROUND',  (0, -1), (-1, -1), colors.HexColor('#eef6ff')),
        ]))
        elems += [tbl, Spacer(1, 4*mm)]
        elems.append(Paragraph(
            'Debit entries increase asset/expense accounts; '
            'Credit entries increase liability/equity/income accounts.',
            self.styles['Note']
        ))

        doc.build(elems, onFirstPage=cb, onLaterPages=cb)
        buffer.seek(0)
        return buffer
