<?php 
session_start();
ob_start();

// Define constants for better performance and maintenance
define('DATE_FORMAT', 'd-m-Y');
define('NUMBER_FORMAT_DECIMALS', 0);

// Helper function for number formatting to reduce repetition
function formatNumber($number, $decimals = NUMBER_FORMAT_DECIMALS) {
    return number_format($number, $decimals);
}

// Helper function for kolektibilitas calculation
function getKolektibilitas($daysPastDue, $flat_t_margin) {
    if ($flat_t_margin <= 0) return 'L';
    if ($daysPastDue <= 30) return 'D';
    if ($daysPastDue <= 45) return 'D';
    return 'M';
}

// Initialize summary variables
$summary = [
    'plafond' => 0,
    'bakidebet' => 0,
    'margin' => 0,
    'pokok' => 0,
    'total' => 0
];
?>
<!DOCTYPE html>
<html>
<head>
    <title>Cetak PDF</title>
    <style>
        /* Combine all styles for better performance */
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            padding: 4px;
            font-size: 12px;
        }
        .header-text {
            font-family: Arial;
            text-align: center;
            margin: 0px;
        }
        .centered {
            text-align: center;
        }
        .right-aligned {
            text-align: right;
        }
        .header-cell {
            text-align: center;
            background: #ddd;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <?php     
    $periode = date('Y-m-d', strtotime($_SESSION['tuggakan']['periode2']));
    $sqlt = $_SESSION['tuggakan']['kode']['sqlt'];
    $kode = $_SESSION['tuggakan']['kode']['kode'];
    
    ?>
    
    <!-- Header Section -->
    <p class="header-text">PT. MENARA SEMBILAN SEJAHTERA</p>
    <p class="header-text" style="font-size:13px;">KANTOR <?php echo $_SESSION['kantor']; ?></p>
    <p class="header-text" style="font-size:13px;">LAPORAN TUNGGAKAN</p>
    <p class="header-text" style="font-size:13px;"><?php echo date('d-m-Y', strtotime($periode)); ?></p>

    <!-- Main Table -->
    <table border="1">
        <thead>
            <tr>
                <th class="header-cell" style="width:3%">No.</th>
                <th class="header-cell" style="width:5%">Tgl</th>
                <th class="header-cell" style="width:9%">Rekening</th>
                <th class="header-cell" style="width:11%">Nama</th>
                <th class="header-cell" style="width:9%">Plafond</th>
                <th class="header-cell" style="width:9%">Bakidebet</th>
                <th class="header-cell" style="width:9%">Barang</th>
                <th class="header-cell" style="width:7%">Jaminan</th>
                <th class="header-cell" style="width:7%">T Ujroh</th>
                
                <th class="header-cell" style="width:3%">Kol</th>
            </tr>
        </thead>
        <tbody>
            <?php
            require_once '../koneksi.php';
            error_reporting(0);

            // Use prepared statement for better performance and security
            $stmt = mysqli_prepare($koneksi, $sqlt);
        if ($stmt) {
            mysqli_stmt_bind_param($stmt, "ss", $periode, $kode);
        }
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
            
            $no = 0;
            $currentDate = new DateTime($periode);

            while ($data = mysqli_fetch_assoc($result)) {
                $no++;
                
                // Extract data and calculate values
                $plafond = $data['plafond'];
                $margin = $data['margin'];
                $jangkawaktu = $data['jangkawaktu'];
                
                // Calculate installment details
                $angsuran_margin = $plafond * $margin / 100;
                $angsuran_pokok = $plafond / $jangkawaktu;
                
                // Calculate days difference
                $startDate = new DateTime($data['tgl']);
                $daysDiff = $startDate->diff($currentDate)->days;
                $kolPeriod = floor($daysDiff / 15);
                
                // Calculate tunggakan
                $flat_t_margin = ($angsuran_margin * 3) - $data['tmargin'];
                //$flat_t_margin = ($angsuran_margin * $kolPeriod) - $data['tmargin'];
                $flat_t_pokok = ($angsuran_pokok * $kolPeriod) - $data['tpokok'];
                $tot_tunggakan = $flat_t_margin + $flat_t_pokok;
                
                // Update summary
                $summary['plafond'] += $plafond;
                $summary['bakidebet'] += $data['bakidebet'];
                $summary['margin'] += $flat_t_margin;
                $summary['pokok'] += $flat_t_pokok;
                $summary['total'] += $tot_tunggakan;
                
                // Get kolektibilitas
                $kolektibilitas = getKolektibilitas($daysDiff, $flat_t_margin);
                ?>
                <tr>
                    <td class="centered"><?php echo $no; ?></td>
                    <td class="centered"><?php echo date(DATE_FORMAT, strtotime($data['tgl'])); ?></td>
                    <td><?php echo htmlspecialchars($data['rekening']); ?></td>
                    <td><?php echo htmlspecialchars(substr($data['nama'], 1, 14)); ?></td>
                    <td class="right-aligned"><?php echo formatNumber($plafond); ?></td>
                    <td class="right-aligned"><?php echo formatNumber($data['bakidebet'], 2); ?></td>
                    <td><?php echo htmlspecialchars(substr($data['barang'],0,40)); ?></td>
                    <td><?php echo htmlspecialchars(substr($data['jaminan'],0,20)); ?></td>
                    <!-- <td class="right-aligned"><?php echo formatNumber($flat_t_pokok); ?></td> -->
                    <td class="right-aligned"><?php echo formatNumber($flat_t_margin); ?></td>
                    <!-- <td class="right-aligned"><?php echo formatNumber($tot_tunggakan); ?></td> -->
                    <td class="centered"><?php echo $kolektibilitas; ?></td>
                </tr>
            <?php } 
            mysqli_stmt_close($stmt);
            mysqli_close($koneksi);
            ?>
            
            <!-- Summary Row -->
            <tr>
                <td colspan="4" class="centered"><b>Jumlah</b></td>
                <td class="right-aligned"><b><?php echo formatNumber($summary['plafond']); ?></b></td>
                <td class="right-aligned"><b><?php echo formatNumber($summary['bakidebet']); ?></b></td>
                <td></td>
                <td class="right-aligned"><b><?php echo formatNumber($summary['pokok']); ?></b></td>
                <td class="right-aligned"><b><?php echo formatNumber($summary['margin']); ?></b></td>
                <td class="right-aligned"><b><?php echo formatNumber($summary['total']); ?></b></td>
                <td></td>
            </tr>
        </tbody>
    </table>
</body>
</html>
<?php
$html = ob_get_clean();

require '../html2pdf/autoload.php';
$pdf = new Spipu\Html2Pdf\Html2Pdf('L', 'A4', 'en');
$pdf->WriteHTML($html);
$pdf->Output('Laporan_Tunggakan.pdf', 'D');
?>