
@extends('layouts.app')
@section('title', 'Edit DID')
@section('content')
<meta name="csrf-token" content="{{ csrf_token() }}"> 
<style>
      
      #preloader {
            background-color: black;
            bottom: 0;
            left: 0;
            position: fixed;
            right: 0;
            top: 0;
            z-index: 2147483647;
        }
        #preloader-status {
            background: center center no-repeat;
            height: 80px;
            left: 50%;
            top: 50%;
            position: absolute;
            width: 80px;
            margin: -40px 0 0 -40px;
        }
    </style>
<section class="content">
			<div class="row">			  
				<div class="col-lg-12 col-12">
					  <div class="box">  
                        <div id="preloader"style="display:none;">
                            <div id="preloader-status">
                                <img  src="assets/images/loader-30px.gif">
                            </div>  
                        </div>                              
							 <div class="box-body">
								<h4 class="box-title text-info mb-0"><i class="fa fa-edit me-15"></i> Buy Phone Number From DIDForSale</h4>
                                <a href="{{url('/did')}}" type="button" style="float:right" class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5"><i class="fa fa-eye fa-sx"></i> Show Phone Number</a>

								<hr class="my-15">
							    <div class="row">
								  <div class="col-md-6">
                                    <div class="form-group">
									    <label class="form-label">Country</label>
                                        <div class="input-group mb-3">
                                            <span class="input-group-text"><i class="ti-world"></i></span>
                                            <select id="country" class="form-select">
                                    <option value="1">United States (+1)</option>
                                    <option value="1">Canada (+1)</option>
                                    <option value="44">United Kingdom (+44)</option>
                                </select>							</div>
                                        </div>
								    </div>
								    <div class="col-md-6">
                                        <div class="form-group">
                                        <label class="form-label">Number Type  </label>
                                            <div class="input-group mb-3">
                                                <span class="input-group-text @error('caller_id') text-danger border-danger @enderror"><i class="ti-user"></i></span>
                                                <select id="numberType" class="form-select">
                                    <option value="local">Local</option>
                                    <option value="tollfree">Toll Free</option>
                                </select>
                                            </div>
                                        </div>
                                    </div>
							
                               
                                    <div class="col-md-6">
                                        <div class="form-group @error('description') has-error @enderror">
                                        <label class="form-label">Show</label> 
                                            <div class="input-group mb-3">
                                                    <span class="input-group-text @error('caller_id') text-danger border-danger @enderror"><i class="ti-user"></i></span>
                                                    <select id="show" class="form-select">
                                                        <option value="10">10</option>
                                                        <option value="20">20</option>
                                                        <option value="50">50</option>
                                                    </select>
                                                </div>
                                            </div>
                                    </div>
								  <div class="col-md-6">
									<div class="form-group">
									  <label class="form-label">Number</label>
                                        <div class="input-group mb-3">
                                            <span class="input-group-text @error('caller_id') text-danger border-danger @enderror"><i class="ti-mobile"></i></span>

                                            <input id='phone' type="text" class="form-control"  />
								
                                        </div>
								  </div>
								  </div>
                                </div>
							
                       
                          
                            
                        
                               
                          
                        
                          
      
                         
                           
                      
                          
                           
							<!-- /.box-body -->
							<div class="box-footer text-end">
								<a href="/did"><button type="button" class="btn btn-warning me-1">
								  <i class="ti-trash"></i></a> Cancel
								</button>
								<button onclick="getDidList();"type="submit" name="submit" value="add" class="btn btn-primary">
								  <i class="ti-save-alt"></i> Submit
								</button>
							</div>  
                              <!-- /.row -->
          <div class="row" style="padding-top:5px;">
                            <div class="col-sm-12">
                                <p id="no_data_found" style="display: none;text-align: left;color:red;"></p>
                            </div>
					  </div>
					  <!-- /.box -->			
				</div>  

		
		  </div>
		


<div class="row">

 
  
  <div class="col-lg-12 col-12">
    <div class="box">

     <div class="box-body">           
        <div class="table-responsive">
          <table id="tickets" class="table mt-0 table-hover no-wrap did_list_table" data-page-size="10">
            <thead>
              <tr>
                        <th>
                        <input type="checkbox" id="select_all_checkbox"  onclick="checkDIds();"/>
						<label for="select_all_checkbox"></label></th>
                        <th>Number</th>
                        <th>State</th>
                        <th>Type</th>                       

                      </tr>
            </thead>
            <tbody id="did_list_body_html"></tbody>
                            <tfoot>
                                <tr>
                                    <td  style="text-align: right;">
                                        <input id="buy_number_btn" style="display: none;" value="Buy" type="button" class="btn btn-warning" onclick="validateOrder();" />
                                    </td>
                                </tr>
                            </tfoot>
          </table>
        </div>
      </div>
    </div>
  </div>
 
  <div class="modal fade" id="buy" tabindex="-1" aria-labelledby="myModalExcelLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"  id="upload-excel">Confirm Order</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
    
      <div class="modal-body"id="buy_modal_body">
      
        
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
        <button type="submit"name="submit" class="btn btn-info btn-sm "onclick="buyDid();">Confirm</button>
      </div>
        </form>
    </div>
  </div>
</div>
</div>
<!-- /.row -->

</section>

<script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM=" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/imask"></script>
<script>
 


    $(document).ready(function () {
   
    }).ajaxStart(function () {
        $('#preloader').css({'opacity': 0.5}).fadeIn();
        $('#preloader-status').show();
    }).ajaxStop(function () {
        $('#preloader').css({'opacity': 0}).fadeOut();
        $('#preloader-status').hide();
    });

    function getDidList() {
        if ($("#phone").val() == '' || $("#phone").val().length < 3) {
            toastr.error('Phone number length must be equal to or more than 3');
            return;
        }
        $("#preloader").show();
    $('#preloader').css({'opacity': 0.5}).fadeIn();
    $('#preloader-status').show();
        $.ajax({
            url: '/get-did-list-from-sale',
            type: 'post',
            data: {'country': $("#country").val(), 'numberType': $("#numberType").val(),
                'show': $("#show").val(), 'phone': $("#phone").val(),
                '_token': $('meta[name="csrf-token"]').attr('content') // Add the CSRF token here
},
            success: function (response) {
                console.log('Response from the server:', response);
                
                var dateSet = response;
                if (dateSet.length > 0) {
                    $("#buy_number_btn").show();
                    $("#no_data_found").hide();
                } else {
                    var num = $("#phone").val();
                    num = num.replaceAll('(', '');
                    num = num.replaceAll(')', '');
                    num = num.replaceAll('_', '');
                    num = num.replaceAll('-', '');
                        // Construct the default message
        var defaultMessage = `This ${num} combination is not available currently. Please Click on the Create Order button below in order to raise the order manually for phone number with area code ${num} within 12-24 hours subject to availability.`;
        defaultMessage += ` &nbsp;&nbsp;<button class="btn btn-primary btn-sm" onclick="backOrder();">Create Order</button>`;
                    var message = response.message || defaultMessage;
                $("#no_data_found").html('<b>' + message + '</b>');
                    // $("#no_data_found").html('<b>This ' + num + ' combination is not available currently. Please Click on the Create Order button below in order to raise the order manually for phone number with area code ' + num + ' within 12- 24 hours with subject to availability.</b> &nbsp;&nbsp;<button class="btn btn-primary btn-sm" onclick="backOrder();">Create Order</button>');
                    $("#no_data_found").show();
                    $("#buy_number_btn").hide();
                }
                initDT(dateSet);
            },
            error: function (xhr) {
    console.log(xhr);

    // Extract error message from the response
    var errorMessage = "Something went wrong!";
    try {
        if (xhr.responseJSON && xhr.responseJSON.message) {
            errorMessage = xhr.responseJSON.message;
        } else if (xhr.responseText) {
            var response = JSON.parse(xhr.responseText);
            errorMessage = response.message || "Something went wrong!";
        }
    } catch (e) {
        errorMessage = "Unable to parse error message.";
    }

    // Show error message using toastr
    toastr.error(errorMessage);
},
complete: function () {
            // This code will be executed after the success or error callback
            $("#preloader").hide();
            $('#preloader').css({'opacity': 0}).fadeOut();
            $('#preloader-status').hide();
        }
        });
    }

    function initDT(dateSet) {
        $('.did_list_table').dataTable({
            destroy: true,
            paging: true,
            lengthChange: true,
            ordering: false,
            data: dateSet
        });
    }

    function checkDIds() {
        if ($("#select_all_checkbox").prop('checked') == true) {
            $('.did_checkbox').prop('checked', true);
        } else {
            $('.did_checkbox').prop('checked', false);
        }
    }

    function validateOrder() {
        var checked = 1;
        $('.did_checkbox').each(function () {
            if (this.checked == true) {
                checked = 0;
            }
        });
        if (checked) {
            toastr.error('Please select at least one number');
            return;
        }

        var didHtml = '';
        var total_amount = 0;
        var amount = 2;
        $(".did_checkbox").each(function (ind, ele) {
            if (this.checked == true) {
                didHtml += "<p> DID "+ele.value+" - $"+amount+"</p>";
                total_amount += amount;
            }
        });

        var html = "<p>Please Confirm the order for phone number(s) below:</p>";
        html += didHtml;
        html += "<p>Total Amount : $"+total_amount+" will be deducted from your balance every month.</p>"
        $('#buy_modal_body').html(html);
        $('#buy').modal('show');
    }

    function buyDid() {
        $('#buy').modal('hide');
        var dids = [];
        $(".did_checkbox").each(function (ind, ele) {
            if (this.checked == true) {
                var DidObj = new Object();
                DidObj.value = ele.value;
                DidObj.id = ele.id;
                DidObj.ratecenter = ele.getAttribute('data-ratecenter');
                DidObj.referenceid = ele.getAttribute('data-referenceid');
                DidObj.state = ele.getAttribute('data-state');
                DidObj.didtype = ele.getAttribute('data-didtype');
                var DidObjJsonString= JSON.stringify(DidObj);
                dids.push(DidObjJsonString);
            }
        });

        $.ajax({
            url: '/buy-did',
            type: 'post',
            data: {'number': dids, 'country_code': $("#country").val(),'_token': $('meta[name="csrf-token"]').attr('content') // Add the CSRF token here
},
            success: function (response) {
                toastr.success(response.message);
                setTimeout(function () {
                    window.location.href = "/did";
                }, 700);
            },
            error: function (response) {
                toastr.error(response.message);
            }
        });
    }

    function backOrder() {
        toastr.success('Back Order Created');
        setTimeout(function () {
            window.location.href = "/did";
        }, 700);
    }
</script>

@endsection
