import os
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from openpyxl.utils import get_column_letter

from reportlab.lib.pagesizes import A4, landscape
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch

from database import get_stok_harian_detail, is_shift_closed

def format_rupiah(val):
    """Format integer ke rupiah string: 8000 -> Rp 8.000"""
    if val is None or val == "":
        return "Rp 0"
    return f"Rp {val:,.0f}".replace(",", ".")

def generate_pdf_report(tanggal, output_path, db_path=None, filter_kategori=None):
    """
    Generate PDF A4 Landscape Report for a given date.
    """
    if filter_kategori and str(filter_kategori).lower() == 'indomie & gorengan':
        from report_khusus import generate_pdf_khusus
        return generate_pdf_khusus(tanggal, output_path, db_path)

    data_list = get_stok_harian_detail(tanggal, db_path=db_path) if db_path else get_stok_harian_detail(tanggal)
    if filter_kategori:
        data_list = [d for d in data_list if str(d['nama_kategori']).lower() == str(filter_kategori).lower()]
    
    # Setup document: A4 Landscape
    doc = SimpleDocTemplate(
        output_path,
        pagesize=landscape(A4),
        leftMargin=30,
        rightMargin=30,
        topMargin=30,
        bottomMargin=30
    )
    
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'TitleStyle',
        parent=styles['Heading1'],
        fontName='Helvetica-Bold',
        fontSize=16,
        leading=20,
        alignment=1, # Center
        spaceAfter=6
    )
    
    subtitle_style = ParagraphStyle(
        'SubtitleStyle',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=10,
        leading=14,
        alignment=1, # Center
        spaceAfter=15
    )
    
    header_style = ParagraphStyle(
        'HeaderStyle',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=8,
        leading=10,
        alignment=1, # Center
        textColor=colors.whitesmoke
    )
    
    cell_style = ParagraphStyle(
        'CellStyle',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=8,
        leading=10
    )
    
    cell_style_center = ParagraphStyle(
        'CellStyleCenter',
        parent=cell_style,
        alignment=1 # Center
    )
    
    cell_style_right = ParagraphStyle(
        'CellStyleRight',
        parent=cell_style,
        alignment=2 # Right
    )

    cell_style_bold_right = ParagraphStyle(
        'CellStyleBoldRight',
        parent=cell_style,
        fontName='Helvetica-Bold',
        alignment=2 # Right
    )

    story = []
    
    # Title & Header
    title_text = "LAPORAN HARIAN KANTIN SECABA RINDAM III/SILIWANGI"
    story.append(Paragraph(title_text, title_style))
    
    status_str = "KUNCI / CLOSED" if (is_shift_closed(tanggal, db_path) if db_path else is_shift_closed(tanggal)) else "BUKA / ACTIVE"
    subtitle_text = f"Tanggal Laporan: {tanggal}   |   Status Shift: {status_str}"
    story.append(Paragraph(subtitle_text, subtitle_style))
    
    # Table data
    # Header Row 1 & 2
    table_data = [
        [
            Paragraph("NO", header_style),
            Paragraph("JENIS BARANG", header_style),
            Paragraph("STOK BARANG", header_style), "", "", "", "",
            Paragraph("Penjualan", header_style), "",
            Paragraph("PEMBAYARAN", header_style), "",
            Paragraph("LABA", header_style)
        ],
        [
            "", "",
            Paragraph("SISA H-1", header_style),
            Paragraph("BELI", header_style),
            Paragraph("JUMLAH", header_style),
            Paragraph("JUAL", header_style),
            Paragraph("SISA", header_style),
            Paragraph("HARGA JUAL", header_style),
            Paragraph("TOTAL", header_style),
            Paragraph("HARGA BELI", header_style),
            Paragraph("TOTAL", header_style),
            ""
        ]
    ]
    
    # Populate rows
    total_beli_sum = 0
    total_jual_sum = 0
    total_laba_sum = 0
    
    sum_sisa_h1 = 0
    sum_beli = 0
    sum_jumlah = 0
    sum_jual = 0
    sum_sisa = 0

    # Group by category in table display
    current_category = None
    row_number = 1
    
    for item in data_list:
        # Jika ada kategori baru, tambahkan baris pembatas kategori
        if item['nama_kategori'] != current_category:
            current_category = item['nama_kategori']
            # Tambahkan baris nama kategori
            cat_header_style = ParagraphStyle(
                'CatHeaderStyle',
                parent=styles['Normal'],
                fontName='Helvetica-Bold',
                fontSize=8,
                leading=10,
                alignment=0, # Left
                textColor=colors.HexColor('#1A365D')
            )
            table_data.append([
                "", Paragraph(f"--- KATEGORI: {current_category.upper()} ---", cat_header_style),
                "", "", "", "", "", "", "", "", "", ""
            ])
        
        # Calculate dynamic calculations in python for PDF
        jumlah = item['sisa_h1'] + item['beli']
        sisa = jumlah - item['jual']
        total_jual = item['jual'] * item['harga_jual']
        total_beli = item['jual'] * item['harga_beli']
        laba = total_jual - total_beli
        
        # Sum columns
        sum_sisa_h1 += item['sisa_h1']
        sum_beli += item['beli']
        sum_jumlah += jumlah
        sum_jual += item['jual']
        sum_sisa += sisa
        total_jual_sum += total_jual
        total_beli_sum += total_beli
        total_laba_sum += laba
        
        row = [
            Paragraph(str(row_number), cell_style_center),
            Paragraph(item['nama_barang'], cell_style),
            Paragraph(str(item['sisa_h1']), cell_style_center),
            Paragraph(str(item['beli']), cell_style_center),
            Paragraph(str(jumlah), cell_style_center),
            Paragraph(str(item['jual']), cell_style_center),
            Paragraph(str(sisa), cell_style_center),
            Paragraph(format_rupiah(item['harga_jual']), cell_style_right),
            Paragraph(format_rupiah(total_jual), cell_style_right),
            Paragraph(format_rupiah(item['harga_beli']), cell_style_right),
            Paragraph(format_rupiah(total_beli), cell_style_right),
            Paragraph(format_rupiah(laba), cell_style_right),
        ]
        table_data.append(row)
        row_number += 1
        
    # Add Total Row
    total_label_style = ParagraphStyle(
        'TotalLabelStyle',
        parent=styles['Normal'],
        fontName='Helvetica-Bold',
        fontSize=8,
        leading=10,
        alignment=1 # Center
    )
    table_data.append([
        Paragraph("TOTAL", total_label_style), "",
        Paragraph(str(sum_sisa_h1), total_label_style),
        Paragraph(str(sum_beli), total_label_style),
        Paragraph(str(sum_jumlah), total_label_style),
        Paragraph(str(sum_jual), total_label_style),
        Paragraph(str(sum_sisa), total_label_style),
        "",
        Paragraph(format_rupiah(total_jual_sum), total_label_style),
        "",
        Paragraph(format_rupiah(total_beli_sum), total_label_style),
        Paragraph(format_rupiah(total_laba_sum), ParagraphStyle('LabaTotal', parent=total_label_style, textColor=colors.HexColor('#2F855A'))),
    ])
    
    # Column widths (total = 770)
    col_widths = [25, 135, 45, 40, 50, 40, 45, 65, 75, 65, 75, 110]
    
    t = Table(table_data, colWidths=col_widths, repeatRows=2)
    
    # Table Styling
    t_style = [
        # Merges for Header
        ('SPAN', (0, 0), (0, 1)),   # NO
        ('SPAN', (1, 0), (1, 1)),   # JENIS BARANG
        ('SPAN', (2, 0), (6, 0)),   # STOK BARANG
        ('SPAN', (7, 0), (8, 0)),   # Penjualan
        ('SPAN', (9, 0), (10, 0)),  # PEMBAYARAN
        ('SPAN', (11, 0), (11, 1)), # LABA
        
        # Header styles
        ('BACKGROUND', (0, 0), (-1, 1), colors.HexColor('#1A365D')),
        ('ALIGN', (0, 0), (-1, 1), 'CENTER'),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#CBD5E0')),
        ('TOPPADDING', (0, 0), (-1, -1), 4),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 4),
    ]
    
    # Add spans for category rows (Col 1 spans across other columns)
    current_row_idx = 2
    category_rows = []
    
    # We find where category rows are
    for item in data_list:
        if item['nama_kategori'] != current_category:
            current_category = item['nama_kategori']
            category_rows.append(current_row_idx)
            # Span category header row
            t_style.append(('SPAN', (1, current_row_idx), (-1, current_row_idx)))
            t_style.append(('BACKGROUND', (0, current_row_idx), (-1, current_row_idx), colors.HexColor('#EDF2F7')))
            current_row_idx += 1
        current_row_idx += 1
        
    # Total row styling
    total_row_idx = len(table_data) - 1
    t_style.append(('SPAN', (0, total_row_idx), (1, total_row_idx))) # NO and JENIS BARANG merged
    t_style.append(('BACKGROUND', (0, total_row_idx), (-1, total_row_idx), colors.HexColor('#E2E8F0')))
    t_style.append(('LINEABOVE', (0, total_row_idx), (-1, total_row_idx), 1.5, colors.HexColor('#1A365D')))
    
    t.setStyle(TableStyle(t_style))
    story.append(t)
    
    doc.build(story)


def generate_excel_report(tanggal, output_path, db_path=None, filter_kategori=None):
    """
    Generate Excel Report for a given date with formula-based totals.
    """
    if filter_kategori and str(filter_kategori).lower() == 'indomie & gorengan':
        from report_khusus import generate_excel_khusus
        return generate_excel_khusus(tanggal, output_path, db_path)

    data_list = get_stok_harian_detail(tanggal, db_path=db_path) if db_path else get_stok_harian_detail(tanggal)
    if filter_kategori:
        data_list = [d for d in data_list if str(d['nama_kategori']).lower() == str(filter_kategori).lower()]
    
    wb = openpyxl.Workbook()
    ws = wb.active
    ws.title = "Laporan Kantin"
    
    # Aktifkan gridlines
    ws.views.sheetView[0].showGridLines = True
    
    # Styles
    font_title = Font(name="Calibri", size=16, bold=True, color="1A365D")
    font_subtitle = Font(name="Calibri", size=11, italic=True)
    font_header = Font(name="Calibri", size=10, bold=True, color="FFFFFF")
    font_category = Font(name="Calibri", size=10, bold=True, color="1A365D")
    font_data = Font(name="Calibri", size=10)
    font_total = Font(name="Calibri", size=10, bold=True)
    
    fill_header = PatternFill(start_color="1A365D", end_color="1A365D", fill_type="solid")
    fill_category = PatternFill(start_color="EDF2F7", end_color="EDF2F7", fill_type="solid")
    fill_total = PatternFill(start_color="E2E8F0", end_color="E2E8F0", fill_type="solid")
    
    align_center = Alignment(horizontal="center", vertical="center", wrap_text=True)
    align_left = Alignment(horizontal="left", vertical="center")
    align_right = Alignment(horizontal="right", vertical="center")
    
    thin_border_side = Side(style="thin", color="CBD5E0")
    border_cell = Border(left=thin_border_side, right=thin_border_side, top=thin_border_side, bottom=thin_border_side)
    
    double_bottom_side = Side(style="double", color="1A365D")
    thick_top_side = Side(style="medium", color="1A365D")
    border_total = Border(left=thin_border_side, right=thin_border_side, top=thick_top_side, bottom=double_bottom_side)

    # Title rows
    ws.merge_cells("A1:L1")
    ws["A1"] = "LAPORAN HARIAN KANTIN SECABA RINDAM III/SILIWANGI"
    ws["A1"].font = font_title
    ws["A1"].alignment = align_center
    ws.row_dimensions[1].height = 30
    
    ws.merge_cells("A2:L2")
    status_str = "KUNCI / CLOSED" if (is_shift_closed(tanggal, db_path) if db_path else is_shift_closed(tanggal)) else "BUKA / ACTIVE"
    ws["A2"] = f"Tanggal Laporan: {tanggal}   |   Status Shift: {status_str}"
    ws["A2"].font = font_subtitle
    ws["A2"].alignment = align_center
    ws.row_dimensions[2].height = 20

    # Header Row 1 (Excel Row 4)
    headers_r1 = ["NO", "JENIS BARANG", "STOK BARANG", "", "", "", "", "Penjualan", "", "PEMBAYARAN", "", "LABA"]
    for col_idx, text in enumerate(headers_r1, 1):
        cell = ws.cell(row=4, column=col_idx, value=text)
        cell.font = font_header
        cell.fill = fill_header
        cell.alignment = align_center
        cell.border = border_cell
        
    # Header Row 2 (Excel Row 5)
    headers_r2 = ["", "", "SISA H-1", "BELI", "JUMLAH", "JUAL", "SISA", "HARGA JUAL", "TOTAL", "HARGA BELI", "TOTAL", ""]
    for col_idx, text in enumerate(headers_r2, 1):
        cell = ws.cell(row=5, column=col_idx, value=text)
        cell.font = font_header
        cell.fill = fill_header
        cell.alignment = align_center
        cell.border = border_cell

    # Merges for Header
    ws.merge_cells("A4:A5") # NO
    ws.merge_cells("B4:B5") # JENIS BARANG
    ws.merge_cells("C4:G4") # STOK BARANG
    ws.merge_cells("H4:I4") # Penjualan
    ws.merge_cells("J4:K4") # PEMBAYARAN
    ws.merge_cells("L4:L5") # LABA
    
    ws.row_dimensions[4].height = 20
    ws.row_dimensions[5].height = 20

    # Populate Data
    start_row = 6
    current_row = start_row
    item_no = 1
    current_category = None
    
    category_start_rows = []
    
    for item in data_list:
        # Jika kategori baru
        if item['nama_kategori'] != current_category:
            current_category = item['nama_kategori']
            # Tulis baris kategori
            ws.merge_cells(start_row=current_row, start_column=2, end_row=current_row, end_column=12)
            cat_cell = ws.cell(row=current_row, column=2, value=f"--- KATEGORI: {current_category.upper()} ---")
            cat_cell.font = font_category
            cat_cell.alignment = align_left
            
            # Format seluruh baris kategori
            for col_idx in range(1, 13):
                c = ws.cell(row=current_row, column=col_idx)
                c.fill = fill_category
                c.border = border_cell
                
            ws.row_dimensions[current_row].height = 22
            current_row += 1
            
        # Write data
        ws.cell(row=current_row, column=1, value=item_no).alignment = align_center
        ws.cell(row=current_row, column=2, value=item['nama_barang']).alignment = align_left
        
        # Stok Values
        ws.cell(row=current_row, column=3, value=item['sisa_h1']).alignment = align_center
        ws.cell(row=current_row, column=4, value=item['beli']).alignment = align_center
        
        # JUMLAH = SISA_H1 + BELI (Formula)
        ws.cell(row=current_row, column=5, value=f"=C{current_row}+D{current_row}").alignment = align_center
        
        ws.cell(row=current_row, column=6, value=item['jual']).alignment = align_center
        
        # SISA = JUMLAH - JUAL (Formula)
        ws.cell(row=current_row, column=7, value=f"=E{current_row}-F{current_row}").alignment = align_center
        
        # Prices
        cell_hj = ws.cell(row=current_row, column=8, value=item['harga_jual'])
        cell_hj.alignment = align_right
        cell_hj.number_format = '"Rp "#,##0'
        
        # TOTAL JUAL = JUAL * HARGA JUAL (Formula)
        cell_tj = ws.cell(row=current_row, column=9, value=f"=F{current_row}*H{current_row}")
        cell_tj.alignment = align_right
        cell_tj.number_format = '"Rp "#,##0'
        
        cell_hb = ws.cell(row=current_row, column=10, value=item['harga_beli'])
        cell_hb.alignment = align_right
        cell_hb.number_format = '"Rp "#,##0'
        
        # TOTAL BELI = BELI * HARGA BELI (Formula)
        cell_tb = ws.cell(row=current_row, column=11, value=f"=D{current_row}*J{current_row}")
        cell_tb.alignment = align_right
        cell_tb.number_format = '"Rp "#,##0'
        
        # LABA = TOTAL JUAL - TOTAL BELI (Formula)
        cell_laba = ws.cell(row=current_row, column=12, value=f"=I{current_row}-K{current_row}")
        cell_laba.alignment = align_right
        cell_laba.number_format = '"Rp "#,##0'
        
        # Borders and fonts
        for col_idx in range(1, 13):
            c = ws.cell(row=current_row, column=col_idx)
            c.font = font_data
            c.border = border_cell
            
        ws.row_dimensions[current_row].height = 20
        
        item_no += 1
        current_row += 1

    # Total Row (Excel Row = current_row)
    total_row = current_row
    ws.merge_cells(start_row=total_row, start_column=1, end_row=total_row, end_column=2)
    ws.cell(row=total_row, column=1, value="TOTAL KESELURUHAN").alignment = align_center
    
    # Formulas for totals
    ws.cell(row=total_row, column=3, value=f"=SUM(C6:C{total_row-1})").alignment = align_center
    ws.cell(row=total_row, column=4, value=f"=SUM(D6:D{total_row-1})").alignment = align_center
    ws.cell(row=total_row, column=5, value=f"=SUM(E6:E{total_row-1})").alignment = align_center
    ws.cell(row=total_row, column=6, value=f"=SUM(F6:F{total_row-1})").alignment = align_center
    ws.cell(row=total_row, column=7, value=f"=SUM(G6:G{total_row-1})").alignment = align_center
    
    # Prices column: total jual, total beli, total laba sum
    ws.cell(row=total_row, column=8, value="-").alignment = align_center
    
    cell_tot_jual = ws.cell(row=total_row, column=9, value=f"=SUM(I6:I{total_row-1})")
    cell_tot_jual.alignment = align_right
    cell_tot_jual.number_format = '"Rp "#,##0'
    
    ws.cell(row=total_row, column=10, value="-").alignment = align_center
    
    cell_tot_beli = ws.cell(row=total_row, column=11, value=f"=SUM(K6:K{total_row-1})")
    cell_tot_beli.alignment = align_right
    cell_tot_beli.number_format = '"Rp "#,##0'
    
    cell_tot_laba = ws.cell(row=total_row, column=12, value=f"=SUM(L6:L{total_row-1})")
    cell_tot_laba.alignment = align_right
    cell_tot_laba.number_format = '"Rp "#,##0'
    
    # Styles for total row
    for col_idx in range(1, 13):
        c = ws.cell(row=total_row, column=col_idx)
        c.font = font_total
        c.fill = fill_total
        c.border = border_total
        
    ws.row_dimensions[total_row].height = 25

    # Auto-adjust column widths
    for col in ws.columns:
        # Check values
        max_len = 0
        col_letter = get_column_letter(col[0].column)
        
        # Don't auto-fit merged A and B cells too wide due to title rows
        for cell in col:
            if cell.row > 3: # Skip title merged rows for length checking
                val_str = str(cell.value or '')
                if len(val_str) > max_len:
                    max_len = len(val_str)
                    
        # Apply padding
        ws.column_dimensions[col_letter].width = max(max_len + 5, 10)

    # Specific widths for columns to make it look premium
    ws.column_dimensions['A'].width = 6
    ws.column_dimensions['B'].width = 28
    ws.column_dimensions['C'].width = 12
    ws.column_dimensions['D'].width = 10
    ws.column_dimensions['E'].width = 12
    ws.column_dimensions['F'].width = 10
    ws.column_dimensions['G'].width = 12
    ws.column_dimensions['H'].width = 15
    ws.column_dimensions['I'].width = 18
    ws.column_dimensions['J'].width = 15
    ws.column_dimensions['K'].width = 18
    ws.column_dimensions['L'].width = 20

    wb.save(output_path)

def generate_pdf_keuangan(tanggal, output_path, db_path=None):
    from database import get_transaksi_keuangan_by_tanggal
    from reportlab.lib.colors import HexColor
    import locale
    
    data_list = get_transaksi_keuangan_by_tanggal(tanggal, db_path) if db_path else get_transaksi_keuangan_by_tanggal(tanggal)
    
    doc = SimpleDocTemplate(
        output_path,
        pagesize=A4, 
        leftMargin=40,
        rightMargin=40,
        topMargin=40,
        bottomMargin=40
    )
    
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        'TitleStyle',
        parent=styles['Heading1'],
        fontName='Helvetica-Bold',
        fontSize=16,
        leading=20,
        alignment=1,
        textColor=HexColor('#2c3e50'),
        spaceAfter=6
    )
    subtitle_style = ParagraphStyle(
        'SubtitleStyle',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=10,
        leading=14,
        alignment=1,
        textColor=HexColor('#7f8c8d'),
        spaceAfter=15
    )
    section_title_style = ParagraphStyle(
        'SectionTitle',
        parent=styles['Heading3'],
        fontName='Helvetica-Bold',
        fontSize=12,
        textColor=HexColor('#2c3e50'),
        spaceAfter=10
    )
    cell_style = ParagraphStyle(
        'CellStyle',
        parent=styles['Normal'],
        fontName='Helvetica',
        fontSize=10,
        leading=12
    )
    cell_style_center = ParagraphStyle('CellStyleCenter', parent=cell_style, alignment=1)
    
    # Custom Number formatting
    def fmt_num(val):
        if val == 0:
            return "-"
        return f"{val:,.0f}"

    story = []
    
    # --- HEADER ---
    story.append(Paragraph("LAPORAN KEUANGAN KANTIN", title_style))
    story.append(Paragraph(f"Periode/Tanggal: {tanggal}", subtitle_style))
    
    # Horizontal line
    story.append(Spacer(1, 10))
    # A line can be drawn using a table with 1 row and 1 col, with top border.
    line_table = Table([['']], colWidths=[doc.width])
    line_table.setStyle(TableStyle([
        ('LINEABOVE', (0,0), (-1,-1), 1, HexColor('#bdc3c7')),
    ]))
    story.append(line_table)
    story.append(Spacer(1, 15))
    
    story.append(Paragraph("Rincian Transaksi", section_title_style))
    
    # --- MAIN TABLE ---
    header_style = ParagraphStyle('HeaderStyle', parent=cell_style_center, fontName='Helvetica-Bold', textColor=colors.white)
    
    table_data = [[
        Paragraph("No", header_style),
        Paragraph("Jenis Transaksi", header_style),
        Paragraph("Keterangan", header_style),
        Paragraph("Masuk<br/>(Rp)", header_style),
        Paragraph("Keluar<br/>(Rp)", header_style)
    ]]
    
    total_masuk = 0
    total_keluar = 0
    
    for idx, row in enumerate(data_list, 1):
        masuk = row['nominal'] if row['jenis'] == 'PENDAPATAN' else 0
        keluar = row['nominal'] if row['jenis'] == 'PENGELUARAN' else 0
        
        total_masuk += masuk
        total_keluar += keluar
        
        ket = row['keterangan'] or "-"
        
        # Color formatting
        masuk_str = f"<font color='#27ae60'><b>{fmt_num(masuk)}</b></font>" if masuk > 0 else "-"
        keluar_str = f"<font color='#c0392b'><b>{fmt_num(keluar)}</b></font>" if keluar > 0 else "-"
        
        table_data.append([
            Paragraph(str(idx), cell_style_center),
            Paragraph(row['kategori'], cell_style),
            Paragraph(ket, cell_style),
            Paragraph(masuk_str, ParagraphStyle('R', parent=cell_style, alignment=2)),
            Paragraph(keluar_str, ParagraphStyle('R', parent=cell_style, alignment=2))
        ])
        
    t = Table(table_data, colWidths=[30, 110, 195, 90, 90])
    t.setStyle(TableStyle([
        ('BACKGROUND', (0, 0), (-1, 0), HexColor('#34495e')),
        ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('GRID', (0, 0), (-1, -1), 0.5, HexColor('#bdc3c7')),
        ('BOTTOMPADDING', (0, 0), (-1, 0), 8),
        ('TOPPADDING', (0, 0), (-1, 0), 8),
    ]))
    
    for i in range(1, len(table_data)):
        t.setStyle(TableStyle([
            ('BOTTOMPADDING', (0, i), (-1, i), 8),
            ('TOPPADDING', (0, i), (-1, i), 8),
        ]))
        
    story.append(t)
    story.append(Spacer(1, 20))
    
    # --- SUMMARY TABLE ---
    laba_bersih = total_masuk - total_keluar
    
    summary_data = [
        [
            Paragraph("Total Pendapatan", cell_style), 
            Paragraph(f"<font color='#27ae60'><b>Rp<br/>{fmt_num(total_masuk)}</b></font>", ParagraphStyle('R', parent=cell_style, alignment=2))
        ],
        [
            Paragraph("Total Pengeluaran", cell_style), 
            Paragraph(f"<font color='#c0392b'><b>Rp<br/>{fmt_num(total_keluar)}</b></font>", ParagraphStyle('R', parent=cell_style, alignment=2))
        ],
        [
            Paragraph("<b>LABA BERSIH (Sisa<br/>Uang)</b>", cell_style), 
            Paragraph(f"<b>Rp<br/>{fmt_num(laba_bersih)}</b>", ParagraphStyle('R', parent=cell_style, alignment=2))
        ]
    ]
    
    # Create the summary table and align it to the right
    t_sum = Table(summary_data, colWidths=[150, 130])
    t_sum.setStyle(TableStyle([
        ('GRID', (0, 0), (-1, -1), 0.5, HexColor('#bdc3c7')),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('BOTTOMPADDING', (0, 0), (-1, -1), 10),
        ('TOPPADDING', (0, 0), (-1, -1), 10),
        ('BACKGROUND', (0, 2), (-1, 2), HexColor('#e2e6e9')), # Grey background for Laba
    ]))
    
    # Wrap in a parent table to push it to the right
    parent_t_sum = Table([['', t_sum]], colWidths=[235, 280])
    story.append(parent_t_sum)
    
    doc.build(story)
    return output_path

