<?php
defined('BASEPATH') or exit('No direct script access allowed');

$laporan = array();
$totalPajak = 0;
$totalTransaksi = 0;
$totalBayar = 0;
$totalDiskon = 0;
$totalPiutang = 0;

if (!empty($posts)) {
    foreach ($posts as $row) {
        $dataBayar = bayar($row['id_invoice']);
        $jumlahBayar = (is_array($dataBayar) && isset($dataBayar['Totalbayar']))
            ? round((float) $dataBayar['Totalbayar'])
            : 0;

        $jumlahTransaksi = round(
            (float) sumOrder($row['id_invoice']) - (float) totalDiskon($row['id_invoice'])
        );
        $diskonTransaksi = round((float) $row['potongan_harga']);

        $dataPiutang = sumPiutang($row['id_invoice']);
        $piutangTercatat = (is_array($dataPiutang) && isset($dataPiutang[0]['piutang']))
            ? round((float) $dataPiutang[0]['piutang'])
            : round((float) $dataPiutang);

        if ((float) $row['pajak'] > 0) {
            $jumlahPajak = round(($jumlahTransaksi * (float) $row['pajak']) / 100);
            $jumlahPiutang = round(
                $jumlahTransaksi + $jumlahPajak - $jumlahBayar - $diskonTransaksi
            );
        } else {
            $jumlahPajak = 0;
            $jumlahPiutang = round(
                $jumlahTransaksi - $piutangTercatat - $diskonTransaksi
            );
        }

        if ($row['status'] === 'batal') {
            $jumlahPajak = 0;
            $jumlahTransaksi = 0;
            $jumlahBayar = 0;
            $diskonTransaksi = 0;
            $jumlahPiutang = 0;
        }

        $namaPelanggan = ((int) $row['tampil'] === 0) ? $row['nama'] : $row['perusahaan'];
        $rincianBarang = array();
        $detail = detail_order($row['id_invoice'], 'semua');

        if (!empty($detail)) {
            foreach ($detail as $item) {
                $subtotalKotor = (float) $item->jumlah * (float) $item->harga;
                $diskonItem = ((float) $item->diskon > 0)
                    ? ($subtotalKotor * (float) $item->diskon) / 100
                    : 0;
                $dataBahan = getDetailBahan($item->id_bahan);

                $rincianBarang[] = array(
                    'nama_barang' => (is_object($dataBahan) && isset($dataBahan->title))
                        ? $dataBahan->title
                        : '',
                    'harga' => round((float) $item->harga),
                    'qty' => (float) $item->jumlah,
                    'total' => round($subtotalKotor - $diskonItem)
                );
            }
        }

        $laporan[] = array(
            'no_transaksi' => $row['id_transaksi'],
            'tanggal_order' => $row['tgl_trx'],
            'kasir' => $row['kasir'],
            'pelanggan' => $namaPelanggan,
            'rincian' => $rincianBarang,
            'pajak' => $jumlahPajak,
            'total_transaksi' => $jumlahTransaksi,
            'total_bayar' => $jumlahBayar,
            'diskon' => $diskonTransaksi,
            'piutang' => $jumlahPiutang
        );

        $totalPajak += $jumlahPajak;
        $totalTransaksi += $jumlahTransaksi;
        $totalBayar += $jumlahBayar;
        $totalDiskon += $diskonTransaksi;
        $totalPiutang += $jumlahPiutang;
    }
}

$formatTanggal = function ($tanggal) {
    return (!empty($tanggal) && $tanggal !== '0000-00-00' && strtotime($tanggal))
        ? dtimes($tanggal, false, false)
        : '-';
};
$formatQty = function ($qty) {
    return ((float) $qty == floor((float) $qty))
        ? (string) (int) $qty
        : rtrim(rtrim(number_format((float) $qty, 2, ',', '.'), '0'), ',');
};
$e = function ($value) {
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
};

$periodeDari = (!empty($dari) && strtotime($dari)) ? date('d/m/Y', strtotime($dari)) : '-';
$periodeSampai = (!empty($sampai) && strtotime($sampai)) ? date('d/m/Y', strtotime($sampai)) : '-';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title><?=$e($title);?></title>
    <style>
        @page { margin: 22px 22px 31px; }
        * { box-sizing: border-box; }
        body {
            margin: 0;
            color: #344054;
            font-family: DejaVu Sans, Arial, sans-serif;
            font-size: 7px;
        }
        .report-header {
            margin-bottom: 10px;
            padding: 9px 12px;
            border-bottom: 2px solid #586070;
            background: #f5f8fb;
            text-align: center;
        }
        .report-header .company {
            margin-bottom: 2px;
            color: #1769e8;
            font-size: 8px;
            font-weight: bold;
        }
        .report-header h1 {
            margin: 0 0 3px;
            color: #1d2939;
            font-size: 15px;
            line-height: 1.2;
        }
        .report-header .period {
            color: #667085;
            font-size: 7px;
        }
        .summary-cards {
            width: 100%;
            margin: 0 0 10px;
            border-collapse: separate;
            border-spacing: 4px 0;
            table-layout: fixed;
        }
        .summary-cards td {
            width: 20%;
            padding: 0;
            border: 0;
            vertical-align: top;
        }
        .summary-card {
            height: 38px;
            padding: 7px 8px;
            border: 1px solid #dfe5ee;
            border-left-width: 4px;
            background: #fff;
        }
        .summary-card .card-label {
            margin-bottom: 3px;
            color: #667085;
            font-size: 6.3px;
            font-weight: bold;
            line-height: 1.1;
        }
        .summary-card .card-value {
            color: #1d2939;
            font-size: 10px;
            font-weight: bold;
            line-height: 1.1;
            white-space: nowrap;
        }
        .card-transaksi { border-left-color: #6657e8; background: #f7f6ff; }
        .card-bayar { border-left-color: #299dea; background: #f3faff; }
        .card-piutang { border-left-color: #9146e8; background: #faf6ff; }
        .card-pajak { border-left-color: #20bfb8; background: #f3fffe; }
        .card-diskon { border-left-color: #ff7f32; background: #fff8f3; }
        table {
            border-collapse: collapse;
            table-layout: fixed;
        }
        .report-table {
            width: 100%;
            border: 1px solid #dfe5ee;
        }
        .report-table > thead { display: table-header-group; }
        .report-table > tfoot { display: table-row-group; }
        .report-table > tbody > tr { page-break-inside: avoid; }
        .report-table > tbody.transaction-group { page-break-inside: avoid; }
        .report-table > thead > tr:first-child > th {
            padding: 6px 3px;
            border: 1px solid #707382;
            background: #5a5b68;
            color: #fff;
            font-weight: bold;
            line-height: 1.25;
            text-align: center;
            vertical-align: middle;
        }
        .report-table > thead > tr.detail-header > th {
            padding: 4px 2px;
            border: 1px solid #707382;
            background: #5a5b68;
            color: #fff;
            font-size: 6.3px;
            font-weight: bold;
            line-height: 1.15;
            text-align: center;
            vertical-align: middle;
        }
        .report-table > tbody > tr > td {
            padding: 5px 3px;
            border: 1px solid #dfe5ee;
            background: #fff;
            vertical-align: middle;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }
        .report-table > tbody > tr.transaction-even > td {
            background: #fbfcfe;
        }
        .report-table > tbody > tr.transaction-start > td {
            border-top-color: #cbd3df;
        }
        .center { text-align: center; }
        .right { text-align: right; white-space: nowrap; }
        .customer {
            color: #31b84d;
            line-height: 1.25;
        }
        .item-name {
            padding-left: 7px !important;
            line-height: 1.25;
            text-align: left;
        }
        .item-number {
            padding-right: 3px !important;
            font-size: 6.4px;
            text-align: right;
            white-space: nowrap;
        }
        .item-qty {
            padding: 3px 1px !important;
            text-align: center;
            white-space: nowrap;
        }
        .total-row td {
            padding: 5px 4px;
            border: 1px solid #dfe5ee;
            border-top: 1px solid #cbd3df;
            background: #f8fafc;
            font-weight: bold;
            vertical-align: middle;
        }
        .total-label {
            color: #667085;
            font-size: 6px;
            font-weight: normal !important;
            text-align: left;
        }
        .empty {
            padding: 16px !important;
            color: #667085;
            text-align: center;
        }
        .result-count {
            margin-top: 8px;
            color: #344054;
            font-size: 8px;
        }
        .footer {
            position: fixed;
            right: 0;
            bottom: -20px;
            left: 0;
            padding-top: 4px;
            border-top: 1px solid #dfe5ee;
            color: #667085;
            font-size: 6px;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="footer">
        Rincian Penjualan &mdash; Periode <?=$e($periodeDari);?> s.d. <?=$e($periodeSampai);?>
    </div>

    <div class="report-header">
        <div class="company"><?=$e(info()['title']);?></div>
        <h1>RINCIAN PENJUALAN</h1>
        <div class="period">Periode: <?=$e($periodeDari);?> s.d. <?=$e($periodeSampai);?></div>
    </div>

    <table class="summary-cards">
        <tr>
            <td>
                <div class="summary-card card-transaksi">
                    <div class="card-label">Total Transaksi</div>
                    <div class="card-value"><?=rp($totalTransaksi);?></div>
                </div>
            </td>
            <td>
                <div class="summary-card card-bayar">
                    <div class="card-label">Total Bayar</div>
                    <div class="card-value"><?=rp($totalBayar);?></div>
                </div>
            </td>
            <td>
                <div class="summary-card card-piutang">
                    <div class="card-label">Total Piutang</div>
                    <div class="card-value"><?=rp($totalPiutang);?></div>
                </div>
            </td>
            <td>
                <div class="summary-card card-pajak">
                    <div class="card-label">Total Pajak</div>
                    <div class="card-value"><?=rp($totalPajak);?></div>
                </div>
            </td>
            <td>
                <div class="summary-card card-diskon">
                    <div class="card-label">Total Diskon</div>
                    <div class="card-value"><?=rp($totalDiskon);?></div>
                </div>
            </td>
        </tr>
    </table>

    <table class="report-table">
        <colgroup>
            <col style="width:3%">
            <col style="width:8%">
            <col style="width:9%">
            <col style="width:7%">
            <col style="width:8%">
            <col style="width:17%">
            <col style="width:6%">
            <col style="width:4%">
            <col style="width:7%">
            <col style="width:5%">
            <col style="width:7%">
            <col style="width:6%">
            <col style="width:5%">
            <col style="width:8%">
        </colgroup>
        <thead>
            <tr>
                <th rowspan="2">No</th>
                <th rowspan="2">No Trx</th>
                <th rowspan="2">Tanggal Order</th>
                <th rowspan="2">Kasir</th>
                <th rowspan="2">Pelanggan</th>
                <th colspan="4">Rincian Penjualan Barang</th>
                <th rowspan="2">Pajak</th>
                <th rowspan="2">Total<br>Transaksi</th>
                <th rowspan="2">Total<br>Bayar</th>
                <th rowspan="2">Diskon</th>
                <th rowspan="2">Piutang</th>
            </tr>
            <tr class="detail-header">
                <th>Nama Barang</th>
                <th>Harga</th>
                <th>Qty</th>
                <th>Total</th>
            </tr>
        </thead>
        <?php if (!empty($laporan)) { ?>
            <?php foreach ($laporan as $index => $row) {
                $items = !empty($row['rincian'])
                    ? $row['rincian']
                    : array(array('nama_barang' => 'Tidak ada item', 'harga' => 0, 'qty' => 0, 'total' => 0));
                $rowspan = count($items);
                $stripeClass = (($index + 1) % 2 === 0) ? ' transaction-even' : '';
            ?>
            <tbody class="transaction-group">
            <?php
                foreach ($items as $itemIndex => $item) {
                    $startClass = ($itemIndex === 0) ? ' transaction-start' : '';
            ?>
            <tr class="<?=$startClass.$stripeClass;?>">
                <?php if ($itemIndex === 0) { ?>
                <td rowspan="<?=$rowspan;?>" class="center"><?=$index + 1;?></td>
                <td rowspan="<?=$rowspan;?>" class="center"><?=$e($row['no_transaksi']);?></td>
                <td rowspan="<?=$rowspan;?>" class="center"><?=$e($formatTanggal($row['tanggal_order']));?></td>
                <td rowspan="<?=$rowspan;?>" class="center"><?=$e($row['kasir']);?></td>
                <td rowspan="<?=$rowspan;?>"><span class="customer"><?=$e($row['pelanggan']);?></span></td>
                <?php } ?>
                <td class="item-name"><?=$e($item['nama_barang']);?></td>
                <td class="item-number"><?=rp($item['harga']);?></td>
                <td class="item-qty"><?=$e($formatQty($item['qty']));?></td>
                <td class="item-number"><?=rp($item['total']);?></td>
                <?php if ($itemIndex === 0) { ?>
                <td rowspan="<?=$rowspan;?>" class="right"><?=rp($row['pajak']);?></td>
                <td rowspan="<?=$rowspan;?>" class="right"><?=rp($row['total_transaksi']);?></td>
                <td rowspan="<?=$rowspan;?>" class="right"><?=rp($row['total_bayar']);?></td>
                <td rowspan="<?=$rowspan;?>" class="right"><?=rp($row['diskon']);?></td>
                <td rowspan="<?=$rowspan;?>" class="right"><?=rp($row['piutang']);?></td>
                <?php } ?>
            </tr>
            <?php
                }
            ?>
            </tbody>
            <?php
            } ?>
        <?php } else { ?>
            <tbody>
            <tr><td colspan="14" class="empty">Data belum ada untuk filter yang dipilih.</td></tr>
            </tbody>
        <?php } ?>
        <tfoot>
            <tr class="total-row">
                <td colspan="9" class="total-label">Total keseluruhan</td>
                <td class="right"><?=rp($totalPajak);?></td>
                <td class="right"><?=rp($totalTransaksi);?></td>
                <td class="right"><?=rp($totalBayar);?></td>
                <td class="right"><?=rp($totalDiskon);?></td>
                <td class="right"><?=rp($totalPiutang);?></td>
            </tr>
        </tfoot>
    </table>

    <div class="result-count">Menampilkan: <?=count($laporan);?></div>
</body>
</html>
