<?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 = $_POST['stdt'] ?? date('Y-m-d');
$enddt = $_POST['enddt'] ?? date('Y-m-d');
$logusers = $_POST['logusers'] ?? '0';
$dbarea = $_POST['dbarea'] ?? '0';
$bl_area = $_POST['bl_area'] ?? '0';

$stdt_safe = mysqli_real_escape_string($con, $stdt);
$enddt_safe = mysqli_real_escape_string($con, $enddt);
$logusers_safe = mysqli_real_escape_string($con, $logusers);
$dbarea_safe = mysqli_real_escape_string($con, $dbarea);
$bl_area_safe = mysqli_real_escape_string($con, $bl_area);

$csadded = $_SESSION['murgibhai'];
$getlog = f(q("SELECT * FROM tbl_login WHERE l_uid='$csadded'"));
$ltype = $getlog['l_type'];
$uidd = $getlog['user_id'];

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

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

$area_filter = ($bl_area_safe !== '0') ? " AND bl_area='$bl_area_safe'" : "";

$qury = '';
if ($ltype == 2) {
    if ($logusers_safe === '0') {
        if ($dbarea_safe === '0') {
            $qury = "SELECT * FROM `cbill` WHERE bl_user='$getlog[l_uid]' AND bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter";
        } else {
            $qury = "SELECT * FROM `cbill` WHERE bl_line='$dbarea_safe' AND bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter";
        }
    } else {
        if ($dbarea_safe === '0') {
            $qury = "SELECT * FROM `cbill` WHERE bl_com='$logusers_safe' AND bl_user='$getlog[l_uid]' AND bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter";
        } else {
            $qury = "SELECT * FROM `cbill` WHERE bl_com='$logusers_safe' AND bl_line='$dbarea_safe' AND bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter";
        }
    }
} elseif ($ltype == 1) {
    if ($logusers_safe === '0') {
        if ($dbarea_safe === '0') {
            $qury = "SELECT * FROM `cbill` WHERE bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter";
        } else {
            $qury = "SELECT * FROM `cbill` WHERE bl_line='$dbarea_safe' AND bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter";
        }
    } else {
        if ($dbarea_safe === '0') {
            $qury = "SELECT * FROM `cbill` WHERE bl_com='$logusers_safe' AND bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter";
        } else {
            $qury = "SELECT * FROM `cbill` WHERE bl_line='$dbarea_safe' AND bl_com='$logusers_safe' AND bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter";
        }
    }
} else {
    $qury = "SELECT * FROM cbill WHERE bl_cid='$uidd' AND bl_dt BETWEEN '$stdt_safe' AND '$enddt_safe' $area_filter ORDER BY blid DESC";
}

$query = mysqli_query($con, $qury);
$reportRows = [];
$totblamt = 0.0;
$totpay = 0.0;
$totdisc = 0.0;

while ($arrc = mysqli_fetch_assoc($query)) {
    $row = f(q("SELECT * FROM `adduser` WHERE id={$arrc['bl_cid']}"));
    $billamt = floatval($arrc['bl_amt']) + floatval($arrc['bl_prevdue']);
    $duess = abs(round($billamt - (floatval($arrc['bl_payamt']) + floatval($arrc['bl_disc']))));
    $totblamt += $billamt;
    $totpay += floatval($arrc['bl_payamt']);
    $totdisc += floatval($arrc['bl_disc']);

    $getco = f(q("SELECT * FROM tbl_company WHERE c_id='{$row['com_id']}'"));
    $coname = $getco['c_shortname'] ?? '';
    $linemanInfo = f(q("SELECT * FROM tbl_login WHERE l_id='{$arrc['bl_line']}'"));
    $lineman_name = $linemanInfo['l_name'] ?? '';

    $periodStart = format_report_date($arrc['bl_stdt']);
    $periodEnd = format_report_date($arrc['bl_expiry']);

    $reportRows[] = [
        'company' => $coname,
        'lineman' => $lineman_name,
        'custid' => $row['custid'],
        'name' => $row['name'],
        'phone' => $row['phone'],
        'address' => $row['address'],
        'period_start' => $periodStart,
        'period_end' => $periodEnd,
        'bill_amt' => $billamt,
        'paid_amt' => floatval($arrc['bl_payamt']),
        'due_amt' => $duess,
    ];
}

$totdue = abs(round($totblamt - ($totpay + $totdisc)));
$showCompany = ($logusers_safe === '0');
$colspan = $showCompany ? 8 : 7;

ob_start();
?>
<table id="reportTable" class="stripe data-table" style="width:100%;">
    <thead>
        <tr>
            <th class="table-plus datatable-nosort">Sl. No</th>
            <?php if ($showCompany) { ?><th class="address-wrap">Company</th><?php } ?>
            <th>Lineman</th>
            <th>Customer Id</th>
            <th>Customer Name</th>
            <th>Phone</th>
            <th class="address-wrap">Address</th>
            <th>Period</th>
            <th>Bill Amt (incl Prev Due)</th>
            <th>Paid Amt</th>
            <th>Due Amt</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($reportRows as $index => $row) { ?>
            <tr>
                <td class="table-plus"><?= $index + 1 ?></td>
                <?php if ($showCompany) { ?><td><?= htmlspecialchars($row['company'] ?? '', ENT_QUOTES, 'UTF-8') ?></td><?php } ?>
                <td><?= htmlspecialchars($row['lineman'], ENT_QUOTES, 'UTF-8') ?></td>
                <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 class="address-wrap"><?= htmlspecialchars($row['address'], ENT_QUOTES, 'UTF-8') ?></td>
                <td>
                    <div><?= htmlspecialchars($row['period_start'], ENT_QUOTES, 'UTF-8') ?></div>
                    <div style="font-size:11px;">to</div>
                    <div><?= htmlspecialchars($row['period_end'], ENT_QUOTES, 'UTF-8') ?></div>
                </td>
                <td><?= number_format($row['bill_amt'], 2) ?></td>
                <td><?= number_format($row['paid_amt'], 2) ?></td>
                <td><?= number_format($row['due_amt'], 2) ?></td>
            </tr>
        <?php } ?>
        <tr class="total-row">
            <td colspan="<?= $colspan ?>"><strong>Total</strong></td>
            <td><strong><?= number_format($totblamt, 2) ?></strong></td>
            <td><strong><?= number_format($totpay, 2) ?></strong></td>
            <td><strong><?= number_format($totdue, 2) ?></strong></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{max-width:220px;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>Bill Generation Report from ' . $displayStd . ' to ' . $displayEnd . ' for ' . htmlspecialchars($comname, ENT_QUOTES, 'UTF-8') . '</h4></div>';
    $dompdf->loadHtml('<html><head><meta charset="UTF-8">' . $pdfStyle . '</head><body>' . $pdfHeader . $reportTableHtml . '</body></html>');
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream("bill-generation-report-{$stdt}-{$enddt}.pdf", ['Attachment' => false]);
    exit;
}
?>
<!DOCTYPE html>
<html>
   <head>
      <?php include('include/head.php'); ?>
      <title>Bill Generate Report for <?= htmlspecialchars($displayStd, ENT_QUOTES, 'UTF-8') ?> and <?= htmlspecialchars($displayEnd, ENT_QUOTES, 'UTF-8') ?> for <?= htmlspecialchars($comname, ENT_QUOTES, 'UTF-8') ?></title>
      <link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/jquery.dataTables.css">
      <link rel="stylesheet" type="text/css" href="src/plugins/datatables/media/css/dataTables.bootstrap4.css">
      <link rel="stylesheet" type="text/css" href="src/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: 13px !important;
         }
         td{
         font-size: 12px !important;
         border:1px solid #e2e1e1;
         }
         table{
            width: 100%;
            border-collapse: collapse;
            }
            tr{
            width: 100%;
            }
            thead > tr > th{
            background-color: #bad5e4;
            }
         .address-wrap{
             max-width: 260px;
             word-wrap: break-word;
             word-break: break-word;
             white-space: normal;
         }
         .export-btn{
             margin-right:10px;
             padding:6px 18px;
             color:#fff;
             border:none;
             border-radius:4px;
             cursor:pointer;
             font-size:12px;
             background:#007bff;
         }
         .export-btn:hover{
             background:#0056b3;
         }
         .report-actions{
             text-align:right;
             margin:10px 0;
         }
         @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%;">
      <div class="report-actions">
            <a href="billgenerate_report_excel.php?stdt=<?= urlencode($stdt) ?>&enddt=<?= urlencode($enddt) ?>&logusers=<?= urlencode($logusers) ?>&dbarea=<?= urlencode($dbarea) ?>&bl_area=<?= urlencode($bl_area) ?>" class="btn btn-primary" target="_blank">Export To Excel</a>
            <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="bill_generate_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="logusers" value="<?= htmlspecialchars($logusers, ENT_QUOTES, 'UTF-8') ?>">
         <input type="hidden" name="dbarea" value="<?= htmlspecialchars($dbarea, ENT_QUOTES, 'UTF-8') ?>">
         <input type="hidden" name="bl_area" value="<?= htmlspecialchars($bl_area, ENT_QUOTES, 'UTF-8') ?>">
         <input type="hidden" name="export_pdf" value="1">
      </form>
      <br>
      <center><h4>Bill Generation Report from <?= htmlspecialchars($displayStd, ENT_QUOTES, 'UTF-8') ?> to <?= htmlspecialchars($displayEnd, ENT_QUOTES, 'UTF-8') ?> for <?= htmlspecialchars($comname, ENT_QUOTES, 'UTF-8') ?></h4></center><br>
      <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(){
         	$('.data-table').DataTable({
         		scrollCollapse: true,
         		autoWidth: false,
         		responsive: true,
               paging: false,
               lengthChange: false,
               searching: false,
         		columnDefs: [{
         			targets: "datatable-nosort",
         			orderable: false,
         		}],
         		"lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
         		"language": {
         			"info": "_START_-_END_ of _TOTAL_ entries",
         			searchPlaceholder: "Search"
         		},
         	});
         });
      </script>
   </body>
</html>
