<?php
include "top.php";

$stdt = isset($_REQUEST['stdt']) ? $_REQUEST['stdt'] : '';
$endt = isset($_REQUEST['endt']) ? $_REQUEST['endt'] : '';
$bl_area = isset($_REQUEST['bl_area']) ? $_REQUEST['bl_area'] : '0';
$exportPdf = !empty($_POST['export_pdf']);

$area_filter = ($bl_area != '0') ? " AND area_id='$bl_area'" : "";
$q = "SELECT * FROM adduser WHERE is_cable=1 AND pexpiry BETWEEN '$stdt' AND '$endt' $area_filter ORDER BY pexpiry ASC";
$getc = mysqli_query($con, $q);

if ($bl_area != '0') {
    $geta = f(q("SELECT arname FROM tbl_area WHERE arid='$bl_area'"));
    $aname = $geta['arname'];
} else {
    $aname = "All Areas";
}

$rowsHtml = '';
$c = 0;
while ($arr = mysqli_fetch_array($getc)) {
    $c++;
    $expiry = date("d-m-Y", strtotime($arr['pexpiry']));
    $lpaydt = !empty($arr['lpaydt']) ? date("d-m-Y", strtotime($arr['lpaydt'])) : '-';
    $get_last_bill = f(q("SELECT bl_due,bl_payamt FROM cbill WHERE bl_cid='{$arr['id']}' ORDER BY blid DESC LIMIT 1"));
    $last_bill_due_amt = !empty($get_last_bill) ? $get_last_bill['bl_due'] : '-';
    $last_bill_payamt = !empty($get_last_bill) ? $get_last_bill['bl_payamt'] : '-';

    $rowsHtml .= "<tr>
            <td>{$c}</td>
            <td><strong>{$arr['name']}</strong></td>
            <td>{$arr['phone']}</td>
            <td>{$arr['area_name']}</td>
            <td class='vc-col'>{$arr['vc']}</td>
            <td>{$arr['custid']}</td>
            <td>{$expiry}</td>
            <td>{$arr['price']}</td>
            <td>{$lpaydt} <br> Rs {$last_bill_payamt}</td>
            <td>{$last_bill_due_amt}</td>
        </tr>";
}

if ($c == 0) {
    $rowsHtml .= '<tr><td colspan="10" style="text-align:center;">No records found for the selected criteria.</td></tr>';
}

function render_table()
{
    global $rowsHtml;
    return '<table>
        <thead>
            <tr>
                <th>Sl</th>
                <th>Customer Name</th>
                <th>Phone</th>
                <th>Area</th>
                <th class="vc-col">VC no</th>
                <th>A/C No</th>
                <th>Expiry Date</th>
                <th>Price</th>
                <th>Last Pay Dt & Amt.</th>
                <th>Last Bill Due Amount</th>
            </tr>
        </thead>
        <tbody>' . $rowsHtml . '</tbody>
    </table>';
}

if ($exportPdf) {
    require_once dirname(__FILE__) . '/dompdf/autoload.inc.php';
    $dompdf = new \Dompdf\Dompdf();
    $tableHtml = render_table();
    $pdfHtml = '<html><head><style>body{font-family:Arial,sans-serif;}table{width:100%;border-collapse:collapse;margin-top:20px;}th,td{border:1px solid #ccc;padding:8px;text-align:left;font-size:11px;}th{background:#f4f4f4;font-weight:bold;}.vc-col{width:100px;word-wrap:break-word;white-space:normal;word-break:break-all;}</style></head><body><div style="text-align:center;margin-bottom:20px;"><h4>End Date Wise Customer Report</h4><p><strong>Period:</strong> ' . date("d-m-Y", strtotime($stdt)) . ' to ' . date("d-m-Y", strtotime($endt)) . ' | <strong>Area:</strong> ' . $aname . '</p></div>' . $tableHtml . '</body></html>';
    $dompdf->loadHtml($pdfHtml);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    $dompdf->stream("enddate-report.pdf", ['Attachment' => false]);
    exit;
}

?>
<!DOCTYPE html>
<html>

<head>
    <?php include('include/head.php'); ?>
    <title>End Date Wise Customer Report</title>
    <style type="text/css">
        body {
            background-color: white;
            font-family: Arial, sans-serif;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        th,
        td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
            font-size: 11px;
        }

        th {
            background-color: #f4f4f4;
            font-weight: bold;
        }

        .vc-col {
            width: 100px;
            word-wrap: break-word;
            white-space: normal;
            word-break: break-all;
        }

        .header-info {
            text-align: center;
            margin-bottom: 20px;
        }

        .no-print {
            text-align: right;
            margin-bottom: 10px;
        }

        @media print {
            .no-print {
                display: none;
            }

            body {
                padding: 0;
            }

            table {
                border: 1px solid #000;
            }

            th,
            td {
                border: 1px solid #000;
            }
        }
    </style>
</head>

<body style="padding: 20px;">

    <div class="no-print">
        <button onclick="window.print();" class="btn btn-primary btn-sm">Print Report</button>
        <button onclick="document.getElementById('pdfForm').submit();" class="btn btn-info btn-sm">Export to
            PDF</button>
        <button onclick="window.close();" class="btn btn-secondary btn-sm">Close</button>
    </div>

    <form id="pdfForm" method="POST" action="enddate_print.php" target="_blank" style="display:none;">
        <input type="hidden" name="stdt" value="<?php echo htmlspecialchars($stdt); ?>">
        <input type="hidden" name="endt" value="<?php echo htmlspecialchars($endt); ?>">
        <input type="hidden" name="bl_area" value="<?php echo htmlspecialchars($bl_area); ?>">
        <input type="hidden" name="export_pdf" value="1">
    </form>

    <div class="header-info">
        <h4>End Date Wise Customer Report</h4>
        <p>
            <strong>Period:</strong> <?php echo date("d-m-Y", strtotime($stdt)); ?> to
            <?php echo date("d-m-Y", strtotime($endt)); ?> |
            <strong>Area:</strong> <?php echo $aname; ?>
        </p>
    </div>

    <?php echo render_table(); ?>

    <script type="text/javascript">
        window.onload = function () {
            // Uncomment below if you want auto-print dialog on load
            // window.print();
        };
    </script>
</body>

</html>