// internal/utils/pdf_export.go
package utils

import (
	"bytes"
	"fmt"

	"github.com/jung-kurt/gofpdf"
)

// PDFExporter handles PDF generation
type PDFExporter struct {
	pdf *gofpdf.Fpdf
}

// NewPDFExporter creates a new PDF exporter
func NewPDFExporter() *PDFExporter {
    pdf := gofpdf.New("P", "mm", "A4", "")
    pdf.AddPage()
    
    // ✅ Coba gunakan font built-in yang pasti ada
    pdf.SetFont("Helvetica", "", 12)  // Ganti dari "Arial" ke "Helvetica"

    return &PDFExporter{
        pdf: pdf,
    }
}

// AddTitle adds a title to the PDF
func (e *PDFExporter) AddTitle(title string) {
	e.pdf.SetFont("Arial", "B", 16)
	e.pdf.Cell(0, 10, title)
	e.pdf.Ln(12)
	e.pdf.SetFont("Arial", "", 12)
}

// AddSubtitle adds a subtitle to the PDF
func (e *PDFExporter) AddSubtitle(subtitle string) {
	e.pdf.SetFont("Arial", "I", 11)
	e.pdf.Cell(0, 8, subtitle)
	e.pdf.Ln(10)
	e.pdf.SetFont("Arial", "", 12)
}

// AddText adds regular text
func (e *PDFExporter) AddText(text string) {
	e.pdf.SetFont("Arial", "", 10)
	e.pdf.MultiCell(0, 6, text, "", "", false)
	e.pdf.Ln(4)
}

// AddNewLine adds a new line
func (e *PDFExporter) AddNewLine() {
	e.pdf.Ln(6)
}

// AddTable adds a table to the PDF
func (e *PDFExporter) AddTable(headers []string, data [][]string) {
	// Calculate column widths
	pageWidth, _ := e.pdf.GetPageSize()
	margins := 20.0 // Left + Right margins
	tableWidth := pageWidth - margins
	colWidth := tableWidth / float64(len(headers))

	// Add headers
	e.pdf.SetFont("Arial", "B", 10)
	e.pdf.SetFillColor(200, 200, 200)
	for _, header := range headers {
		e.pdf.CellFormat(colWidth, 8, header, "1", 0, "C", true, 0, "")
	}
	e.pdf.Ln(-1)

	// Add data rows
	e.pdf.SetFont("Arial", "", 9)
	e.pdf.SetFillColor(255, 255, 255)
	
	fill := false
	for _, row := range data {
		for _, cell := range row {
			if fill {
				e.pdf.SetFillColor(245, 245, 245)
			} else {
				e.pdf.SetFillColor(255, 255, 255)
			}
			e.pdf.CellFormat(colWidth, 7, cell, "1", 0, "L", true, 0, "")
		}
		e.pdf.Ln(-1)
		fill = !fill
	}
}

// AddPageNumber adds page numbers
func (e *PDFExporter) AddPageNumber() {
	e.pdf.AliasNbPages("")
	e.pdf.SetY(-15)
	e.pdf.SetFont("Arial", "I", 8)
	e.pdf.CellFormat(0, 10, fmt.Sprintf("Halaman %d/{nb}", e.pdf.PageNo()), "", 0, "C", false, 0, "")
}

// Output returns the PDF as bytes
func (e *PDFExporter) Output() *bytes.Buffer {
	var buf bytes.Buffer
	err := e.pdf.Output(&buf)
	if err != nil {
		return nil
	}
	return &buf
}