<?php
$parentuserid = $_SESSION['userid'];

$start_input = $_GET['start'] ?? date('01-m-Y');
$end_input   = $_GET['end']   ?? date('d-m-Y');


function toMysqlDate($dateStr)
{
    if (empty($dateStr)) {
        return date('Y-m-d');
    }
    $parts = explode('-', $dateStr);
    if (count($parts) === 3 && checkdate((int)$parts[1], (int)$parts[0], (int)$parts[2])) {
        return $parts[2] . '-' . $parts[1] . '-' . $parts[0];
    }
    return date('Y-m-d');
}

$start_mysql = toMysqlDate($start_input);
$end_mysql   = toMysqlDate($end_input);


$end_mysql_full = $end_mysql . ' 23:59:59';
$accountData = $obj->raw_sql("
    SELECT a.*, ag.ag_name AS agent_name, ag.ip AS agent_ip
    FROM re_vw_account a
    LEFT JOIN re_tbl_agent ag ON ag.ag_id = a.agent_id
    WHERE a.entry_by = '$parentuserid' 
      AND a.entry_date BETWEEN '$start_mysql' AND '$end_mysql_full'
    ORDER BY a.entry_date ASC
");
?>

<!-- Date Filter -->
<form id="statementFilter" action="" method="GET">
    <input type="hidden" name="page" value="reseller-statement">

    <div class="row mb-3 align-items-end">
        <div class="col-md-3 col-sm-6 mb-2">
            <label for="minDate" class="form-label">From:</label>
            <input type="text" name="start" id="minDate" class="form-control datepicker"
                placeholder="dd-mm-yyyy" value="<?= htmlspecialchars($start_input) ?>">
        </div>
        <div class="col-md-3 col-sm-6 mb-2">
            <label for="maxDate" class="form-label">To:</label>
            <input type="text" name="end" id="maxDate" class="form-control datepicker"
                placeholder="dd-mm-yyyy" value="<?= htmlspecialchars($end_input) ?>">
        </div>
        <!-- <div class="col-md-auto align-self-end mb-2">
            <button class="btn btn-primary btn-sm" type="submit">Submit</button>
            <a href="?page=reseller-statement" class="btn btn-outline-secondary btn-sm">Clear</a>
        </div> -->
    </div>
</form>
<?php $lastBalance = 0; ?>
<div id="month_print">
    <table class="table table-striped table-hover table-modern" id="monthly_tbl">
        <thead>
            <tr>
                <th>Sl</th>
                <th>Date</th>
                <th>Particular</th>
                <th>Client</th>
                <th>Ip</th>
                <th>User</th>
                <th class="text-right">Credit</th>
                <th class="text-right">Debit</th>
                <th class="text-right">Balance</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <th colspan="6" class="text-center">Total</th>
                <th class="text-right" id="totalCredit"></th>
                <th class="text-right" id="totalDebit"></th>
                <th class="text-right" id="totalBalance"></th>
            </tr>
        </tfoot>
        <tbody>
            <?php
            $balance = 0;
            $credit_total = 0;
            $debit_total = 0;
            $i = 0;

            foreach ($accountData as $acount) {
                $i++;
                $amount = $acount['acc_amount'];
                $credit = 0;
                $debit = 0;
                if ($acount['acc_type'] == 1) { // Debit
                    $debit = $amount;
                    $balance -= $debit;
                    $debit_total += $debit;
                } else { // Credit
                    $credit = $amount;
                    $balance += $credit;
                    $credit_total += $credit;
                }


                $lastBalance = $balance;
            ?>
                <tr>
                    <td><?php echo $i; ?></td>
                    <td><?php echo date('d-m-Y', strtotime($acount['entry_date'])); ?></td>
                    <td><?php echo $acount['acc_description']; ?></td>
                    <td><?php echo $acount['agent_name']; ?></td>
                    <td><?php echo $acount['agent_ip']; ?></td>
                    <td><?php echo $acount['FullName']; ?></td>
                    <td class="text-right"><?php echo $credit; ?></td>
                    <td class="text-right"><?php echo $debit; ?></td>
                    <td class="text-right"><?php echo $balance; ?></td>
                </tr>
            <?php } ?>
        </tbody>
    </table>
</div>

<button class="btn btn-primary btn-sm mt-2" onclick="printDiv('month_print')">Print Statement</button>

<?php echo $obj->start_script(); ?>

<!-- JS & DataTables -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.10.0/js/bootstrap-datepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.10.0/css/bootstrap-datepicker.min.css" />

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">

<script>
    $(document).ready(function() {
        $('.datepicker').datepicker({
            autoclose: true,
            format: 'dd-mm-yyyy'
        });

        // Initialize DataTable
        var table = $('#monthly_tbl').DataTable({
            responsive: true,
            pageLength: 25,
            order: [
                [1, 'asc']
            ],
            dom: 'Bfrtip',
            buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
            footerCallback: function(row, data, start, end, display) {
                var api = this.api();
                var totalCredit = api.column(6, {
                    page: 'current'
                }).data().reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
                var totalDebit = api.column(7, {
                    page: 'current'
                }).data().reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
                var totalBalance = api.column(8, {
                    page: 'current'
                }).data().reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
                $('#totalCredit').html(totalCredit);
                $('#totalDebit').html(totalDebit);
                $('#totalBalance').html(<?= json_encode($lastBalance) ?>);
            }
        });

        // Date filter
        $.fn.dataTable.ext.search.push(
            function(settings, data, dataIndex) {
                var min = $('#minDate').val();
                var max = $('#maxDate').val();
                var date = data[1]; // Date column
                if (min && max) {
                    var d = date.split('-');
                    var dat = new Date(d[2], d[1] - 1, d[0]);
                    var minD = new Date(min.split('-')[2], min.split('-')[1] - 1, min.split('-')[0]);
                    var maxD = new Date(max.split('-')[2], max.split('-')[1] - 1, max.split('-')[0]);
                    return (dat >= minD && dat <= maxD);
                }
                return true;
            }
        );

        $('#minDate,#maxDate').change(function() {
            // table.draw();
            $('#statementFilter').submit();
        });
    });

    // Print
    function printDiv(divName) {
        var printContents = document.getElementById(divName).innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
    }
</script>

<?php echo $obj->end_script(); ?>