package com.example.kasirapp

import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import android.os.Bundle
import android.os.Environment
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class ReceiptPreviewActivity : AppCompatActivity() {

    private lateinit var receiptText: String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_receipt_preview)

        val tvReceipt = findViewById<TextView>(R.id.tv_receipt)
        val btnPrintPdf = findViewById<Button>(R.id.btn_print_pdf)

        receiptText = intent.getStringExtra("receipt_text") ?: ""
        tvReceipt.text = receiptText

        btnPrintPdf.setOnClickListener {
            createPdf(receiptText)
        }
    }

    private fun createPdf(text: String) {
        val document = PdfDocument()
        val pageInfo = PdfDocument.PageInfo.Builder(300, 600, 1).create()
        val page = document.startPage(pageInfo)
        val canvas = page.canvas
        val paint = Paint()
        paint.textSize = 8f

        var y = 20f
        for (line in text.split("\n")) {
            canvas.drawText(line, 10f, y, paint)
            y += paint.descent() - paint.ascent()
        }

        document.finishPage(page)

        val fileName = "struk_${System.currentTimeMillis()}.pdf"
        val file = File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), fileName)

        try {
            document.writeTo(FileOutputStream(file))
            Toast.makeText(this, "PDF berhasil dibuat: ${file.absolutePath}", Toast.LENGTH_LONG).show()
            openPdf(file)
        } catch (e: IOException) {
            e.printStackTrace()
            Toast.makeText(this, "Gagal membuat PDF: ${e.message}", Toast.LENGTH_SHORT).show()
        } finally {
            document.close()
        }
    }

    private fun openPdf(file: File) {
        val uri = FileProvider.getUriForFile(this, "${applicationContext.packageName}.provider", file)
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setDataAndType(uri, "application/pdf")
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

        try {
            startActivity(intent)
        } catch (e: ActivityNotFoundException) {
            Toast.makeText(this, "Tidak ada aplikasi untuk membuka PDF", Toast.LENGTH_SHORT).show()
        }
    }
}
