@extends('layouts.app')
@section('title', 'Drip Campaign')

@section('content')
<style>
    /* Style for the active state */
.btn-toggle.active {
    background-color: #2196f3; /* Set to the desired green color */
    color: white; /* Set to the desired text color */
    border-color: green; /* Set to the desired border color */
}

/* Style for the inactive state */
.btn-toggle:not(.active) {
    background-color: red; /* Set to the desired red color */
    color: white; /* Set to the desired text color */
    border-color: red; /* Set to the desired border color */
}
    </style>
    
<section class="content">
   <div class="box-body">
              <h4 class="box-title text-info mb-0"><i class="fa fa-user fa-sx"></i> Drip Campaigns</h4>
              <a href="{{url('drip-campaigns/add')}}"  style="float:right" class="waves-effect waves-light btn btn-rounded btn-primary btn-bitbucket btn-sm mb-5"><i class="fa fa-plus"></i>Add Campaign</a>
              <hr class="my-15">
                        <div class="box box-default" style="display: none;" id="add_marketing_campaign">

       
        <!-- /.box-header -->
          <div class="row">
            <div class="col-12">
        <form method="post">
                    @csrf
                    
               <input type="hidden" class="form-control" required name="marketing_id" id="marketing_id">
        <div class="row">
            <div class="col-md-4">
              <div class="form-group">
                <label class="form-label">Title</label>
                <div class="input-group mb-3">
                <span class="input-group-text"><i class="ti-user"></i></span>
               <input type="text" class="form-control" required name="title" id="title"value="{{old('title')}}">
              </div>
              </div>
            </div>
            <!-- /.col -->
            <div class="col-md-6">
              <div class="form-group">
                <label class="form-label">Description</label>
                <div class="input-group mb-3">
                <span class="input-group-text"><i class="ti-user"></i></span>
               <input type="text" class="form-control" required name="description" id="description"value="{{old('description')}}">
               </div>
              </div>

            </div>

            <div class="col-md-1">
              <div class="form-group">
                <label class="form-label"></label>
               <button type="submit"  class="form-control btn btn-primary btn-sm"  id="saveMarketingCampaign">Save</button>

              </div>

            </div>
        </form>
            <!-- /.col -->
          </div>
          </div>
          <!-- /.row -->
        </div>
        </div>
        <!-- /.box-body -->


      </div>


     

      <div class="row">

       
        
        <div class="col-12">
          <div class="box">
          
           <div class="box-body">           
              <div class="table-responsive">
                <table id="tickets" class="table mt-0 table-hover no-wrap" data-page-size="10">
                  <thead>
                    <tr>
                              <th>#</th>
                              <th>Campaign Name</th>
                              <th>Description</th> 
                              <th>Status</th>                                                       
                              <th>Action</th>

                            </tr>
                  </thead>
                  <tbody>
                  @foreach($drip_campaigns as $key => $campaigns)
                                <tr>
                                  <th scope="row">{{$key+1}}</th>
                                  <td>{{$campaigns->title}}</td>                            
                                  <td> {{$campaigns->description}}</td>
                                  <td>
                                  <button type="button"data-listid="{{$campaigns->campaign_id}}" class="btn btn-sm btn-toggle  @if($campaigns->campaign_status == '1') active @endif" data-bs-toggle="button" aria-pressed="true" autocomplete="off">
                                        <div class="handle"></div>
                                      </button>
                                      
                                    </td>
                        
                                  <td>
                                     <a style="cursor:pointer;margin-right:5x;" href="{{ url('drip-campaigns/edit/' . $campaigns->campaign_id) }}"  title="Edit Marketing Campaign" ><i class="fa fa-edit fa-lg"></i></a> 
                                 <!-- <a style="cursor:pointer;color:blue;;" href="/marketing-campaign/{{$campaigns->id}}/schedules" title="View Marketing Campaign Schedule List" data-marketingid={{$campaigns->id}}><i class="fa fa-list fa-lg" aria-hidden="true"></i></a>
                                        <a style="cursor:pointer;color:blue;;" title="Add Text Schedule" data-marketingid={{$campaigns->id}}  class='addSmsSchedule'><i class="fa fa-comment-o fa-lg"></i></a> -->
                                        <!-- <a style="cursor:pointer;color:blue;;"  title="Add Email Schedule"  data-marketingid={{$campaigns->id}} class='addEmailSchedule'><i class="fa fa-envelope fa-lg"></i></a></td> -->
                                        <a  type="button" style="cursor:pointer;"data-bs-toggle="modal" data-bs-target="#myModal{{$campaigns->id}}" data-id="{{$campaigns->id}}" class="list-icons-item me-10"><i class="fa fa-eye fa-lg"></i></a>

                                  
                             
                                </tr>

                                <div id="myModal{{$campaigns->id}}" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                                  <div class="modal-dialog modal-lg">
                                    <div class="modal-content">
                                      
                                      
                                      <!-- /.box-header -->
                                      <div class="box-body">
                                        
                                        
                                        <!-- form itself -->
                                        <form id="test-form" class="mfp-hide white-popup-block">
                                        <h4><i class="icon-Cardboard-vr"><span class="path1"></span><span class="path2"></span></i> Campaign Details <button style="padding: 5px 11px 5px 11px;" type="button" class="btn btn-danger float-end" data-bs-dismiss="modal">X</button></h4>
                                        <hr>
                                        <div class="row">
                                          <div class="col-md-6">
                                            
                                          <div class="form-group">
                                            <i style="color:black;" class="ti-user"></i> <label class="form-label" for="inputName"> Name</label>
                                            <p><span class="badge  badge-primary"style="font-size: 1rem;">{{$campaigns->title}}</span></p>
                                          </div>
                                          <div class="form-group">
    <i style="color:black;" class="ti ti-mobile"></i>
    <label class="form-label" for="inputName">Lead Status</label>
    
    @php
        // Find the lead status with the matching ID from the object array
        $leadStatus = null;
        foreach ($lead_status as $status) {
            if ($status->id == $campaigns->lead_status_id) {
                $leadStatus = $status;
                break;
            }
        }
    @endphp

    @if ($leadStatus)
        <p><span class="badge  badge-primary">{{ $leadStatus->title }}</span></p>
    @else
        <p><span class="badge  badge-secondary">Status not found</span></p>
    @endif
</div>

<div class="form-group">
                                            <i style="color:black;" class="ti ti-mobile"></i> <label class="form-label" for="inputName">Schedule Day & Time</label>
                                            @php
    // Assuming run_time is in 24-hour format (e.g., 13:00 for 1:00 PM)
    $time = \Carbon\Carbon::parse($campaigns->run_time); // Parse the time into a Carbon instance
    $formattedTime = $time->format('g:i A'); // 'g:i A' for 12-hour format with AM/PM
@endphp

<p><span class="badge badge-primary">{{ $campaigns->schedule_day }} {{ $formattedTime }}</span></p>
                                          </div>
                                    

                                          <!-- <div class="form-group">
                                            
                                            <i style="color:black;" class="ti-timer"></i> <label class="form-label" for="inputName">Smtp</label>
                                            <p><span class="badge badge-sm badge-primary"></span></p>
                                          </div>
                                      -->
                                      
                                      
                         
                                        
                                        </div>

                                        <div class="col-md-6">
                                          <div class="form-group">
                                            <i style="color:black;" class="ti-timer"></i> <label class="form-label" for="inputName">Description</label>
                                            <p><span class="badge  badge-primary"style="font-size: 1rem;">{{$campaigns->description}}</span></p>
                                          </div>
                                          <div class="form-group">
                                          @php
        // Find the lead status with the matching ID from the object array
        $emailTemplate = null;
        foreach ($email_templates as $status) {
            if ($status->id == $campaigns->email_template_id) {
                $emailTemplate = $status;
                break;
            }
        }
    @endphp
                                            <i style="color:black;" class="ti-mobile"></i> <label class="form-label" for="inputPhone">Email template</label>
                                            <p><span class="badge badge-primary">{{$emailTemplate->template_name}}</span></p>
                                            
                                          </div>
                                          <div class="form-group">
                                            <i style="color:black;" class="ti-email"></i> <label class="form-label" for="inputEmail">Schedule</label>
                                            <p><span class="badge badge-primary">{{$campaigns->schedule}}</span></p>

                                          </div>
                                      
                                        

                                        
       
                                        
                                        </div>
                                        </div>

                                          
                                      </form>
                                    </div>
                                      <!-- /.box-body -->
                                      <!-- /.box -->
                                      
                                    </div>
                                    <!-- /.modal-content -->
                                  </div>
                                  <!-- /.modal-dialog -->
                                </div>
                            @endforeach
                         
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      
</div>
                      
                      
                                  
                                 
                        </div>
          </div>
        </div>
      </div>
      <!-- /.row -->

<div class="modal fade" id="deleteMarketingModel" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="add-edit">Confirm Delete</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
             
                <input type="hidden"  class="form-control" name="send" id="send" value="1"/>
                <input type="hidden"  class="form-control" name="campaign_id" id="campaign_id" value=""/>
                        <div class="modal-body">
                        <p>You are about to delete <b><i class="title"></i></b> Campaign.</p>
                            <p>Do you want to proceed?</p>
                            <input type="" class="form-control" name="marketing_id" value="" id="marketing_id">
                                  <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-primary btn-sm deleteMarketing">Delete</button>
                                  </div>
                        </div>
          </div>
        </div>
      </div>

    </section>
        <!-- /.content -->


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

    <script>
        $("#openMarketingForm").click(function(){
            $("#add_marketing_campaign").show();
            $("#openMarketingForm").hide();

        });

    </script>

    <script>
        $(".editMC").click(function(){
            $("#add_marketing_campaign").show();
            $("#openMarketingForm").hide();
            $("#saveMarketingCampaign").html('Update');

            var marketingid = $(this).data('marketingid');
            //alert(marketingid);

            $.ajax({
                url: 'drip-campaigns/' + marketingid,
                type: 'get',
                success: function(response) {
                    //alert(response.id);
                    $("#title").val(response.title);
                    $("#description").val(response.description);
                    $("#marketing_id").val(response.id);


                    //window.location.reload(1);
                }
            });

        });
    </script>

    <!-- add sms schedule -->
    <script>
    $(".addSmsSchedule").click(function()
        {

            var marketingid = $(this).data('marketingid');
            $("#sms_campaign_id").val(marketingid);
            $("#addSmsScheduleModel").modal('show');
            const now = moment().add(10, 'minutes')
            time = now.format("HH:mm");
            document.getElementById("sms_run_time").value = time ;
        });

    $(document).on("click", "#addSmsSchedule", function (e) {
            e.preventDefault();


            sms_list_id = $("#sms_list_id").val();
            if(sms_list_id == ''){
                $("#errorsms_list_id").html('Please select List');
                return false;
            }


            listheader = $("#sms_listheader").val();

            if(listheader == ''){
                $("#errorsmslistheader").html('Please select listheader');
                return false;
            }


            sms_template_id = $("#sms_template_id").val();
            if(sms_template_id == ''){
                $("#errorsms_template_id").html('Please select text templates');
                return false;
            }

            sms_country_code = $("#sms_country_code").val();
            if(sms_country_code == ''){
                $("#error_sms_country_code").html('Please enter country code');
                return false;
            }

            did_setting = $("#did_setting").val();
            if(did_setting == ''){
                $("#errordid_setting").html('Please select text did');
                return false;
            }

            var run_date = $("#sms_run_date").val();
            if(run_date == ''){
                $("#errorsms_run_time").html('Please select date');
                return false;

            }
            var run_time = $("#sms_run_time").val();
            if(run_time == ''){
                $("#errorsms_run_time").html('Please select time ');
                return false;
            }

            var localTime = new Date(run_date+' '+run_time+':00');
            var now = moment().add(10, 'minutes').format("YYYY-MM-DD HH:mm:ss");

            var localTime = new Date(localTime);
            var now = new Date(now);

            time = moment(localTime).utc().format('YYYY-MM-DD HH:mm:ss');

            if (localTime < now) {
                $("#errorsms_run_time").html('Please select runtime from atleast 10 min ahead from current time ');
                return false;
            }

             sms_send = $("#sms_send").val();
             sms_campaign_id = $("#sms_campaign_id").val();

             created_by = <?= Session::get('id'); ?>
            //alert(created_by);





            postData = {
                "_token"            : $("#user-role-csrf").val(),
                "campaign_id"       : $("#sms_campaign_id").val(),
                "list_id"           : $("#sms_list_id").val(),
                "list_column_name"           : $("#sms_listheader").val(),
                "send"              : $("#sms_send").val(),
                "sms_template_id" : $("#sms_template_id").val(),
                "sms_setting_id"  : $("#did_setting").val(),
                "sms_country_code"  : $("#sms_country_code").val(),
                "run_time"          : time,
                "created_by"        : created_by

            };
            console.log(postData);

            $.ajax({
                type: "POST",
                url: "{{ route('addMarketingScheduleSMS') }}",
                data: postData,
                success: function(responce){
                    console.log(responce);
                    $("#email-schedule-sms").html('<div class="alert alert-success" id="alert-success">Campaign Schedule Added</div>');
                   // $("#addEmailSchedule-cancel").click();
                  setTimeout(function(){ window.location.reload(1); }, 3000);
                },
                error: function(error){
                    console.log(error.responseJSON);
                    $("#email-schedule-sms").html('<i class="glyphicon glyphicon-info-sign"></i> Something went wrong, Please try again...');
                    $("#email-schedule-sms").show();
                }
            });
        });
    </script>
    <!-- close sms schedule -->

    <!-- Email schedule -->
    <script>
    $(".addEmailSchedule").click(function()
        {
            var marketingid = $(this).data('marketingid');
            $("#campaign_id").val(marketingid);
            $("#addEmailScheduleModel").modal('show');
            const now = moment().add(10, 'minutes')
            time = now.format("HH:mm");
            document.getElementById("run_time").value = time ;
        });

    $(document).on("click", "#addEmailSchedule", function (e) {
            e.preventDefault();


            list_id = $("#list_id").val();

      

            email_template_id = $("#email_template_id").val();
            if(email_template_id == ''){
                $("#erroremail_template_id").html('Please select email templates');
                return false;
            }

            email_setting_id = $("#email_setting_id").val();
            if(email_setting_id == ''){
                $("#erroremail_setting_id").html('Please select email setting id');
                return false;
            }

            var run_date = $("#run_date").val();
            if(run_date == ''){
                $("#errorrun_time").html('Please select date');
                return false;

            }
            var run_time = $("#run_time").val();
            if(run_time == ''){
                $("#errorrun_time").html('Please select time ');
                return false;

            }
            var localTime = new Date(run_date+' '+run_time+':00');
            var now = moment().add(10, 'minutes').format("YYYY-MM-DD HH:mm:ss");

            var localTime = new Date(localTime);
            var now = new Date(now);

            time = moment(localTime).utc().format('YYYY-MM-DD HH:mm:ss');

            if (localTime < now) {
                $("#errorrun_time").html('Please select runtime from atleast 10 min ahead from current time ');
                return false;
            }

             send = $("#send").val();
             campaign_id = $("#campaign_id").val();

             created_by = <?= Session::get('id'); ?>
            //alert(created_by);





            postData = {
                "_token"            : $("#user-role-csrf").val(),
                "campaign_id"       : $("#campaign_id").val(),
                "list_id"           : $("#list_id").val(),
                "list_column_name"  : $("#listheader").val(),
                "send"              : $("#send").val(),
                "email_template_id" : $("#email_template_id").val(),
                "email_setting_id"  : $("#email_setting_id").val(),
                "lead_status_id"  : $("#lead_status_id").val(),
                "run_time"          : time,
                "created_by"        : created_by

            };
            console.log(postData);
            $.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
            $.ajax({
                type: "POST",
                url: "{{ route('addDripSchedule') }}",
                data: postData,
                success: function(response){
                    console.log(response);
                    $("#email-schedule").html('<div class="alert alert-success" id="alert-success">Campaign Schedule Added</div>');
                   // $("#addEmailSchedule-cancel").click();
                   setTimeout(function(){ window.location.reload(1); }, 3000);
                },
                error: function(error){
                    console.log(error.responseJSON);
                    $("#email-schedule").html('<i class="glyphicon glyphicon-info-sign"></i> Something went wrong, Please try again...');
                    $("#email-schedule").show();
                }
            });
        });
    </script>
    <!-- close Email schedule -->

    <script>
        $(".openMarketingDelete").click(function()
        {
            var marketingid = $(this).data('marketingid');
            $("#deleteMarketingModel").modal('show');
            $("#marketing_id").val(marketingid);
        });

        $(document).on("click", ".deleteMarketing", function()
        {
        // if (confirm("Are you sure you want to delete this record?")) {
            var campaign = $("#campaign_id").val();
            var el = this;
            $.ajax({
                url: 'deleteMarketingCampaign/' + campaign,
                type: 'get',
                success: function(response) {
                    window.location.reload(1);
                }
            });
        });

        $(document).on("change", "#sms_list_id", function()
        {
            var list_id = $("#sms_list_id").val();
            //alert(list_id);
            var el = this;
            $.ajax({
                url: 'findListHeader/' + list_id,
                type: 'get',
                dataType: "json",
                success: function(response) {
                    var text = "<option value=''>Select Column</option>";
                    $.each(response.data, function(key,value) {
                        text += "<option value="+value.column_name+">"+value.header+"</option>";
                    });
                    $("#hidden_sms_listheader").show();
                    document.getElementById("sms_listheader").innerHTML = text;
                }
            });
        });

        $(document).on("change", "#list_id", function()
        {
            var list_id = $("#list_id").val();
            //alert(list_id);
            var el = this;
            $.ajax({
                url: 'findListHeader/' + list_id,
                type: 'get',
                dataType: "json",
                success: function(response) {
                    var text = "<option value=''>Select Column</option>";
                    $.each(response.data, function(key,value) {
                        text += "<option value="+value.column_name+">"+value.header+"</option>";
                    });
                    document.getElementById("listheader").innerHTML = text;
                    $("#hidden_listheader").show();
                }
            });
        });
    </script>







<script>
$(function()
{
        // Set up CSRF token for all AJAX requests
        $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $("#tickets").on("click", ".btn-toggle", function ()
    {
       //console.log('hi');
       var $btn = $(this); // Store reference to the button
       var status = $btn.hasClass('active') ? 1 : 0; // Toggle status based on class
       //alert(status);
        var listid = $(this).data('listid');    


        $.ajax({
            type: "GET",
            dataType: "json",
            url: '/updateDripStatus/'+listid+ '/' +status,

            success: function(data)
            {
                console.log(data);
                if(data.status == 'true')
                {
                
                    toastr.success(data.message);
                }
                else
                {
                    toastr.error(data.message);

                }

                console.log(data.success);
                window.location.reload(1);
            }
        });
    })
})
</script>
@endsection
