<?php
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include('includes/function.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
$admin = $_SESSION["admin_" . $dbname];

$formname = "No Sale - Datewise";
$file = "custnosale.php";

$maindb = "accmast";
$trandb = "actran";

mysqli_select_db($conn, $zdb);

$gcond = "";
$accond = "";
$stcond = "";
$ctcond = "";
$city = $_POST[city];
$state = $_POST[state];
$citycond = "";
$statecond = "";
if (!empty($_POST["acname"])) {
    $accode = trim($_POST["acname"]);
    $accond = " and accode = '$accode' ";
}
if (!empty($state)) {
    $statecond = " AND `state` = '$state' ";
}
if (!empty($city)) {
    $citycond = " AND `city` LIKE '%$city%' ";
}
$mfrmdate = $_POST["frmdt"];
$mtodate = $_POST["todt"];
$notfound = $_POST["notfnd"];

if (isset($_POST["submit"])) {

    $message = $_POST["sms"];
//    $mobileno = $_POST["mobileno"];

    $mobilenumbers = array();

    foreach ($_POST['check_list'] as $to) {
        $mobilenumbers = "$to";
//    browse($message);
//    browse($mobilenumbers);


        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://app.rapbooster.com/api/sendMsg',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => array('apiAuthkey' => '6a9f4ac6eda804fb0ab6', 'msg' => "$message", 'receiverMobile' => "91$mobilenumbers"),
        ));

        $response = curl_exec($curl);
//    print $response;

        curl_close($curl);
//        echo $response;
        browse("SMS Send to Customer");

        echo "<script>"
        . "window.close();"
        . "</script>";
    }
}

if (empty($mfrmdate)) {
    browse("From Date Cannot Be Empty");
    echo "<script>"
    . "window.close();"
    . "</script>";
}

if (empty($mtodate)) {
    browse("To Date Cannot Be Empty");
    echo "<script>"
    . "window.close();"
    . "</script>";
}

if ($mfrmdate > $mtodate) {
    browse("To Date Cannot Be Less Than From Date");
    header("refresh: 1; custsale.php");
    exit();
}

if (isset($_POST["view"])) {

    $getacc = mysqli_query($conn, "SELECT * FROM `accmast` WHERE grpcode = '010' $accond $statecond $citycond order by name") or die(mysqli_error($conn));
    $fetacc = mysqli_fetch_array($getacc);
    $acname = $fetacc['name'];

    $gettran = mysqli_query($conn, "SELECT * FROM `accmast` WHERE grpcode = '010' and accode not in (Select accode from actran
                          where date >= '$mfrmdate' and date <= '$mtodate' and (source = 'SL' or source = 'SLTX') ) $statecond $citycond  order by name") or die(mysqli_error($conn));

//print table($gettran);
    include("includes/linkshead.php");
    $mfdt = date("d-m-Y", strtotime($mfrmdate));
    $mtdt = date("d-m-Y", strtotime($mtodate));
    ?>
    <style>
        table th{
            background-color: #337AB7;
        }
    </style>
    <!--    <script type="text/javascript">
        $(document).ready(function () {
            //        left side
            $(".dtlsale").hide();
            $(".dtlsale2").hide();
            $("body").on('dblclick', '.getdtl', getDetails);
            $("body").on('dblclick', '.getdtl2', getDetails2);
            $("body").on('dblclick', '.dtlhide1', hideDetails);
            $("body").on('dblclick', '.dtlhide2', hideDetails2);
            function getDetails() {
                var trid = $(this).closest('tr').attr('id');
                var idval = trid.split('_')[1];
                $("#dtlsale_" + idval).show();
            }
            function getDetails2() {
                var trid = $(this).closest('tr').attr('id');
                var idval = trid.split('_')[1];
                $("#dtlsale2_" + idval).show();
            }
            function hideDetails() {
                var trid = $(this).closest('tr').attr('id');
                var idval = trid.split('_')[1];
                $("#dtlsale_" + idval).hide();
            }
            function hideDetails2() {
                var trid = $(this).closest('tr').attr('id');
                var idval = trid.split('_')[1];
                $("#dtlsale2_" + idval).hide();
            }

            //        right side
            $(".rdtlsale").hide();
            $(".rdtlsale2").hide();
            $("body").on('dblclick', '.rgetdtl', getDetailsr);
            $("body").on('dblclick', '.rgetdtl2', getDetailsr2);
            $("body").on('dblclick', '.rdtlhide1', hideDetailsr);
            $("body").on('dblclick', '.rdtlhide2', hideDetailsr2);
            function getDetailsr() {
                var trid = $(this).closest('tr').attr('id');
                var idval = trid.split('_')[1];
                $("#rdtlsale_" + idval).show();
            }
            function getDetailsr2() {
                var trid = $(this).closest('tr').attr('id');
                var idval = trid.split('_')[1];
                $("#rdtlsale2_" + idval).show();
            }
            function hideDetailsr() {
                var trid = $(this).closest('tr').attr('id');
                var idval = trid.split('_')[1];
                $("#rdtlsale_" + idval).hide();
            }
            function hideDetailsr2() {
                var trid = $(this).closest('tr').attr('id');
                var idval = trid.split('_')[1];
                $("#rdtlsale2_" + idval).hide();
            }
        });

    </script>-->
    <script type="text/javascript">
        function checkAll(ele) {
            var checkboxes = document.getElementsByTagName('input');
            if (ele.checked) {
                for (var j = 0; j < checkboxes.length; j++) {
                    if (checkboxes[j].type == 'checkbox') {
                        checkboxes[j].checked = true;
                    }
                }
            } else {
                for (var j = 0; j < checkboxes.length; j++) {
                    console.log(j)
                    if (checkboxes[j].type == 'checkbox') {
                        checkboxes[j].checked = false;
                    }
                }
            }
        }
    </script>

    </head>

    <body id="ledger">   
        <form name="myform" method="post">

            <div class="row" style="padding : 1%">
                <div class="col-lg-1"></div>
                <div class="col-lg-10">
                    <?php include ("includes/head_rep.php"); ?>
                    <div class="box">
                        
                        <div id="sortableTable" class="body collapse in">
                            <table>
                                <tr align="right">
                                    <td align="right"  style='text-align:right;'>
                                        <b style="font-weight:900;font-size: 16px">
                                            Message
                                        </b>
                                    </td>
                                    <td align="left">
                                        <p style="padding:0px; margin: 0px;">
                                            <textarea rows="5" cols="50" name="sms" id="sms"></textarea>
                                            <!--maxlength="160"-->
                                        </p>
                                    </td>              
                                </tr>   
                                <tr>   

                                    <td colspan="2" align="center">
                                        <p style="padding:4px; margin: 4px;">
                                            <input type="submit" name="submit" class=" btn" id="submit" value="Send" style="width:193px;height: 40px;background-color: cadetblue;color: white"/>
                                        </p>
                                    </td>
                                </tr> 
                            </table>
                            <table class="table table-bordered sortableTable responsive-table">

                                <thead>
                                    <tr>
                                        <th style="width:5%">Sr.</th>
                                        <th style="width:25%">Customer Name</th>
                                        <th style="width:7%">Mobile No.</th>
                                        <th style="width:7%">City</th>
                                        <th style="width:10%">Last Bill No.</th>
                                        <th style="width:10%">Bill Date</th>
                                        <th style="width:10%">Bill Amount</th>
                                        <th style="width:7%">
                                            <input type="checkbox" name="Check_ctr" onchange="checkAll(this)" id="example-select-all" class="chk" value="<?php echo $row['mobile']; ?>"
                                                   onClick="Check(document.myform.check_list)" style="height:25px;width: 25px;">
                                        </th>
                                    </tr>
                                </thead>
                                <tbody class="tbody">

                                    <?php
                                    $totcash = $totbank = $tottrf = $mnctr = 0;

                                    while ($fetacc = mysqli_fetch_array($gettran)) {

                                        $accode = $fetacc['accode'];
                                        $name = $fetacc['name'];

                                        $getbill = mysqli_query($conn, "SELECT *, DATE_FORMAT(date,'%d-%m-%Y') as mydt from actran where accode = '$accode' 
                                                            and date < '$mfrmdate' and (source = 'SL' or source = 'SLTX') order by date desc limit 1") or die(mysqli_error($conn));
                                        $fetbill = mysqli_fetch_array($getbill);
                                        $norows = mysqli_num_rows($getbill);
                                        $city = $fetacc['city'];
                                        $mobile = $fetacc['mobile'];

                                        if ($norows > 0) {
                                            $vouchno = $fetbill['vouchno'];
                                            $billdate = $fetbill['mydt'];
                                            $billamt = abs($fetbill['amount']);
                                        } else {
                                            if ($notfound == "Y") {
                                                continue;
                                            } else {
                                                $vouchno = 'Not Found';
                                                $billdate = '';
                                                $billamt = 0;
                                            }
                                        }
                                        $mnctr++;


                                        echo "<tr>";
                                        echo "<td>$mnctr</td>";
                                        echo "<td>$name</td>";
                                        echo "<td>$mobile</td>";
                                        echo "<td>$city</td>";
                                        echo "<td>$vouchno</td>";
                                        echo "<td>$billdate</td>";
                                        echo "<td class='text-right'>" . number_format($billamt, 2) . "</td>";
                                        ?>
                                    <td>
                                        <input type="checkbox" value="<? echo $fetacc['mobile']; ?>" id="check_list" class="chk" name="check_list[]" style="height:20px;width:20px"/>
                                    </td>
                                    <?php
                                    echo "</tr>";
                                }
                                ?>
                                </tbody>
                            </table>    
                        </div>
                    </div>
                </div>
            </div>
            <?php include("includes/linksfoot.php"); ?>
        </form>
    </body>
    </html>
    <?php
}

if (isset($_POST["excel"])) {

    $getacc = mysqli_query($conn, "SELECT * FROM `accmast` WHERE grpcode = '010' $accond  $statecond $citycond   order by name") or die(mysqli_error($conn));
    $fetacc = mysqli_fetch_array($getacc);
    $acname = $fetacc['name'];

    $gettran = mysqli_query($conn, "SELECT * FROM `accmast` WHERE grpcode = '010' and accode not in (Select accode from actran
                          where date >= '$mfrmdate' and date <= '$mtodate' and (source = 'SL' or source = 'SLTX') )  $statecond $citycond   order by name") or die(mysqli_error($conn));


    $contents .= "No sale," . $getac['name'] . "\n";

    $contents .= "Sr, Name, Mobile, City, Bill Date, Amount\n";

    $ctr = 1;

    while ($fetacc = mysqli_fetch_array($gettran)) {

        $accode = $fetacc['accode'];
        $name = $fetacc['name'];

        $getbill = mysqli_query($conn, "SELECT *, DATE_FORMAT(date,'%d-%m-%Y') as mydt from actran where accode = '$accode' 
                                     and date < '$mfrmdate' and (source = 'SL' or source = 'SLTX') order by date desc") or die(mysqli_error($conn));
        $fetbill = mysqli_fetch_array($getbill);
        $norows = mysqli_num_rows($getbill);
        $city = $fetacc[city];
        $mobile = $fetacc[mobile];

        if ($norows > 0) {
            $vouchno = $fetbill['vouchno'];
            $billdate = $fetbill['mydt'];
            $billamt = abs($fetbill['amount']);
        } else {
            if ($notfound == "Y") {
                continue;
            } else {
                $vouchno = 'Not Found';
                $billdate = '';
                $billamt = 0;
            }
        }
        $mnctr++;

        $contents .= "$ctr" . ",";
        $contents .= "$name" . ",";
        $contents .= "$mobile" . ",";
        $contents .= "$city" . ",";
        $contents .= "$billdate" . ",";
        $contents .= "$amt" . "\n";
    }
    $contents .= ",Total" . ",,,,,";
    $contents .= "$totqty" . ",";
    $contents .= "$totleft" . "\n";

    $contents = strip_tags($contents);
    header("Content-Disposition: attachment; filename=$formname" . date('d-m-Y') . ".csv");
    print $contents;
}
?>