<?php include '../header.php'; ?> <?php include '../sidemenu.php'; ?>

<style type="text/css">
.no-js #loader { display: none;  }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
.se-pre-con {
	position: absolute;
	left: 0px;
	top: 0px;
	width: 12%;
	height: 12%;
	z-index: 9999;
	margin: 70px 45%;
	background: url(<?=$app_url;?>loading_gif/loader-64x/Preloader_2.gif) center no-repeat #fff;
}
</style>

<div class="content-wrapper" style="min-height: 1203.6px;">
	<!-- Content Header (Page header) -->
	<section class="content-header">
		<div class="container-fluid">
			<div class="row mb-2">
				<div class="col-md-6">
					<h3>SMS</h3>
				</div>
				<div class="col-md-6">
				</div>
			</div>
		</div>
	</section>

    <section class="content">
		<div class="container-fluid">
			<div class="row">
				<div class="col-md-12">
					<div class="card card-outline card-primary">
						<div class="card-header">
							<h3 class="card-title">SMS</h3>
						</div>
						<div class="overlay white" id="loading" style="display:none;position: absolute;width: 100%;height: 100%;z-index: 10000;">
							<i class="fas fa-3x fa-sync-alt rotate360"  style="margin: 70px 45%;"></i>
						</div>
						<form role="form" id="frmEntry">

                            <div class="card-header p-0 border-bottom-0">
                                <ul class="nav nav-tabs" role="tablist">
                                    <li class="nav-item optStatus" data-status="1">
                                        <a class="nav-link active" id="tab_expired" name="optStatus" data-toggle="pill" href="#tab1" role="tab" aria-selected="false">1</a>
                                    </li>
                                    <li class="nav-item optStatus" data-status="2">
                                        <a class="nav-link " id="tab_reminder" name="optStatus" data-toggle="pill" href="#tab1" role="tab" aria-selected="false">2</a>
                                    </li>
                                </ul>
                            </div>

							<div class="card-body" id='frmNormal'>
								<div class="row">                                 
                                    <div class="col-md-4">
										<div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">SMS Balance:</label>
                                            <div class="col-md-8">
                                                <input type="text" class="form-control" id="txtSMSBalance" style="text-align:right;" disabled>
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">Today Date: </label>
                                            <div class="col-md-8">  
                                                <div class="input-group input-append date" id="datePicker" data-date="2020-02-17" data-date-format="yyyy-mm-dd">
                                                    <div class="input-group-prepend">
                                                        <span class="input-group-addon input-group-text" style="width: 40px; display: table-cell;">
                                                            <i class="far fa-calendar-alt"></i>
                                                        </span>
                                                    </div>
                                                    <input type="text" class="form-control float-right" id="txtDatePicker" value="1982-06-15" disabled>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">City:</label>
                                            <div class="col-md-8">
                                                <select type="text" class="form-control" id="cboCity"></select>
                                            </div>
                                        </div>
										<input class="custom-control-input" type="radio" id="optAll" name="optType" value=""  style="display:none;" checked>
										<div class="input-group mb-3">
											<label class="col-md-4 col-form-label" style="text-align: right;">Expired:  </label> 
										<div class="col-md-7">
										<input type="text" class="form-control rounded-0" id="txtExpired" style="text-align:right;" disabled>
										<div>

										</div></div>

											<div class="col-md-1">
												<div class="custom-control custom-radio">
													<input class="custom-control-input" type="radio" id="optExpired" name="optType" value="expired">
													<label for="optExpired" class="custom-control-label"></label>
												</div>
											</div>
										</div>

										<div class="input-group mb-3">
											<label class="col-md-4 col-form-label" style="text-align: right;">Reminder:  </label> 
										<div class="col-md-7">
										<input type="text" class="form-control rounded-0" id="txtReminder" style="text-align:right;" disabled>
										<div>

										</div></div>

											<div class="col-md-1">
												<div class="custom-control custom-radio">
													<input class="custom-control-input" type="radio" id="optReminder" name="optType" value="reminder">
													<label for="optReminder" class="custom-control-label"></label>
												</div>
											</div>
										</div>
                                    </div>
									<div class="col-md-1"></div>
									<div class="col-md-7" id='myTable'>
										<div class="card-body p-0">
											<table class="table  table-responsive table-head-fixed table-bordered" id="myTable" style="max-height: 389px;font-size:12px;" >
												<thead>                  
													<tr>
														<th style="width: 3%;">#</th>
														<th style="text-align: center; width: 15%;">Phone</th>
														<th>Message</th>
														<th style="text-align: center; width: 10%;">All &nbsp;<div class="icheck-info d-inline"><input type="checkbox" id="chkSelectAll" ><label for="chkSelectAll"></label></div></th>
													</tr>
												</thead>
												<tbody>
												</tbody>
											</table>
										</div>
										<br>
										<div class="form-group row">
										<div class="col-md-8"></div>
											<div class="col-md-4">
												<button type="button" class="btn btn-info btn-block" onclick="sendAllSMS();" id="btnSave" style="display:none;"><span class="fas fa-paper-plane">&nbsp;&nbsp;Send All <span id="txtSMSType"> </span></span></button>
											</div>					
										</div>
									</div>
								</div>
							</div>

                            <div class="card-body" id='frmAll' style='display:none;'>
								<div class="row">                                 
                                    <div class="col-md-4">
										<div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">SMS Balance:</label>
                                            <div class="col-md-8">
                                                <input type="text" class="form-control" id="txtSMSBalance2" style="text-align:right;" disabled>
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">City:</label>
                                            <div class="col-md-8">
                                                <select type="text" class="form-control" id="cboCity2"></select>
                                            </div>
                                        </div>	
                                        <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;">Message:</label>
                                            <div class="col-md-8">
                                                <textarea type="text" class="form-control "   rows="6" name="message" id="message" ></textarea>
                                            </div>
                                        </div>	
                                        <div class="form-group row">
                                            <label class="col-md-4 col-form-label" style="text-align: right;"></label>
                                            <div class="col-md-8">
                                            <ul id="sms-counter" class="alert alert-danger">
                                            <li>Encoding: <span class="encoding"></span></li>
                                            <li>Length: <span class="length"></span></li>
                                            <li>Messages: <span class="messages"></span></li>
                                            <li>Per Message: <span class="per_message"></span></li>
                                            <li>Remaining: <span class="remaining"></span></li>
                                            </ul>
                                            </div>
                                        </div>	
                                      
                                    </div>
									<div class="col-md-1"></div>

									<div class="col-md-7" id='myTable2'>
									<div class="form-group row">
                                            <label class="col-md-8 col-form-label" style="text-align: right;"></label>
                                            <div class="col-md-4">
                                                <input type="text" class="form-control" id="txtSearch"   placeholder='Search'>
                                            </div>
                                        </div>
										<div class="card-body p-0">
											<table class="table  table-responsive table-head-fixed table-bordered" id="myTable2" style="max-height: 389px;font-size:12px;">
												<thead>                  
													<tr>
														<th style="width: 3%;">#</th>
                                                        <th>Customer Name</th>
														<th style="text-align: center; width: 15%;">Phone</th>
														<th style="text-align: center; width: 10%;">All &nbsp;<div class="icheck-info d-inline"><input type="checkbox" id="chkSelectAll2" ><label for="chkSelectAll2"></label></div></th>
													</tr>
												</thead>
												<tbody>
												</tbody>
											</table>
										</div>
										<br>
										<div class="form-group row">
										<div class="col-md-8"></div>
											<div class="col-md-4">
												<button type="button" class="btn btn-info btn-block" onclick="sendAllSMS2();" id="btnSave2" style="display:none;"><span class="fas fa-paper-plane">&nbsp;&nbsp;Send All</span></button>
											</div>					
										</div>
									</div>
								</div>
							</div>

						</form>
					</div>
				</div>

				
			</div>
		</div>
	</section>
</div>
<?php include '../footer.php'; ?>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script src="plug/sms_counter.min.js"></script>

<script>
	$('#message').countSms('#sms-counter');
	var C = '<?php echo $_SESSION['city']?>';
	var d = new Date();
	var mm = (d.getMonth("MM")+1);
	var dd = d.getDate();
	var customDate = d.getFullYear() + "-" + ((mm<10)?"0" + mm:mm) + "-" +  ((dd<10)?"0" + dd:dd);
	$('#datePicker').attr("data-date",customDate);
	$("#txtDatePicker").val(customDate);

	var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-36251023-1']);
  _gaq.push(['_setDomainName', 'jqueryscript.net']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

		// $j("#datepicker").datepicker();
	getSMSBalance();
        $('#frmNormal').removeAttr("display","none;");
		$("body").addClass("sidebar-collapse");
		if(C=='Main Office'){
			getAllCity();
		}else{
			$("#cboCity").append("<option value= '" + C + "'  >" + C + "</option>");	
            $("#cboCity2").append("<option value= '" + C + "'  >" + C + "</option>");	
		}
		getAll();
			// $('#datePicker').datepicker();
  })();


	$(".optStatus").on('click', function(e){
        if($(this).attr("data-status")=="1"){
            $("#frmNormal").removeAttr("style", "display:none;");
            $("#frmAll").attr("style", "display:none;");
        }else{
            $("#frmAll").removeAttr("style", "display:none;");
            $("#frmNormal").attr("style", "display:none;");
        }
	});

	function getSMSBalance(){

		$.ajax({
			url: APP_URL + "api/AUTh/check_sms_balance.php"
		}).done(function(data) {
			$("#txtSMSBalance").val(data);
            $("#txtSMSBalance2").val(data);
		});
	}

	$("#txtSearch").on("keyup", function() {
			var value = $(this).val().toLowerCase();
			$("#myTable2 > tbody > tr ").filter(function() {      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
			});
		});

	function getAllCity(){
		$("#cboCity").find("option").remove();
		$("#cboCity").append("<option value= '' data-id = ''></option>");
        $("#cboCity2").find("option").remove();
		$("#cboCity2").append("<option value= '' data-id = ''></option>");
		$.ajax({
			url: APP_URL + "api/city/get_all_rows.php"
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				$("#cboCity").append("<option value= '" + v.name + "' data-code= '" + v.code + "' >" + v.name + "</option>");
                $("#cboCity2").append("<option value= '" + v.name + "' data-code= '" + v.code + "' >" + v.name + "</option>");						
			});		
		});
	}


	$("#cboCity").change(function(){
		// create();
		getAll();
		getList();
	});

    $("#cboCity2").change(function(){
		// create();
		getList2();
	});

	$("#txtDatePicker").change(function(){
		getAll();
		getList();
	});

	$('input[type=radio][name=optType]').on('change', function() {
		// create();
		getList();
		$("#txtSMSType").text($(this).val().toUpperCase());

	});

	function getList2(){
		var city = $("#cboCity2").val();
		$("#myTable2").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/customer/get_all_rows_list.php",
			type: "POST",
			data: JSON.stringify({ city: city }),
		}).done(function(data) {
			console.log(data);
			$("#total_records").text("");
			$.each(data.records, function(i, v) {
				if(data.records){$("#total_records").text(" - " + data.records.length + " records");}else{$("#total_records").text(" - " + 0 + " record(s) found.");}
                if(data.records.length>0){
                    $("#btnSave2").attr("style", "display:block;");
                }else{
                    $("#btnSave2").attr("style", "display:none;");
                }
				console.log(v);
				$("#myTable2").find("tbody")
				.append($('<tr>')
					.append("<td style='width: 10px'>" + (i+1) + "</td>")
                    .append("<td style='display:none;'>" + v.id + "</td>")
					.append("<td>" + v.name + "</td>")
					.append("<td>" + v.phone + "</td>")
                    .append("<td style='text-align: center;'><div class='icheck-info d-inline'><input type='checkbox' id='" + v.id + "' class='itemc2'><label for='" + v.id + "'></label></div></td>")
					// .append("<td><button type='button' class='btn btn-block btn-success btn-sm fas fa-edit' onclick='edit(\"" + v.id + "\", this)' style='padding: 0px 13px;font-size: 20px; min-width: 37px'></button></td>")
					)
			});
		});
	} 

	function getAll(){
		var date = $("#txtDatePicker").val();
		var city = $("#cboCity").val();
		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/sales/get_sms_list.php",
			type: "POST",
			data: JSON.stringify({ date: date, city: city }),
		}).done(function(data) {
			console.log(data);
			$("#txtExpired").val(data.total_expired_count);
			$("#txtReminder").val(data.total_reminder_count);
			// $("#txtRenew").val(data.total_renew_count);
			// $("#txtCED").val(data.ced_count);
		});
	}

	function getList(){
		$('#myTable').append('<div class="se-pre-con"></div>');    
		// $("#loading").css("display","block");
		var date = $("#txtDatePicker").val();
		var city = $("#cboCity").val();
		var sms_type = $('input[name=optType]:checked').val();

		$("#myTable").find("tbody").find("tr").remove();
		$.ajax({
			url: APP_URL + "api/sales/get_sms_detail_list.php",
			type: "POST",
			data: JSON.stringify({ date: date, city: city, sms_type: sms_type }),
		}).done(function(data) {

			$(".se-pre-con").fadeOut("slow");
			if(data.detail.length>0){
				$("#btnSave").attr("style", "display:block;");
			}else{
				$("#btnSave").attr("style", "display:none;");
			}
			$("#loading").css("display","none");
			$("#myTable").find("tbody").find("tr").remove();
			$.each(data.detail, function(i, v) {
				$("#myTable").find("tbody")
				.append($('<tr>')
					.append("<td>" + (i+1) + "</td>")
					.append("<td style='display:none;'>" + v.id + "</td>")
					.append("<td>" + v.phone + "</td>")
                    .append("<td>" + v.msg + "</td>")
					.append("<td style='text-align: center;'><div class='icheck-info d-inline'><input type='checkbox' id='" + v.id + "' class='itemc'><label for='" + v.id + "'></label></div></td>")
					// onclick='sendSMS(\"" + v.id + "\",\"" + v.phone + "\"," + v.msg + ",this)'
					// .append("<td style='text-align:center;'><span class='btn btn-info btn-sm' style='cursor:pointer; font-size: 12px; width: 50px;' onclick='sendSMS(" + v.id + ",\"" + sms_type + "\",this)'><i class='fas fa-paper-plane' title='Send'></i></span></td>")
				);
			});	
		});
	}

	$("#chkSelectAll").click(function() {
	    if ($(this).is(':checked')) {
	        $('.itemc').prop('checked', true);
	    } else {
	        $('.itemc').prop('checked', false);
	    }
	});

    $("#chkSelectAll2").click(function() {

			var value = "";
			$("#myTable2 > tbody > tr ").filter(function() {      $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
			});

	    if ($(this).is(':checked')) {
	        $('.itemc2').prop('checked', true);
	    } else {
	        $('.itemc2').prop('checked', false);
	    }
	});

	function sendAllSMS(){

	$("#loading").css("display", "block");
	var details = [];
	$("#myTable tbody tr td input[type='checkbox']".is(":checked")).each(function (){
			var detail = {
				"sid" : $(this).parent().parent().find("td").eq(1).text()
			}
			details.push(detail);
	});

	var detail_list = {
		"date":  $("#txtDatePicker").val(),
		"sms_type": $('input[name=optType]:checked').val(),
		"details": details
	}

	if(details.length==0){
		bootbox.alert("Please choose Invoice.");
		$("#loading").css("display", "none");
		return false;
	}else{
		$("#loading").css("display", "none");
		bootbox.confirm({
			message: "<h4>Are you sure?</h4>",
			buttons: {
				confirm: {
					label: '<span class="glyphicon glyphicon-ok"></span> Yes',
					className: 'btn-primary'
				},
				cancel: {
					label: '<span class="glyphicon glyphicon-remove"></span> No',
					className: 'btn-danger'
				}
			},
			callback: function (result) {
				if(result){
					$.ajax({
						url: APP_URL + "api/AUTh/send_allsms.php",
						type: "POST",
						data: JSON.stringify(detail_list)
					}).done(function(data) {
						if(data.msg=="send"){
							$('#chkSelectAll').prop('checked', false);
							getAll();
							getList();
							getSMSBalance();
							bootbox.alert("SMS Sent Successfully.");
						}else{
							bootbox.alert("Error on server side.");
						}
					});
				}
			}
		});
	}
}

function sendAllSMS2(){

$("#loading").css("display", "block");
var details = [];
$("#myTable2 tbody tr td input[type='checkbox']").each(function (){
    var ischecked = $(this).is(":checked");
    if(ischecked){
        var detail = {
            "sid" : $(this).parent().parent().parent().find("td").eq(1).text(),
			"phone" : $(this).parent().parent().parent().find("td").eq(3).text()
        }
        details.push(detail);
    }
});

var detail_list = {
    "description":  $("#message").val(),
    "details": details
}

if(details.length==0){
    bootbox.alert("Please choose Customer.");
    $("#loading").css("display", "none");
    return false;
}else{
    $("#loading").css("display", "none");
    bootbox.confirm({
        message: "<h4>Are you sure?</h4>",
        buttons: {
            confirm: {
                label: '<span class="glyphicon glyphicon-ok"></span> Yes',
                className: 'btn-primary'
            },
            cancel: {
                label: '<span class="glyphicon glyphicon-remove"></span> No',
                className: 'btn-danger'
            }
        },
        callback: function (result) {
            if(result){
                $.ajax({
                    url: APP_URL + "api/AUTh/send_allsms_customer.php",
                    type: "POST",
                    data: JSON.stringify(detail_list)
                }).done(function(data) {
                    if(data.msg=="send"){
                        $('#chkSelectAll').prop('checked', false);
						$("#message").val("");
                        getSMSBalance();
                        bootbox.alert("SMS Sent Successfully.");
                    }else{
                        bootbox.alert("Error on server side.");
                    }
                });
            }
        }
    });
}
}

	
</script>
