<?php
ini_set('max_execution_time', 360); 
include "top.php"; 

$area_id = $_POST['area_id'];
$mnth = $_POST['mnth'];
$yrs = $_POST['yrs'];

// First check if this batch has already been processed
$chk = f(q("SELECT * FROM tbl_server_bill WHERE m_month='$mnth' AND m_year='$yrs' AND m_area='$area_id' AND m_done=1"));

if($chk['m_id'] != '') {
    // Get all unpaid customers for this lineman and period
    $query = "SELECT a.* 
              FROM `adduser` a
              LEFT JOIN `cbill` b ON a.id = b.bl_cid 
                  AND b.bl_month = '$mnth' 
                  AND b.bl_year = '$yrs'
              WHERE b.bl_cid IS NULL
              AND a.actv = 1
              AND a.line_ids = '$area_id'";
    
    $customers = mysqli_query($con, $query);
    $total = mysqli_num_rows($customers);
    $processed = 0;
    
    echo "<!DOCTYPE html>
    <html>
    <head>
        <title>Bill Generation Progress</title>
        <style>
            body { font-family: Arial, sans-serif; padding: 20px; }
            .progress-container { width: 100%; background-color: #f1f1f1; margin-top: 20px; }
            .progress-bar { width: 0%; height: 30px; background-color: #4CAF50; text-align: center; line-height: 30px; color: white; }
            .log { margin-top: 20px; border: 1px solid #ddd; padding: 10px; height: 300px; overflow-y: scroll; }
        </style>
    </head>
    <body>
        <h2>Generating Bills for $total Customers</h2>
        <div class='progress-container'>
            <div id='progress-bar' class='progress-bar'>0%</div>
        </div>
        <div class='log' id='log'></div>
        
        <script>
            function updateProgress(percent, message) {
                document.getElementById('progress-bar').style.width = percent + '%';
                document.getElementById('progress-bar').innerText = percent + '%';
                
                if(message) {
                    var log = document.getElementById('log');
                    log.innerHTML += message + '<br>';
                    log.scrollTop = log.scrollHeight;
                }
            }
        </script>";
    
    // Process each customer
    while($customer = mysqli_fetch_array($customers)) {
        $processed++;
        $percent = round(($processed / $total) * 100);
        
        $price = $customer['price'];
        $linemanid = $customer['line_ids'] ?: 0;
        
        // Get previous due amount
        $chkbill = f(q("SELECT COUNT(*) as cnt FROM cbill WHERE bl_cid='{$customer['id']}'"));
        if(floatval($chkbill['cnt']) > 0) {
            $getdues = f(q("SELECT * FROM cbill WHERE blid=(SELECT MAX(blid) FROM cbill WHERE bl_cid='{$customer['id']}')"));
            $totdue = $getdues['bl_due'];
        } else {
            $totdue = floatval($customer['prevdue']);
        }
        
        $getdues = f(q("SELECT bl_payamt FROM cbill WHERE bl_cid='{$customer['id']}' ORDER BY blid DESC LIMIT 1"));
        $totpay = $getdues['bl_payamt'];
        $oldprice = $price;
        
        $duesss = floatval($totdue) - floatval($totpay);
        $gst = round(floatval($price) * 0.18, 2);
        $price = round(floatval($price) + floatval($gst), 2);
        
        if($totdue == '') $totdue = 0;
        $totals = floatval($price) + floatval($totdue);
        
        $strtdt = firstday($mnth, $yrs);
        $enddt = lastday($mnth, $yrs);
        $custid = $customer['id'];
        $csadded = md5('admin');
        $txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
        
        $billamt = $totals;
        $discamt = 0;
        $paydt = date('Y-m-d');
        $prevdue = $totdue;
        $remarks = "Bill Generated for Month $mnth, $yrs";
        $oth_due = 0;
        $oth_reason = 'NA';
        $lineman = $linemanid;
        $nogstval = $oldprice;
        
        // Check if bill already exists
        $checkbldt = f(q("SELECT * FROM cbill WHERE bl_cid='$custid' AND bl_stdt='$strtdt'"));
        
        if($checkbldt['bl_cname'] == '') {
            $getmaxcbill = f(q("SELECT * FROM cbill WHERE blid=(SELECT MAX(blid) FROM cbill WHERE bl_cid='$custid'"));
            
            $lastbamt = $getmaxcbill['bl_pak'];
            $lastbdue = $getmaxcbill['bl_due'];
            $custpamt = $billamt;
            $uprice = floatval($billamt);
            $priceamt = $billamt;
            $bgstamt = $gst;
            $gstamt = round(floatval($bgstamt), 2);
            $custpamt = floatval($custpamt) - floatval($bgstamt);
            
            $checkexpiry = f(q("SELECT * FROM adduser WHERE id='{$customer['id']}'"));
            
            $bl_tp = ($customer['is_cable'] == '1') ? '1' : '0';
            
            if($checkexpiry['name'] != '') {
                $getmax = f(q("SELECT MAX(blid) as maxid FROM cbill"));
                $bl_mso = $checkexpiry['mso'];
                $bl_area = $checkexpiry['line_ids'];
                $comid = $checkexpiry['com_id'];
                
                $maxid = $getmax['maxid'];
                $maxid = floatval($maxid) + 1;
                
                $sumdue = f(q("SELECT bl_amt FROM cbill WHERE bl_cid='$custid' ORDER BY blid DESC LIMIT 1"));
                $tdue = $sumdue['bl_amt'];
                
                $getdues = f(q("SELECT bl_payamt FROM cbill WHERE bl_cid='$custid' ORDER BY blid DESC LIMIT 1"));
                $totpay = $getdues['bl_payamt'];
                
                $tdue = (floatval($billamt) + floatval($prevdue)) - floatval($discamt);
                if($tdue == '') $tdue = 0;
                
                $currentb = floatval($billamt);
                $dueamt = $tdue;
                $dues = floatval($dueamt) - floatval(0); // amtpaid is 0 for unpaid bills
                
                $dates = $checkexpiry['pexpiry'];
                $expdate = ($dates == '2020-09-01') ? $strtdt : $strtdt;
                $expirydate = date('Y-m-d', strtotime($expdate. ' + 29 days'));
                $pkid = $checkexpiry['packid'] ?: '0';
                
                if(floatval($oth_due) > 0) {
                    $prevdue = floatval($prevdue) + floatval($oth_due);
                }
                
                // Insert bill record (postpaid - unpaid)
                $sqls = "INSERT INTO cbill SET 
                    bl_cid='$custid', bl_dt=CURDATE(), bl_pid='$pkid', bl_no='$maxid', 
                    bl_cname='{$checkexpiry['name']}', bl_address='{$checkexpiry['address']}', 
                    bl_phone='{$checkexpiry['phone']}', bl_paych='{$checkexpiry['pay_ch']}', 
                    bl_amt='$price', bl_payamt='0', bl_stat='0', bl_paydt='$paydt', 
                    bl_paymd='NA', bl_trn='$txnid', bl_payuid='NA', bl_due='$currentb', 
                    bl_prevdue='$prevdue', bl_user='$csadded', bl_expiry='$expirydate', 
                    bl_tp='$bl_tp', bl_month='$mnth', bl_year='$yrs', bl_stdt='$strtdt', 
                    bl_disc='$discamt', bl_gst='$gstamt', bl_pak='$oldprice', 
                    bl_mso='$bl_mso', bl_area='$bl_area', bl_remarks='$remarks', 
                    oth_reason='$oth_reason', oth_due='$oth_due', bl_com='$comid', 
                    bl_line='$lineman'";
                
                $res = mysqli_query($con, $sqls);
                
                if($res) {
                    mysqli_query($con,"UPDATE adduser SET mnth='$mnth', yrs='$yrs', pexpiry='$expirydate', actv=1, lpaydt='$paydt', lpayamt='0', pay_ch='NA' WHERE id='$custid'");
                    
                    echo "<script>updateProgress($percent, 'Generated bill for {$customer['name']} (ID: {$customer['custid']})');</script>";
                    ob_flush();
                    flush();
                } else {
                    echo "<script>updateProgress($percent, 'Error generating bill for {$customer['name']}: ".mysqli_error($con)."');</script>";
                    ob_flush();
                    flush();
                }
            }
        } else {
            echo "<script>updateProgress($percent, 'Bill already exists for {$customer['name']} (ID: {$customer['custid']})');</script>";
            ob_flush();
            flush();
        }
    }
    
    // Mark this batch as complete
    mysqli_query($con,"UPDATE tbl_server_bill SET m_done='1', m_count='$processed' WHERE m_month='$mnth' AND m_year='$yrs' AND m_area='$area_id'");
    
    echo "<script>updateProgress(100, 'Bill generation completed for $processed customers.');</script>";
    echo "</body></html>";
} else {
    echo "<!DOCTYPE html>
    <html>
    <head>
        <title>Bill Generation Complete</title>
    </head>
    <body>
        <h2>Bill generation for $mnth $yrs has already been completed.</h2>
        <p>This batch was processed earlier and marked as complete.</p>
    </body>
    </html>";
}
?>