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


$firsDayOfMonth = new DateTime('first day of this month');
$dateform = $firsDayOfMonth->format('Y-m-d');
$dateto = date('Y-m-d');

if(isset($_POST['searchSubmit'])){
    $dateform = date('Y-m-d', strtotime($_POST['dateform']));
    $dateto = date('Y-m-d', strtotime($_POST['dateto']));
}

$resellers = $obj->raw_sql("SELECT UserId FROM _reseller_createuser WHERE EntryBy='$parentuserid'");

$resellerIDs = [];

foreach($resellers as $reseller){ $resellerIDs[] = $reseller['UserId']; }

$resellerIDsStr = !empty($resellerIDs) ? implode(',', $resellerIDs) : '0';




$agents = $obj->raw_sql("SELECT ag_id FROM re_tbl_agent WHERE entry_by IN ($resellerIDsStr)");



$agentIDs = [];
foreach($agents as $agent){ $agentIDs[] = $agent['ag_id']; }
$agentIDsStr = !empty($agentIDs) ? implode(',', $agentIDs) : '0';




// 3️⃣ Get all accounting entries for these agents
$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 IN ($resellerIDsStr)
    AND a.entry_date BETWEEN '$dateform' AND '$dateto'
    ORDER BY a.entry_date ASC
");

?>

<!-- Filter Form -->
<form method="POST" class="mb-3">
    <label>From: <input type="text" name="dateform" value="<?php echo date('d-m-Y', strtotime($dateform)); ?>" class="datepicker" required></label>
    <label>To: <input type="text" name="dateto" value="<?php echo date('d-m-Y', strtotime($dateto)); ?>" class="datepicker" required></label>
    <button type="submit" class="btn btn-success btn-sm" name="searchSubmit">Search</button>
</form>

<div id="month_print">
    <h4 class="text-center" id="showDate">
        Statement: <?php echo date('d-M-Y', strtotime($dateform)); ?> to <?php echo date('d-M-Y', strtotime($dateto)); ?>
    </h4>

    <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>
        <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;
    }
?>
            <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>
        <tfoot>
            <tr>
                <td colspan="6" class="text-center"><b>Total</b></td>
                <td class="text-right"><b><?php echo $credit_total; ?></b></td>
                <td class="text-right"><b><?php echo $debit_total; ?></b></td>
                <td class="text-right"><b><?php echo $balance; ?></b></td>
            </tr>
        </tfoot>
    </table>
</div>

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


<?php echo $obj->start_script(); ?>
<!-- JS -->
<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" />

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

    // Initialize DataTable
    $('#monthly_tbl').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[1, 'asc']], // Sort by Date ascending
        dom: 'Bfrtip', // Buttons layout
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    });
});
</script>

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

// 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(); ?>