<?php include "top.php";

function format_report_date($value)
{
    if (empty($value) || $value === '0000-00-00') {
        return '-';
    }
    $dt = date_create($value);
    return $dt ? date_format($dt, 'd-m-Y') : $value;
}

$stdt = mysqli_real_escape_string($con, $_POST['stdt'] ?? date('Y-m-d'));
$enddt = mysqli_real_escape_string($con, $_POST['enddt'] ?? date('Y-m-d'));
$paytype = mysqli_real_escape_string($con, $_POST['paytype'] ?? '0');
$logusers = trim($_POST['logusers'] ?? '0') === '' ? '0' : mysqli_real_escape_string($con, $_POST['logusers']);
$selectedLineman = mysqli_real_escape_string($con, $_POST['lineman'] ?? '0');
$csadded = $_SESSION['murgibhai'] ?? '';
$userLogin = f(q("SELECT * FROM tbl_login WHERE l_uid='$csadded'"));
$ltype = $userLogin['l_type'];
$currentLinemanId = $userLogin['l_id'];

$filterLineman = $selectedLineman;
if ($ltype != '1') {
    $filterLineman = $currentLinemanId;
}

$linemanLabel = 'All Lineman';
if ($filterLineman != '0') {
    $linemanInfo = f(q("SELECT * FROM tbl_login WHERE l_id='$filterLineman'"));
    $linemanLabel = $linemanInfo['l_name'] ?? 'Lineman';
}

$comname = 'All Company';
if ($logusers != '0') {
    $getcom = f(q("SELECT * FROM tbl_company WHERE c_id='$logusers'"));
    $comname = $getcom['c_name'] ?? 'Company';
}

$displayStd = format_report_date($stdt);
$displayEnd = format_report_date($enddt);

$conditions = [
    "a.blid=b.trn_billid",
    "a.bl_payamt>0",
    "a.bl_paydt BETWEEN '$stdt' AND '$enddt'",
];
if ($paytype != '0') {
    $conditions[] = "a.bl_paymd='$paytype'";
}
if ($logusers != '0') {
    $conditions[] = "a.bl_com='$logusers'";
}
if ($filterLineman != '0') {
    $conditions[] = "a.bl_line='$filterLineman'";
}

$sqlq = "SELECT * FROM `cbill` a, `tbl_trans` b WHERE " . implode(' AND ', $conditions);
$query = mysqli_query($con, $sqlq);

$reportRows = [];
$total_billamt = 0;
$total_paidamt = 0;
$counter = 0;
while ($arrc = mysqli_fetch_assoc($query)) {
    $counter++;
    $row = f(q("SELECT * FROM `adduser` WHERE id='{$arrc['bl_cid']}'"));
    $billamt = floatval($arrc['bl_amt']) + floatval($arrc['bl_prevdue']);
    $total_billamt += $billamt;
    $total_paidamt += floatval($arrc['trn_amt']);
    $companyName = '';
    if ($logusers == '0') {
        $company = f(q("SELECT * FROM `tbl_company` WHERE c_id='{$row['com_id']}'"));
        $companyName = $company['c_name'] ?? '';
    }
    $reportRows[] = [
        'company' => $companyName,
        'custid' => $row['custid'],
        'name' => $row['name'],
        'phone' => $row['phone'],
        'area' => $row['area_name'],
        'address' => $row['address'],
        'start_date' => format_report_date($arrc['bl_stdt']),
        'end_date' => format_report_date($arrc['bl_expiry']),
        'bill_amt' => $billamt,
        'paid_amt' => floatval($arrc['trn_amt']),
        'pay_date' => format_report_date($arrc['bl_paydt']),
    ];
}

ob_start();
$displayCompany = 0;
$colspan = $displayCompany ? 9 : 8;
?>
<table id="reportTable" class="stripe">
    <thead>
        <tr>
            <th class="table-plus datatable-nosort">Sl. No</th>
            <?php if ($displayCompany) { ?>
                <th>Company</th><?php } ?>
            <th>Customer Id</th>
            <th>Customer Name</th>
            <th>Phone</th>
            <th>Area</th>
            <th class="address-wrap">Address</th>
            <th>Start Date</th>
            <th>End Date</th>
            <th>Bill Amt (incl Prev Due)</th>
            <th>Paid Amt</th>
            <th>Pay Date</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($reportRows as $index => $row) { ?>
            <tr>
                <td class="table-plus"><?= $index + 1 ?></td>
                <?php if ($displayCompany) { ?>
                    <td class="company-wrap"><?= htmlspecialchars($row['company'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                <?php } ?>
                <td><?= htmlspecialchars($row['custid'], ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($row['name'], ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($row['phone'], ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($row['area'] ?? '', ENT_QUOTES, 'UTF-8') ?></td>
                <td class="address-wrap"><?= htmlspecialchars($row['address'], ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($row['start_date'], ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($row['end_date'], ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= number_format($row['bill_amt'], 2) ?></td>
                <td><?= number_format($row['paid_amt'], 2) ?></td>
                <td><?= htmlspecialchars($row['pay_date'], ENT_QUOTES, 'UTF-8') ?></td>
            </tr>
        <?php } ?>
        <tr class="total-row">
            <td colspan="<?= $colspan ?>"><strong>Total</strong></td>
            <td><strong><?= number_format($total_billamt, 2) ?></strong></td>
            <td><strong><?= number_format($total_paidamt, 2) ?></strong></td>
            <td></td>
        </tr>
    </tbody>
</table>
<?php
$reportTableHtml = ob_get_clean();
$isPdfExport = !empty($_POST['export_pdf']);
if ($isPdfExport) {
    require_once dirname(__FILE__) . '/dompdf/autoload.inc.php';
    $dompdf = new \Dompdf\Dompdf();
    $pdfStyle = '<style>body{font-family:Arial,sans-serif;}table{width:100%;border-collapse:collapse;}th,td{border:1px solid #e2e1e1;padding:6px;font-size:11px;}thead th{background:#bad5e4;} .address-wrap,.company-wrap{max-width:200px;word-wrap:break-word;word-break:break-word;white-space:normal;} .total-row td{background:#e6f7ff;font-weight:bold;}@page{size:A4 portrait;margin:10mm;} </style>';
    $pdfHeader = '<div style="text-align:center;margin-bottom:15px;"><h4>Payment Report ' . ($paytype != '0' ? "({$paytype})" : '') . ' from ' . $displayStd . ' to ' . $displayEnd . ' for ' . htmlspecialchars($comname, ENT_QUOTES, 'UTF-8') . '</h4><p>Lineman: ' . htmlspecialchars($linemanLabel, ENT_QUOTES, 'UTF-8') . '</p></div>';
    $dompdf->loadHtml('<html><head><meta charset="UTF-8">' . $pdfStyle . '</head><body>' . $pdfHeader . $reportTableHtml . '</body></html>');
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream("payment-report-{$stdt}-{$enddt}.pdf", ['Attachment' => false]);
    exit;
}
?>
<!DOCTYPE html>
<html>

<head>
    <?php include('include/head.php'); ?>
    <title>Payment Report for <?= htmlspecialchars($stdt, ENT_QUOTES, 'UTF-8') ?> and
        <?= htmlspecialchars($enddt, ENT_QUOTES, 'UTF-8') ?> for <?= htmlspecialchars($comname, ENT_QUOTES, 'UTF-8') ?>
    </title>
    <link rel="stylesheet" type="text/css"
        href="https://sarmac.b-cdn.net/plugins/datatables/media/css/jquery.dataTables.css">
    <link rel="stylesheet" type="text/css"
        href="https://sarmac.b-cdn.net/plugins/datatables/media/css/dataTables.bootstrap4.css">
    <link rel="stylesheet" type="text/css"
        href="https://sarmac.b-cdn.net/plugins/datatables/media/css/responsive.dataTables.css">
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
    <style type="text/css">
        th {
            font-size: 12px !important;
        }

        td {
            font-size: 11px !important;
            border: 1px solid #e2e1e1;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        thead>tr>th {
            background-color: #bad5e4;
        }

        .total-row {
            font-weight: bold;
            background-color: #e6f7ff;
        }

        .export-btn {
            margin-right: 10px;
            padding: 6px 18px;
            background: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .export-btn:hover {
            background: #0056b3;
        }

        .report-actions {
            text-align: right;
            margin-top: 10px;
            margin-bottom: 15px;
        }

        .address-wrap,
        .company-wrap {
            max-width: 220px;
            word-wrap: break-word;
            word-break: break-word;
            white-space: normal;
        }

        @media print {
            @page {
                size: A4 portrait;
                margin: 10mm;
            }

            body {
                padding: 0;
            }

            .report-actions {
                display: none;
            }

            .export-btn {
                display: none;
            }
        }
    </style>
</head>

<body style="background-color: white; padding: 3%;">
    <br>
    <center>
        <h4>Payment Report <?= ($paytype != '0' ? "({$paytype})" : '') ?> from
            <?= htmlspecialchars($displayStd, ENT_QUOTES, 'UTF-8') ?> to
            <?= htmlspecialchars($displayEnd, ENT_QUOTES, 'UTF-8') ?> for
            <?= htmlspecialchars($comname, ENT_QUOTES, 'UTF-8') ?>
        </h4>
        <p>Lineman: <?= htmlspecialchars($linemanLabel, ENT_QUOTES, 'UTF-8') ?></p>
    </center>
    <br>
    <div class="report-actions">
        <button class="export-btn" type="button" onclick="exportTableToExcel()">Export to Excel</button>
        <button class="export-btn" type="button" onclick="window.print()">Print Report</button>
        <button class="export-btn" type="button" onclick="document.getElementById('pdfExportForm').submit()">Export to
            PDF</button>
    </div>
    <form id="pdfExportForm" method="POST" action="payment-report.php" target="_blank" style="display:none;">
        <input type="hidden" name="stdt" value="<?= htmlspecialchars($stdt, ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="enddt" value="<?= htmlspecialchars($enddt, ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="paytype" value="<?= htmlspecialchars($paytype, ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="logusers" value="<?= htmlspecialchars($logusers, ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="lineman" value="<?= htmlspecialchars($selectedLineman, ENT_QUOTES, 'UTF-8') ?>">
        <input type="hidden" name="export_pdf" value="1">
    </form>
    <div class="table-responsive">
        <?= $reportTableHtml ?>
    </div>
    <?php include('include/script.php'); ?>
    <script src="src/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
    <script src="src/plugins/datatables/media/js/dataTables.bootstrap4.js"></script>
    <script src="src/plugins/datatables/media/js/dataTables.responsive.js"></script>
    <script src="src/plugins/datatables/media/js/responsive.bootstrap4.js"></script>
    <script>
        $(document).ready(function () {
            $('#reportTable').DataTable({
                scrollCollapse: true,
                autoWidth: false,
                responsive: true,
                paging: false,
                lengthChange: false,
                searching: false,
                columnDefs: [{
                    targets: "datatable-nosort",
                    orderable: false,
                }]
            });
        });
        function exportTableToExcel() {
            var html = document.getElementById('reportTable').outerHTML;
            var url = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(html);
            var link = document.createElement("a");
            link.setAttribute("href", url);
            link.setAttribute("download", "payment_report.xls");
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    </script>
</body>

</html>