<? include "top.php";


?>
<!DOCTYPE html>
<html>

<head>
    <?php include('include/head.php'); ?>
    <title>Generate Customer Bill</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>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <style>
        #searchcustomer {
            max-height: 400px;
            overflow-y: auto;
            margin-top: 10px;
        }

        #searchcustomer table {
            font-size: 12px;
        }

        #searchcustomer table th {
            background: #f8f9fa;
            position: sticky;
            top: 0;
        }

        #searchcustomer tr:hover {
            background-color: #f1f1f1;
        }
    </style>
</head>

<body>
    <script>
        function sendAutoSMS(phone, message) {
            console.log('sendAutoSMS called with phone:', phone, 'and message:', message);
            if (phone && message) {
                // Encode the message for URL safety
                var encodedMsg = btoa(unescape(encodeURIComponent(message)));

                // Make AJAX call to send-sms.php
                $.ajax({
                    url: 'send-sms.php',
                    type: 'POST',
                    data: {
                        action: 'sendsms',
                        cphone: phone,
                        msgs: encodedMsg
                    },
                    dataType: 'json',
                    success: function (response) {
                        console.log('SMS sent successfully to', phone);
                        if (!response.success) {
                            console.error('SMS sending failed:', response.error || 'Unknown error');
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('SMS sending failed:', error);
                    }
                });
            } else {
                console.log('sendAutoSMS called but phone or message is missing');
            }
        }
    </script>
    <?php include('include/header.php'); ?>
    <?php include('include/sidebar.php');

    $ltype = $_SESSION['lype'] ?? '';
    $csadded = $_SESSION['murgibhai'] ?? '';
    $linemanFilter = "l_type=2";
    if ($ltype != '1') {
        $linemanFilter .= " AND l_uid='" . mysqli_real_escape_string($con, $csadded) . "'";
    }

    $action = $_REQUEST['action'];
    $gcustid = $_REQUEST['custid'];

    if ($gcustid != '') {


        $getgc = f(q("SELECT * FROM adduser WHERE id='$gcustid'"));
    }

    if ($action == 'save') {

        $lnarid = $_POST['lnarid'];
        $strtdt = $_POST['strtdt'];
        $enddt = $_POST['enddt'];
        $mnth = $_POST['mnth'];
        $yrs = $_POST['yrs'];
        $custid = $_POST['custid'];
        $csadded = $_SESSION['murgibhai'];
        $txnid = substr(hash('sha256', mt_rand() . microtime()), 0, 20);
        $postpaid = $_POST['postpaid'];
        $amtpaid = $_POST['amtpaid'];
        $billamt = $_POST['billamt'];
        $discamt = $_POST['discamt'];
        $sendsms = $_POST['sendsms'];
        $paymodes = $_POST['paymodes'];
        $paydt = $_POST['paydt'];
        $prevdue = $_POST['prevdue'];
        $cpaychannels = $_POST['cpaychannels'];
        $remarks = $_POST['remarks'];

        $oth_due = $_POST['oth_due'];
        $oth_reason = $_POST['oth_reason'];
        $lineman = $_POST['lineman'];
        $nogstval = $_POST['nogstval'];
        $tbillamt = $_POST['tbillamt'];
        $cphone = $_POST['cphone'];

        $upusr = mysqli_query($con, "UPDATE `adduser` SET phone='$cphone' WHERE is_cable=1 AND id='$custid'");


        $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'];

            // if(floatval($lastbamt)>0){
    
            // 	$custpamt=$lastbamt;
    
            // }else{
    
            $custpamt = $billamt;
            //}
    

            $uprice = floatval($billamt);



            //$priceamt=(floatval($uprice)/118)*100;
            $priceamt = $billamt;

            $bgstamt = floatval($uprice) - floatval($priceamt);
            $custpamt = floatval($custpamt) - floatval($bgstamt);
            // if(floatval($discamt)>0){
    
            // 	$priceamt=floatval($priceamt)-floatval($discamt);
    
            // }
            //$priceamt=floatval($billamt)-floatval($bgstamt);
            $gstamt = round(floatval($bgstamt), 2);

            //echo "SELECT * FROM adduser WHERE id='$custid'";
            $checkexpiry = f(q("SELECT * FROM adduser WHERE id='$custid'"));

            if ($checkexpiry['is_cable'] == '1') {

                $bl_tp = '1';
            } else {

                $bl_tp = '0';
            }

            if ($checkexpiry['name'] != '') {

                // Get active financial year
                $getActiveFY = f(q("SELECT * FROM tbl_financial_year_master WHERE fy_is_active='1' LIMIT 1"));

                if ($getActiveFY['fy_id'] == '') {
                    // Fallback: Get current financial year from bill_seq table
                    $currentYear = date('Y');
                    $currentMonth = date('n');

                    // Financial year: April (4) to March (3)
                    if ($currentMonth >= 4) {
                        $fyLabel = $currentYear . '-' . ($currentYear + 1);
                    } else {
                        $fyLabel = ($currentYear - 1) . '-' . $currentYear;
                    }

                    $getFYSeq = f(q("SELECT * FROM tbl_financial_year_bill_seq WHERE year_label='$fyLabel' LIMIT 1"));
                    $fy_id = $getFYSeq['seq_id'] ?? 0;
                } else {
                    $fy_id = $getActiveFY['fy_id'];
                }

                // Get next bill number for this financial year
                mysqli_query($con, "UPDATE tbl_financial_year_bill_seq
				SET current_bill_no = current_bill_no + 1
				WHERE seq_id='$fy_id'");

                $getFYSeq = f(q("SELECT current_bill_no FROM tbl_financial_year_bill_seq WHERE seq_id='$fy_id'"));
                $maxid = $getFYSeq['current_bill_no'];

                $bl_mso = $checkexpiry['mso'];
                $bl_area = $checkexpiry['area_id'];
                $comid = $checkexpiry['com_id'];

                $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;
                }

                if (floatval($prevdue) > 0) {

                    //$tdue=floatval($tdue)+floatval($prevdue);
                }
                $currentb = floatval($billamt);
                $dueamt = $tdue;

                //$dues=(floatval($dueamt)-floatval($discamt))+floatval($prevdue);
                $dues = abs(round(floatval($dueamt) - (floatval($amtpaid) + floatval($discamt)), 2));


                // echo "Outstanding: ".$tdue."<br>";
                // echo "Current Bill: ".$currentb."<br>";
                // echo "Current Dues: ".$dues."<br>";
    
                //die();
    
                $dates = $checkexpiry['pexpiry'];
                if ($dates == '2020-09-01') {
                    $expdate = $strtdt;
                } else {

                    // $curdate=new DateTime($dates);
                    // $newstdate=new DateTime($strtdt);
    

                    // if($curdate>$newstdate){
    
                    // 	$expdate=$dates;
                    // }elseif($curdate==$newstdate){
    
                    // 	$expdate=strtotime('+1 days', strtotime($dates));
                    // 	$expdate=date("Y-m-d",$expdate);
                    // }elseif($curdate<$newstdate){
    
                    $expdate = $strtdt;
                    //}
    

                }



                //echo "Expiry".$expdate; die();
    
                $thirtyDaysUnix = date('Y-m-d', strtotime($expdate . ' + 29 days'));
                //echo "EXPIRY".$thirtyDaysUnix; die();
                $expirydate = $_POST['enddt'];
                $pkid = $checkexpiry['packid'];

                if (floatval($oth_due) > 0) {

                    $prevdue = floatval($prevdue) + floatval($oth_due);
                }

                if ($pkid == '') {

                    $pkid = '0';
                }


                $alavals = $_POST['billamt'];
                $totalamt = $alavals;
                $packpr = $totalamt;
                $ncfamt = 0;
                $chvals = 0;
                $bopv = 0;
                $chtot = 0;
                $accv = 0;
                $bpvals = 0;
                $noopv = $_POST['countch'];



                $delpacks = mysqli_query($con, "DELETE FROM tbl_change_package WHERE userid='$custid'");
                //echo "INSERT INTO  tbl_change_package SET userid='$custid',price='$totalamt',pay_ch='Pack Change',packpr='$packpr',ncf='$ncfamt',chp='$chvals',ala='$alavals',dbp='$bpvals',chno='$noopv',alano='$accv',bpno='$bopv',totalc='$chtot'";
                $res = mysqli_query($con, "INSERT INTO  tbl_change_package SET userid='$custid',price='$totalamt',pay_ch='Pack Change',packpr='$packpr',ncf='$ncfamt',chp='$chvals',ala='$alavals',dbp='$bpvals',chno='$noopv',alano='$accv',bpno='$bopv',totalc='$alavals'");
                if ($res) {

                    $maxidpak = mysqli_insert_id($con);
                    $alacarte = $_POST['alacarte'];
                    $delalacarte = mysqli_query($con, "DELETE FROM tbl_change_package_details WHERE customer_id='$custid' AND pac_type='4'");
                    foreach ($alacarte as $value) {
                        // echo "INSERT INTO tbl_change_package_details SET chid='$maxid',pac_type='4',cust_date=CURDATE(),pac_id='$value',customer_id='$custid'";
                        $res = mysqli_query($con, "INSERT INTO tbl_change_package_details SET chid='$maxidpak',pac_type='4',cust_date=CURDATE(),pac_id='$value',customer_id='$custid'");
                        $ps = getpackname($value) . ', ' . $ps;

                    }

                    //echo $ps;
                    $upusr = mysqli_query($con, "UPDATE `adduser` SET price='$tbillamt',pay_ch='$ps' WHERE is_cable=1 AND id='$custid'");

                }

                $checkexpiry = f(q("SELECT * FROM adduser WHERE id='$custid'"));
                if ($postpaid == '0') {

                    $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='$currentb',bl_payamt='$amtpaid',bl_stat='1',bl_paydt='$paydt',bl_paymd='$paymodes',bl_trn='$txnid',bl_payuid='NA',bl_due='$dues',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='$priceamt',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',bl_financial_year_id='$fy_id'";



                } else {

                    $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='$currentb',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='$priceamt',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',bl_financial_year_id='$fy_id'";
                }
                //echo $sqls; die();
                $res = mysqli_query($con, $sqls);
                $maxbill = mysqli_insert_id($con);

                if ($res) {

                    if ($postpaid == '0') {

                        $gstval = '18';
                        $gstamt = floatval($amtpaid) * (18 / 118);
                        $maxbill = mysqli_insert_id($con);
                        $inspay = mysqli_query($con, "INSERT INTO tbl_billpay SET pay_date='$paydt',pay_amt='$amtpaid',pay_bill='$maxbill',pay_by='$paymodes',pay_user='$csadded',pay_rmrk='$remarks'");
                        $instrn = mysqli_query($con, "INSERT INTO tbl_trans SET trn_ac='$custid',trn_name='$checkexpiry[name]',trn_amt='$amtpaid',trn_date=CURDATE(),trn_type='MONTHLY BILL',trn_gst=1,trn_grate='18',trn_gamt='$gstamt',trn_memo='Bill Amount received for $checkexpiry[name]',trn_billid='$maxbill'");

                    }

                }


                if ($res) {


                    $res1 = mysqli_query($con, "UPDATE adduser SET mnth='$mnth',yrs='$yrs',pexpiry='$expirydate',actv=1,price='$tbillamt',lpaydt='$paydt',lpayamt='$amtpaid',pay_ch='$cpaychannels' WHERE id='$custid'");


                    if ($postpaid == '0') {


                        if ($sendsms == '1') {

                            $checksms = f(q("SELECT COUNT(*) as total FROM tbl_sms"));
                            if (floatval($checksms['total']) <= 5000) {
                                $mobno = $checkexpiry['phone'];
                                if ($mobno != '') {
                                    $msgg = "Dear user your bill has been generated amount is $currentb. Paid amount is: $amtpaid";
                                    require("lib/sender.php");

                                    $obj = new Sender("8013928783", "39678", "PATSMS", $msgg, $mobno);
                                    $obj->Submit();





                                    $insms = mysqli_query($con, "INSERT INTO tbl_sms SET cnt=1");
                                    // echo $result;
    
                                }
                            }
                        }

                        ?>

                        <script type="text/javascript">
                            Swal
                                .fire({
                                    title: 'Bill Generated',
                                    text: 'Choose print format',
                                    icon: 'success',
                                    showCancelButton: true,
                                    confirmButtonText: 'Thermal Print',
                                    cancelButtonText: 'Standard Print'
                                })
                                .then(function (result) {
                                    if (result.value) {
                                        window.open('thermal_print.php?bill_id=<?= $maxbill ?>', '_blank');
                                    } else {
                                        window.open('getbills.php?bill_id=<?= $maxbill ?>', '_blank');
                                    }
                                });


                        </script>


                        <? $issendsms = '0';
                    } else {


                        if ($sendsms == '1') {
                            $mobno = $checkexpiry['phone'];
                            $checksms = f(q("SELECT COUNT(*) as total FROM tbl_sms"));
                            if (floatval($checksms['total']) <= 5000) {
                                if ($mobno != '') {

                                    $msgg = "Dear user your bill has been generated amount is $currentb. Due amount is: $dues";

                                    require("lib/sender.php");

                                    $obj = new Sender("8013928783", "39678", "PATSMS", $msgg, $mobno);
                                    $obj->Submit();
                                    $count = floatval($count) + 1;
                                    $insms = mysqli_query($con, "INSERT INTO tbl_sms SET cnt=1");

                                }

                            }
                        }

                        ?>

                        <script type="text/javascript">
                            window.open('print_bill.php?bill_id=<?= $maxbill ?>', '_blank');


                        </script>

                        <? $issendsms = '0';
                    }
                }

            } else { ?>

                <script type="text/javascript">
                    alert('Bill Already Generated');
                </script>

            <? }


            // $res=mysqli_query($con,"INSERT INTO tbl_lane SET lnname='$lnname',lnarid='$lnarid'");
    

        } else { ?>

            <script type="text/javascript">
                Swal.fire('Bill Already Generated on this date', '', 'error');
            </script>

        <?php }


    }




    ?>
    <?php include "ajax.php";


    if ($gcustid == '') {

        $currentdt = date("Y-m-d");
        $thirtyDaysUnix = strtotime('+29 days', strtotime($currentdt));
        $fetdt = date("Y-m-d", $thirtyDaysUnix);
        //echo "HELLO";
    
    } else {


        $currentdt = strtotime('+1 days', strtotime($getgc['pexpiry']));
        $currentdt = date("Y-m-d", $currentdt);
        $thirtyDaysUnix = strtotime('+29 days', strtotime($currentdt));
        $fetdt = date("Y-m-d", $thirtyDaysUnix);
    }

    $stdates = date("Y-m-d");
    $exppdat = strtotime('+29 days', strtotime($stdates));
    $exppdate = date("Y-m-d", $exppdat);

    ?>

    <script type="text/javascript">

        function getMonthName(month) {
            //alert(month);
            const monthNames = [
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "Jun",
                "Jul",
                "Aug",
                "Sep",
                "Oct",
                "Nov",
                "Dec"
            ];

            const d = new Date(2022, month, 10);
            // d.setMonth(month-1); const monthName = d.toLocaleString("default", {month:
            // "short"});
            const monthName = monthNames[month];
            return monthName;
        }
        function updateDuration() {
            var months = parseInt(document.getElementById('billing_months').value) || 1;
            var basePrice = parseFloat(document.getElementById('multiprice').value) || 0;

            // 1. Calculate new bill amount
            var newBillAmt = basePrice * months;
            document.getElementById('tbillamt').value = newBillAmt.toFixed(2);

            // Recalculate GST and billamt
            genGST(newBillAmt);

            // 2. Calculate new End Date
            var strdtVal = document.getElementById('strdt').value;
            if (strdtVal) {
                var date = new Date(strdtVal);
                if (!isNaN(date.getTime())) {
                    var newdate = new Date(date);
                    newdate.setDate(newdate.getDate() + (months * 30) - 1);

                    var dd = newdate.getDate();
                    var mm = newdate.getMonth() + 1;
                    var y = newdate.getFullYear();

                    if (dd < 10) dd = '0' + dd;
                    if (mm < 10) mm = '0' + mm;

                    var someFormattedDate = y + '-' + mm + '-' + dd;
                    document.getElementById('enddt').value = someFormattedDate;

                    var endo = new Date(someFormattedDate);
                    var mntho = endo.getMonth();
                    var ddl = document.getElementById('mnth');
                    var mname = getMonthName(mntho);

                    var opts = ddl.options.length;
                    for (var i = 0; i < opts; i++) {
                        if (ddl.options[i].value == mname) {
                            ddl.options[i].selected = true;
                            break;
                        }
                    }
                }
            }

            // 3. Recalculate total payment due including previous due/discount
            setpayamt();
        }

        function setdt(oldDate) {
            var tt = oldDate;
            var date = new Date(tt);
            if (isNaN(date.getTime())) {
                return;
            }
            var ddd = date.getDate();
            var mmm = date.getMonth() + 1;
            var yyy = date.getFullYear();

            var ssomeFormattedDate = yyy + '-' + mmm + '-' + ddd;
            document.getElementById('strdt').value = ssomeFormattedDate;

            var months = parseInt(document.getElementById('billing_months').value) || 1;
            var newdate = new Date(date);
            newdate.setDate(newdate.getDate() + (months * 30) - 1);

            var dd = newdate.getDate();
            var mm = newdate.getMonth() + 1;
            var y = newdate.getFullYear();

            if (dd < 10) dd = '0' + dd;
            if (mm < 10) mm = '0' + mm;

            var someFormattedDate = y + '-' + mm + '-' + dd;
            document.getElementById('enddt').value = someFormattedDate;

            var endo = new Date(someFormattedDate);
            var mntho = endo.getMonth();
            var ddl = document.getElementById('mnth');
            var mname = getMonthName(mntho);

            var opts = ddl.options.length;
            for (var i = 0; i < opts; i++) {
                if (ddl.options[i].value == mname) {
                    ddl.options[i].selected = true;
                    break;
                }
            }
        }

        function setpayamt() {

            var a = parseFloat(document.getElementById('discamt').value);
            var b = parseFloat(document.getElementById('billamt').value);
            var p = parseFloat(document.getElementById('prevdue').value);
            var oth = parseFloat(document.getElementById('oth_due').value);
            var fp = parseFloat(b) + parseFloat(p) + parseFloat(oth);

            if (a < fp) {

                var c = parseFloat(fp) - parseFloat(a);
                document
                    .getElementById('amtpaid')
                    .value = Math.round(c);

            } else {

                //alert("Discount amount cannot be greater than the bill amount");
                document
                    .getElementById('discamt')
                    .value = '0';
                document
                    .getElementById('amtpaid')
                    .value = fp;

            }

        }

        function setcur() {

            //document.getElementById('srch').focus();

        }
    </script>
    <style type="text/css">
        .srch {

            font-size: 16px;
        }

        label {

            font-size: 14px;
            font-weight: 600;
        }
    </style>
    <div class="main-container">
        <div class="pd-ltr-20 customscroll customscroll-10-p height-100-p xs-pd-20-10">
            <div class="min-height-200px">
                <div class="page-header">

                    <div class="row">
                        <div class="col-md-6 col-sm-12">
                            <div class="title">
                                <h4 style="margin-bottom:5px;">Generate Customer Bill</h4>
                            </div>

                        </div>
                        <div class="col-md-6 col-sm-12 text-right"></div>
                    </div>
                </div>
                <!-- Default Basic Forms Start -->
                <div class="row">

                    <div class="col-md-9 col-sm-12">
                        <div class="pd-20 bg-white border-radius-4 box-shadow mb-30" style="padding:10px;">

                            <small style="color: red;"><?= $msg ?></small>
                            <form
                                action="<?= $_SERVER['PHP_SELF'] ?>?action=<? if ($action == 'edit') { ?>update&cid=<?= $cid ?><? } else { ?>save<? } ?>"
                                method="POST" id="generatebill">

                                <div class="clearfix" style="min-height: 30px;"></div>
                                <input type="hidden" name="lnarid" id="lnarid" value="1">
                                <input type="hidden" name="sendsms" value="0">
                                <div class="form-group row">

                                    <label class="col-sm-12 col-md-2 col-form-label">A/C No</label>

                                    <div class="col-sm-12 col-md-6">
                                        <input class="form-control" type="text" name="serch" id="srch"
                                            placeholder="Acno"
                                            value="<? if ($gcustid != '') {
                                                echo $getgc['custid'];
                                            } else { ?><?php } ?>"
                                            required="required" onblur="getcust()">
                                    </div>
                                    <div class="col-md-3">
                                        <button type="button" class="btn btn-primary btn-sm" onclick="getcust()">
                                            <i class="fa fa-save"></i>
                                            Search</button>
                                    </div>
                                </div>
                                <div class="form-group row"
                                    style="border:1px solid black; border-radius: 5px;padding:2%;margin:0px 10px;">
                                    <input type="hidden" name="custid" id="custid">
                                    <div class="col-md-3">
                                        <span id="cname" class="srch"></span>
                                    </div>

                                    <!--<div class="col-md-3"><span id="cphone" class="srch"></span></div>-->
                                    <div class="col-md-3">
                                        <b>Phone:
                                        </b><input type="text" name="cphone" id="cphone" />
                                    </div>
                                    <div class="col-md-3">
                                        <span id="cacno" class="srch"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="cvc" class="srch"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="cstb" class="srch"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="cprice" class="srch"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="cexpiry" class="srch"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="cpack" class="srch"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="clpaydt" class="srch"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="clpayamt" class="srch"></span>
                                    </div>
                                    <div class="col-md-3">
                                        <span id="caddr" class="srch"></span>
                                    </div>

                                    <div class="col-md-12" id="alamulti">
                                        <b>Package:
                                        </b>
                                        <!-- <textarea id="cpaychannels" name="cpaychannels"
                                            style="width:100%;"></textarea>-->
                                        <input type="hidden" id="multiprice" name="multiprice" value="0">
                                        <input type="hidden" id="countch" name="countch" value="0">

                                        <select name="alacarte[]" id="alacarte" class="custom-select2 form-control"
                                            multiple="multiple" onchange="setids()">
                                            <? $count = 0;
                                            $getpack = mysqli_query($con, "SELECT * FROM tbl_pack WHERE ptype='4'");
                                            while ($arr = mysqli_fetch_array($getpack)) {
                                                $chkp = f(q("SELECT * FROM tbl_change_package_details WHERE pac_type='4'AND pac_id='$arr[pid]' AND customer_id='$custid'"));
                                                if ($chkp['pac_id'] == $arr['pid']) {
                                                    $alavalu = floatval($alavalu) + floatval($arr['prc']);
                                                    $count++;
                                                }
                                                ?>
                                                <option value="<?= $arr['pid'] ?>" <?php if ($chkp['pac_id'] == $arr['pid']) { ?>
                                                        selected="selected" <?php } ?> data="<?= $arr['prc'] ?>">
                                                    <?= $arr['pname'] ?></option>

                                            <? } ?>
                                        </select>

                                    </div>

                                </div>

                                <div class="form-group row">

                                    <div class="col-sm-12 col-md-2">
                                        <label class="col-sm-12 col-md-12 col-form-label">Start</label>
                                        <input class="form-control" type="text" placeholder="yyyy-mm-dd" id="strdt"
                                            name="strtdt" value="<?= $stdates ?>" onchange="setdt(this.value)">

                                    </div>

                                    <div class="col-sm-12 col-md-2">
                                        <label class="col-sm-12 col-md-12 col-form-label">Duration</label>
                                        <select class="form-control" name="billing_months" id="billing_months" onchange="updateDuration()">
                                            <option value="1">1 Month</option>
                                            <option value="2">2 Months</option>
                                            <option value="3">3 Months</option>
                                            <option value="4">4 Months</option>
                                            <option value="5">5 Months</option>
                                            <option value="6">6 Months</option>
                                            <option value="7">7 Months</option>
                                            <option value="8">8 Months</option>
                                            <option value="9">9 Months</option>
                                            <option value="10">10 Months</option>
                                            <option value="11">11 Months</option>
                                            <option value="12">12 Months</option>
                                        </select>
                                    </div>

                                    <div class="col-sm-12 col-md-2">
                                        <label class="col-sm-12 col-md-12 col-form-label">End</label>
                                        <input class="form-control" type="text" placeholder="yyyy-mm-dd" id="enddt"
                                            name="enddt" value="<?= $exppdate ?>">
                                    </div>

                                    <div class="col-sm-12 col-md-3">
                                        <label class="col-sm-12 col-md-12 col-form-label">Month</label>
                                        <select class="form-control" name="mnth" id="mnth">
                                            <option value="Jan" <? if (date('m') == '1') { ?> selected="selected" <? } ?>>Jan
                                            </option>
                                            <option value="Feb" <? if (date('m') == '2') { ?> selected="selected" <? } ?>>Feb
                                            </option>
                                            <option value="Mar" <? if (date('m') == '3') { ?> selected="selected" <? } ?>>Mar
                                            </option>
                                            <option value="Apr" <? if (date('m') == '4') { ?> selected="selected" <? } ?>>Apr
                                            </option>
                                            <option value="May" <? if (date('m') == '5') { ?> selected="selected" <? } ?>>May
                                            </option>
                                            <option value="Jun" <? if (date('m') == '6') { ?> selected="selected" <? } ?>>Jun
                                            </option>
                                            <option value="Jul" <? if (date('m') == '7') { ?> selected="selected" <? } ?>>Jul
                                            </option>
                                            <option value="Aug" <? if (date('m') == '8') { ?> selected="selected" <? } ?>>Aug
                                            </option>
                                            <option value="Sep" <? if (date('m') == '9') { ?> selected="selected" <? } ?>>Sep
                                            </option>
                                            <option value="Oct" <? if (date('m') == '10') { ?> selected="selected" <? } ?>>
                                                Oct</option>
                                            <option value="Nov" <? if (date('m') == '11') { ?> selected="selected" <? } ?>>
                                                Nov</option>
                                            <option value="Dec" <? if (date('m') == '12') { ?> selected="selected" <? } ?>>
                                                Dec</option>

                                        </select>
                                    </div>

                                    <div class="col-sm-12 col-md-3">
                                        <label class="col-sm-12 col-md-12 col-form-label">Year</label>
                                        <select class="form-control" name="yrs" id="yrs">
                                            <?
                                            for ($i = 2020; $i <= 2030; $i++) {
                                                ?>
                                                <option value="<?= $i ?>" <? if (date('Y') == $i) { ?> selected="selected" <? } ?>>
                                                    <?= $i ?></option>
                                            <? } ?>

                                        </select>
                                    </div>
                                </div>

                                <div class="form-group row">

                                    <div class="col-sm-12 col-md-4">
                                        <label class="col-sm-12 col-md-12 col-form-label">Bill Amount
                                            <span id="billdetails"></span></label>
                                        <input class="form-control" type="text" name="tbillamt" id="tbillamt" value=""
                                            onblur="genGST(this.value)">
                                        <input type="hidden" name="nogstval" value="0" id="nogstval">
                                    </div>

                                    <div class="col-sm-12 col-md-2">
                                        <label class="col-sm-12 col-md-12 col-form-label">Total</label>
                                        <input class="form-control" type="text" name="billamt" id="billamt" value="0"
                                            onblur="setpayamt()">
                                    </div>
                                    <div class="col-sm-12 col-md-2">
                                        <label class="col-sm-12 col-md-12 col-form-label">Previous Due</label>
                                        <input class="form-control" type="text" name="prevdue" id="prevdue" value="0"
                                            onblur="setpayamt()">
                                    </div>
                                    <div class="col-sm-12 col-md-2">
                                        <label class="col-sm-12 col-md-12 col-form-label">Disc. Amt</label>
                                        <input class="form-control" type="text" name="discamt" id="discamt" value="0"
                                            onblur="setpayamt()">
                                    </div>
                                    <div class="col-sm-12 col-md-2">
                                        <label class="col-sm-12 col-md-112 col-form-label">Amount Paid</label>
                                        <input class="form-control" type="text" name="amtpaid" id="amtpaid" value="">
                                    </div>

                                </div>

                                <div class="form-group row">

                                    <div class="col-sm-12 col-md-3">
                                        <label class="col-sm-12 col-md-12 col-form-label  pull-right">Payment
                                            Mode</label>
                                        <select class="form-control" name="paymodes">

                                            <option value="CASH">Cash</option>
                                            <option value="UPI">UPI</option>
                                            <option value="CHEQUE">Cheque</option>
                                            <option value="BANK_TRANSFER">Bank Transfer</option>
                                            <option value="CREDIT_CARD">Credit Card</option>
                                            <option value="DEBIT_CARD">Debit Card</option>
                                            <option value="ONLINE">Online Payment</option>
                                        </select>
                                    </div>

                                    <div class="col-sm-12 col-md-3">
                                        <label class="col-sm-12 col-md-12 col-form-label">Pay Date</label>
                                        <input class="form-control" type="text" placeholder="yyyy-mm-dd" id="paydt"
                                            name="paydt" value="<?php echo date('Y-m-d') ?>" <?php if ($_SESSION['ltype'] != '1') { ?> readonly="readonly" <?php } ?>>
                                    </div>

                                    <div class="col-sm-12 col-md-3">
                                        <label class="col-sm-12 col-md-12 col-form-label  pull-right">Postpaid
                                            Bill</label>
                                        <select class="form-control" name="postpaid" id="postpaid"
                                            onchange="setpaynow(this.value)">
                                            <option value="0">No</option>
                                            <option value="1">Yes</option>
                                        </select>
                                    </div>

                                    <div class="col-md-3">
                                        <label class="col-sm-12 col-md-12 col-form-label  pull-right">Remarks</label>
                                        <input type="text" class="form-control" name="remarks">

                                    </div>

                                    <div class="col-md-3">
                                        <label class="col-sm-12 col-md-12 col-form-label  pull-right">Other Due</label>
                                        <input type="text" class="form-control" name="oth_due" value="0" id="oth_due"
                                            onblur="setpayamt()">

                                    </div>
                                    <div class="col-md-6">
                                        <label class="col-sm-12 col-md-12 col-form-label  pull-right">Other Due
                                            Reason</label>
                                        <input type="text" class="form-control" name="oth_reason">

                                    </div>
                                    <div class="col-md-3">
                                        <label class="col-sm-12 col-md-12 col-form-label  pull-right">Lineman</label>
                                        <select name="lineman" class="form-control" id="lineman">
                                            <?php
                                            $linemanSql = "SELECT * FROM tbl_login WHERE $linemanFilter ORDER BY l_name";
                                            $ql = mysqli_query($con, $linemanSql);
                                            while ($arrcl = mysqli_fetch_array($ql)) {
                                                ?>
                                                <option value="<?php echo $arrcl['l_id'] ?>"><?php echo $arrcl['l_name'] ?>
                                                </option>
                                            <?php } ?>
                                        </select>

                                    </div>

                                </div>

                                <div class="clearfix">
                                    <div class="pull-left">
                                        <!--<h4 class="text-blue">Default Basic Forms</h4> <p class="mb-30 font-14">All
                                            bootstrap element classies</p>-->

                                    </div>
                                    <div class="pull-right">
                                        <button type="button" class="btn btn-danger btn-sm" onclick="postpaidpush()">
                                            <i class="fa fa-save"></i>
                                            Generate Postpaid Bill</button>
                                        <!-- <a href="#basic-form1" class="btn btn-danger btn-sm scroll-click"
                                            rel="content-y" data-toggle="collapse" role="button"><i class="fa fa-code"></i>
                                            Source Code</a> -->
                                        <button type="submit" id="submt" class="btn btn-success btn-sm" disabled="true">
                                            <i class="fa fa-save"></i>
                                            Generate & Pay</button>
                                    </div>
                                </div>
                            </form>
                            <div class="collapse collapse-box" id="basic-form1"></div>
                        </div>
                    </div>
                    <div class="col-md-3 col-sm-12">
                        <div class="pd-20 bg-white border-radius-4 box-shadow mb-30" style="padding:10px;">
                            <h4 class="text-blue">Search Customer</h4>
                            <div class="form-group">
                                <input type="text" class="form-control" name="searchcust" id="searchcust"
                                    placeholder="Search by Name/Acno/Fathers name/Phone" required>
                            </div>
                        </div>
                        <div class="pd-20 bg-white border-radius-4 box-shadow mb-30" style="padding:10px;"
                            id="searchcustomer">




                        </div>


                    </div>
                </div>

            </div>
            <?php include('include/footer.php'); ?>
        </div>
    </div>
    <?php include('include/script.php'); ?>

    <script type="text/javascript">

        function setpaynow(vals) {

            if (vals == 1) {

                document
                    .getElementById('amtpaid')
                    .value = 0;

            } else {

                document
                    .getElementById('amtpaid')
                    .value = document
                        .getElementById('billamt')
                        .value;
            }

        }

        function postpaidpush() {

            var element = document.getElementById('postpaid');
            element.value = 1;
            setpaynow(1);

            document
                .getElementById("generatebill")
                .submit(); //

        }

        function genGST(amts) {

            var nogst = (parseFloat(amts) * parseFloat(100)) / 118;
            //var gstamt = parseFloat(amts) * parseFloat(0.18);
            var gstamt = parseFloat(amts) - parseFloat(nogst);
            //var nogst = parseFloat(amts);
            var totamt = parseFloat(amts); //+ parseFloat(gstamt);

            // document
            //     .getElementById('billdetails')
            //     .innerHTML = "(Pack amt:" + nogst.toFixed(2) + " and gst amt: " + gstamt.toFixed(
            //         2
            //     ) + " )";
            document
                .getElementById('nogstval')
                .value = nogst.toFixed(2);
            document
                .getElementById('billamt')
                .value = totamt.toFixed(2);

        }

        function setids() {

            var totlp = [];
            var selected = [];
            var sum = 0;

            for (var option of document.getElementById('alacarte').options) {
                if (option.selected) {
                    selected.push(option.value);
                    totlp.push(option.getAttribute('data'));

                }

            }

            var count = selected.length;
            //document.getElementById('acc').innerHTML=count;
            for (let i = 0; i < totlp.length; i++) {
                sum += parseFloat(totlp[i]);
            }

            document
                .getElementById('tbillamt')
                .value = sum;
            document
                .getElementById('tbillamt')
                .focus();
            genGST(sum);    
            document
                .getElementById('billamt').value=sum;    
                
            setpayamt();
            document
                .getElementById('prevdue')
                .focus();
            setpayamt();
            
                
            setpayamt();
               
            document
                .getElementById('countch')
                .value = count;

            document
                .getElementById('multiprice')
                .value = sum;

            updateDuration();
        }
    </script>

    <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>
    <!-- buttons for Export datatable -->
    <script src="src/plugins/datatables/media/js/button/dataTables.buttons.js"></script>
    <script src="src/plugins/datatables/media/js/button/buttons.bootstrap4.js"></script>
    <script src="src/plugins/datatables/media/js/button/buttons.print.js"></script>
    <script src="src/plugins/datatables/media/js/button/buttons.html5.js"></script>
    <script src="src/plugins/datatables/media/js/button/buttons.flash.js"></script>
    <script src="src/plugins/datatables/media/js/button/pdfmake.min.js"></script>
    <script src="src/plugins/datatables/media/js/button/vfs_fonts.js"></script>
    <script>
        $('document').ready(function () {
            $('.data-table').DataTable({
                scrollCollapse: true,
                autoWidth: false,
                responsive: true,
                columnDefs: [
                    {
                        targets: "datatable-nosort",
                        orderable: false
                    }
                ],
                "lengthMenu": [
                    [
                        10, 25, 50, -1
                    ],
                    [
                        10, 25, 50, "All"
                    ]
                ],
                "language": {
                    "info": "_START_-_END_ of _TOTAL_ entries",
                    searchPlaceholder: "Search"
                }
            });
            $('.data-table-export').DataTable({
                scrollCollapse: true,
                autoWidth: false,
                responsive: true,
                columnDefs: [
                    {
                        targets: "datatable-nosort",
                        orderable: false
                    }
                ],
                "lengthMenu": [
                    [
                        10, 25, 50, -1
                    ],
                    [
                        10, 25, 50, "All"
                    ]
                ],
                "language": {
                    "info": "_START_-_END_ of _TOTAL_ entries",
                    searchPlaceholder: "Search"
                },
                dom: 'Bfrtip',
                buttons: ['copy', 'csv', 'pdf', 'print']
            });
            var table = $('.select-row').DataTable();
            $('.select-row tbody').on('click', 'tr', function () {
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                } else {
                    table
                        .$('tr.selected')
                        .removeClass('selected');
                    $(this).addClass('selected');
                }
            });
            var multipletable = $('.multiple-select-row').DataTable();
            $('.multiple-select-row tbody').on('click', 'tr', function () {
                $(this).toggleClass('selected');
            });

            setcur();
        });
    </script>

    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $(function () {
            $("#strdt").datepicker({ changeMonth: true, changeYear: true });
            //$( "#strdt" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
            $("#enddt").datepicker({ changeMonth: true, changeYear: true, dateFormat: "yy-mm-dd" });
                
                $("#paydt").datepicker(
                    { changeMonth: true, changeYear: true }
                );
                $("#paydt").datepicker("option", "dateFormat", "yy-mm-dd");
                $('#paydt').datepicker('setDate', 'today');
           
            //$( "#enddt" ).datepicker( "option", "dateFormat", "yy-mm-dd" );
        });

        window.setTimeout(setcur, 2000);

        $(document).ready(function () {
            $(window).keydown(function (event) {
                if (event.keyCode == 13) {
                    event.preventDefault();
                    return false;
                }
            });
        });
    </script>
    <?
    if ($gcustid != '') { ?>

        <script type="text/javascript">
            getcust();
        </script>

    <? }

    ?>

    <script>
        function sendAutoSMS(phone, message) {
            console.log('sendAutoSMS called with phone:', phone, 'and message:', message);
            if (phone && message) {
                // Encode the message for URL safety
                var encodedMsg = btoa(unescape(encodeURIComponent(message)));

                // Make AJAX call to send-sms.php
                $.ajax({
                    url: 'send-sms.php',
                    type: 'POST',
                    data: {
                        action: 'sendsms',
                        cphone: phone,
                        msgs: encodedMsg
                    },
                    dataType: 'json',
                    success: function (response) {
                        console.log('SMS sent successfully to', phone);
                        if (!response.success) {
                            console.error('SMS sending failed:', response.error || 'Unknown error');
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('SMS sending failed:', error);
                    }
                });
            } else {
                console.log('sendAutoSMS called but phone or message is missing');
            }
        }

        // Customer search functionality
        $(document).ready(function () {
            // Search customer on keyup
            $('#searchcust').on('keyup', function () {
                var searchTerm = $(this).val();
                if (searchTerm.length >= 2) {
                    searchCustomers(searchTerm);
                } else {
                    $('#searchcustomer').html('');
                }
            });
        });

        function searchCustomers(searchTerm) {
            $.ajax({
                url: 'searchcust.php',
                type: 'POST',
                data: {
                    action: 'search_customers',
                    term: searchTerm
                },
                success: function (response) {
                    $('#searchcustomer').html(response);
                }
            });
        }

        function selectCustomer(custid) {
            $('#srch').val(custid);
            getcust();
            $('#searchcustomer').html('');
        }
    </script>
    <?php

    if ($issendsms == '1') {
        ?>
        <script>
            // Send SMS automatically
            var phone = '<?= $checkexpiry["phone"] ?>';
            var msg = "<?php echo SITE_NAME; ?>\n\nDear user your bill has been generated amount is <?= $currentb ?>. Payment Amt is: <?php echo $amtpaid ?>. Due is" +
                ": <?= $dues ?>";
            sendAutoSMS(phone, msg);

        </script>
    <?php }

    ?>


</body>

</html>
