@extends('layouts.app')

@section('title', 'Campaign List')
@section('content')
    <style>
        .badge {
            font-size: 1rem;
            font-style: normal;
            font-weight: 400;
            font-family: "IBM Plex Sans", sans-serif;
            line-height: 1.5;
        }
    </style>
    <style>
        .extension-item {
            display: inline-block;
            margin-right: 5px;
            /* Adjust the margin as needed */
        }

        * {
            user-select: none;
            -webkit-tap-highlight-color: transparent;
        }

        .switch {
            transform: scale(0.5);
            /* Adjust the scale value as needed to reduce the size */
        }

        /* 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 */
        }

        .table>tbody>tr>td,
        .table>tbody>tr>th {
            padding: 0rem;
            padding-left: 0.5rem;
            vertical-align: middle;
        }

        .health-check-icon {
            cursor: pointer;
            position: relative;
        }
        .health-check-icon:hover i {
            color: #0d6efd !important;
            transform: scale(1.15);
            transition: all 0.2s ease;
        }
        .health-popover {
            position: absolute;
            z-index: 1060;
            min-width: 260px;
            max-width: 340px;
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
            padding: 0;
            right: 0;
            top: 100%;
            margin-top: 4px;
        }
        .health-popover-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 6px 10px;
            border-bottom: 1px solid #eee;
            font-size: 0.8rem;
            font-weight: 600;
            color: #333;
        }
        .health-popover-close {
            cursor: pointer;
            font-size: 1rem;
            color: #999;
            border: none;
            background: none;
            padding: 0 4px;
            line-height: 1;
        }
        .health-popover-close:hover {
            color: #333;
        }
        .health-popover-body {
            padding: 10px;
        }
    </style>

<style>
.lender-modal {
    border-radius: 10px;
    background-color: #fff;
    font-family: "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.lender-modal > .modal-header {
    border-bottom: 1px solid #ddd !important;
    padding-bottom: 10px !important;
    margin-bottom: 18px !important;
}

.lender-modal .col-md-4 {
    margin-bottom: 14px;
}

.lender-modal label {
    font-size: 1.05rem;    
    font-weight: 500;       
    color: #000;            
    display: inline-flex;
    align-items: center;
    margin-bottom: 3px;
    letter-spacing: 0.2px;
}


.text-icon {
    color: #0d3c7d;
    font-size: 1.2rem;
    margin-right: 6px;
    vertical-align: middle;
    font-weight: 600;
    line-height: 1;
}


.value-text {
    display: inline-block;
    background-color: #46aaf5;
    color:  #ffffff;
    font-size: 0.98rem;
    font-weight: 400;
    padding: 4px 10px;
    border-radius: 6px;
    margin-top: 5px;
    letter-spacing: 0.15px;
    box-shadow: 0 0 1px rgba(0,0,0,0.08);
    width: fit-content;          
    max-width: 100%;             
    word-break: break-word;
}


.lender-modal .col-md-4 > .value-text {
    display: block;
    margin-left: 22px;
}


.value-text:hover {
    background-color: #2196f3;
    color: #ffffff;
    transition: 0.25s ease;
}

.lender-modal > .modal-body {
    padding-top: 2px !important;
    padding-left: 18px !important;
    padding-right: 18px !important;
}

</style>


    <link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
    <!-- Main content -->
    <section class="content">

        <div class="row">
            <div class="col-12">
                <div class="box">
                    <div class="box-body">

                        <h4 class="box-title text-info mb-0"><i class="icon-Cardboard-vr"><span class="path1"></span><span
                                    class="path2"></span></i> Campaign List</h4>
                        <a href="{{ url('/add-campaign') }}" 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-plus"></i> Add Campaign</a>

                        <hr class="my-15">
                        <div class="table-responsive">

                            {{-- <table id="tickets" class="table mt-0 table-hover" data-page-size="10"> --}}
                            <table id="user_table" class="display table mt-0 table-hover" data-page-size="10""
                                style="width:100%">
                                <thead>
                                    <tr>


                                        <th>#</th>
                                        <th>Name</th>
                                        <th>Call Time</th>
                                        <th>Lists Associated</th>
                                        <th>Dialled Leads/Total Leads</th>
                                        <th>Hopper Count</th>
                                        <th>Hopper Mode</th>
                                        <th>Created Date</th>
                                        <th>Status</th>
                                        <th>Action</th>

                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($campaign_list as $key => $campaign)
                                        <tr>
                                            <th scope="row"></th>
                                            <td></td>
                                            <td></td>
                                            <td>
                                                <!-- <a
                                                    href="{{ url('campaign/list') }}/{{ $campaign->id }}">{{ $campaign->rowList }}</a> -->
                                            </td>
                                            <td></td>
                                            <td></td>
                                            <td>
                                               
                                            </td>

                                            <td></td>

                                            <td>
                                              
                                            </td>
                                            <td class="text-center">
                                               
                                            </td>


                                        </tr>
<div id="myModal{{$campaign->id}}" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content lender-modal">

      <!-- Modal Header -->
      <div class="modal-header border-0 pb-0">
        <h4 class="text-dark mb-0" style="font-weight: 400; font-size: 1.35rem;">
          <i class="icon-Cardboard-vr"><span class="path1"></span><span class="path2"></span></i> Campaign Details
        </h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <!-- Modal Body -->
      <div class="modal-body pt-4">
        <div class="row">

          <!-- LEFT COLUMN -->
          <div class="col-md-6">

            <div class="mb-3">
              <i class="ti-user" style="color:black;"></i> 
              <label class="form-label">Name</label>
              <p><span class="badge badge-primary">{{$campaign->title}}</span></p>
            </div>

            <div class="mb-3">
              <i class="ti-mobile" style="color:black;"></i> 
              <label class="form-label">Dialling Mode</label>
              <p><span class="badge badge-sm badge-@if($campaign->dial_mode == 'super_power_dial')danger @elseif ($campaign->dial_mode == 'predictive_dial')primary @elseif ($campaign->dial_mode == 'outbound_ai')secondary @endif">
                @if($campaign->dial_mode == 'super_power_dial') Super Power Dial
                @elseif ($campaign->dial_mode == 'predictive_dial') Predictive Dial
                @elseif ($campaign->dial_mode == 'outbound_ai') Outbound AI
                @endif
              </span></p>
            </div>

            <div class="mb-3">
              <i class="ti-timer" style="color:black;"></i>
              <label class="form-label">Time Based Calling</label>
              <p><span class="badge badge-sm badge-@if($campaign->time_based_calling == '1')success @elseif($campaign->time_based_calling == '0')danger @endif">
                {{$campaign->time_based_calling == '1' ? 'Yes' : 'No'}}
              </span></p>
            </div>

            <div class="mb-3">
              <i class="ti-mobile" style="color:black;"></i>
              <label class="form-label">Caller ID</label>
              <p><span class="badge badge-sm badge-@if($campaign->caller_id == 'custom')success @elseif ($campaign->caller_id == 'area_code')danger @elseif ($campaign->caller_id == 'area_code_random')primary @elseif ($campaign->caller_id == 'area_code_3')secondary @elseif ($campaign->caller_id == 'area_code_4')warning @elseif ($campaign->caller_id == 'area_code_5')info @endif">
                @if($campaign->caller_id == 'custom') Custom
                @elseif ($campaign->caller_id == 'area_code') Area Code
                @elseif ($campaign->caller_id == 'area_code_random') Area Code & Randomizer
                @elseif ($campaign->caller_id == 'area_code_3') Area Code +3
                @elseif ($campaign->caller_id == 'area_code_4') Area Code +4
                @elseif ($campaign->caller_id == 'area_code_5') Area Code +5
                @endif
              </span></p>
            </div>

            <div class="mb-3">
              <i class="ti-world" style="color:black;"></i>
              <label class="form-label">Country Code</label>
              <p><span class="badge badge-sm badge-primary">+{{$campaign->country_code}}</span></p>
            </div>
     <div class="mb-3">
              <i class="ti-mobile" style="color:black;"></i>
              <label class="form-label">Dialled Leads/Total Leads</label>
              <p><span class="badge badge-sm badge-primary">{{$campaign->rowLeadReport}} / {{$campaign->rowListData}}</span></p>
            </div>
                <div class="mb-3">
              <i class="ti-calendar" style="color:black;"></i>
              <label class="form-label">Created Date</label>
              <p><span class="badge badge-sm badge-primary">{{date('Y-m-d H:i', strtotime($campaign->updated))}}</span></p>
            </div>
            <div class="mb-3"style="display:none;">
              <i class="ti-email" style="color:black;"></i>
              <label class="form-label">Send To CRM</label>
              <p><span class="badge badge-sm badge-@if($campaign->send_crm == '1')success @elseif($campaign->send_crm == '0')danger @endif">
                {{$campaign->send_crm == '1' ? 'Yes' : 'No'}}
              </span></p>
            </div>

            <div class="mb-3"style="display:none;">
              <i class="ti-email" style="color:black;"></i>
              <label class="form-label">Send Email</label>
              <p><span class="badge badge-sm badge-@if($campaign->email == '0')danger @elseif($campaign->email == '1')primary @elseif($campaign->email == '2')secondary @elseif($campaign->email == '3')success @endif">
                @if($campaign->email == '0') No
                @elseif($campaign->email == '1') With User Email
                @elseif($campaign->email == '2') With Campaign Email
                @elseif($campaign->email == '3') With System Email
                @endif
              </span></p>
            </div>

            <div class="mb-3"style="display:none;">
              <i class="ti-email" style="color:black;"></i>
              <label class="form-label">Send SMS</label>
              <p><span class="badge badge-sm badge-@if($campaign->sms == '1')success @elseif($campaign->sms == '0')danger @endif">
                {{$campaign->sms == '1' ? 'With User Phone No' : 'No'}}
              </span></p>
            </div>

            <div class="mb-3"style="display:none;">
              <i class="ti-email" style="color:black;"></i>
              <label class="form-label">Send Report</label>
              <p><span class="badge badge-sm badge-@if($campaign->send_report == '1')success @elseif($campaign->send_report == '0')danger @endif">
                {{$campaign->send_report == '1' ? 'Yes' : 'No'}}
              </span></p>
            </div>

          </div> <!-- END LEFT COLUMN -->

          <!-- RIGHT COLUMN -->
          <div class="col-md-6">

            <div class="mb-3">
              <i class="ti-timer" style="color:black;"></i>
              <label class="form-label">Description</label>
              <p><span class="badge badge-sm badge-primary">{{$campaign->description}}</span></p>
            </div>

            <div class="mb-3">
              <i class="ti-mobile" style="color:black;"></i>
              <label class="form-label">Status</label>
              <p>
                <span class="badge badge-sm badge-@if($campaign->status == '1')success @elseif($campaign->status == '0')danger @endif">
                  {{$campaign->status == '1' ? 'Active' : 'Inactive'}}
                </span>
                @if($campaign->status == '0' && !empty($campaign->pause_reason))
                  <br>
                  <span style="display:inline-block;margin-top:5px;background:
                    @if($campaign->pause_reason == 'insufficient_wallet')#ff9800
                    @elseif($campaign->pause_reason == 'ai_quota_exhausted')#f44336
                    @elseif($campaign->pause_reason == 'no_subscription')#f44336
                    @else #9e9e9e
                    @endif;color:#fff;font-size:0.78rem;padding:3px 10px;border-radius:10px;font-weight:500;">
                    @if($campaign->pause_reason == 'insufficient_wallet')
                      <i class="fa fa-exclamation-triangle"></i> Paused: Low Wallet Balance
                    @elseif($campaign->pause_reason == 'ai_quota_exhausted')
                      <i class="fa fa-server"></i> Paused: AI Quota Exhausted
                    @elseif($campaign->pause_reason == 'no_subscription')
                      <i class="fa fa-ban"></i> Paused: No Active Subscription
                    @else
                      <i class="fa fa-info-circle"></i> Paused: {{ $campaign->pause_reason }}
                    @endif
                  </span>
                @endif
              </p>
            </div>

            <div class="mb-3">
              <button type="button" class="btn btn-sm btn-outline-info check-health-btn" data-campaign-id="{{$campaign->id}}">
                <i class="fa fa-heartbeat"></i> Check Campaign Health
              </button>
              <div id="health-result-{{$campaign->id}}" style="margin-top:8px;display:none;"></div>
            </div>

            <div class="mb-3">
              <i class="ti-email" style="color:black;"></i>
              <label class="form-label">Call Time</label>
              <p><span class="badge badge-sm badge-primary">{{date('g:i A', strtotime($campaign->call_time_start))}} to {{date('g:i A', strtotime($campaign->call_time_end))}}</span></p>
            </div>

            <div class="mb-3">
              <i class="ti-mobile" style="color:black;"></i>
              <label class="form-label">Custom Caller ID</label>
              <p><span class="badge badge-sm badge-primary">{{$campaign->caller_id == 'custom' ? $campaign->custom_caller_id : 'NA'}}</span></p>
            </div>

            <div class="mb-3">
              <i class="ti-list" style="color:black;"></i>
              <label class="form-label">List Associated</label>
              <p><span class="badge badge-sm badge-primary">{{$campaign->rowList}}</span></p>
            </div>

       

            <div class="mb-3">
              <i class="ti-mobile" style="color:black;"></i>
              <label class="form-label">Hopper Count</label>
              <p><span class="badge badge-sm badge-primary">{{$campaign->rowLeadTemp}}</span></p>
            </div>

        

          </div> <!-- END RIGHT COLUMN -->

        </div> <!-- END ROW -->
      </div> <!-- END MODAL BODY -->

    </div> <!-- END MODAL CONTENT -->
  </div>
</div>



  </div>
                                    @endforeach

                                </tbody>


                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal fade" id="delete" tabindex="-1" aria-labelledby="deleteLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="myModalLabel">Confirm Delete</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal"
                                aria-label="Close"></button>
                        </div>

                        <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="hidden" class="form-control" name="campaign_id" value=""
                                id="campaign_id">

                        </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-danger btn-sm deleteCampaign">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 src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>


    <script>
        function showConfrom(dataId) {

            var delete_id = dataId;
            $("#delete").modal('show');
            $("#campaign_id").val(delete_id);
        }
        // $(".openCampaignDelete").click(function() {

        //     // var delete_id = $(this).data('campaignid');
        //     // $("#delete").modal('show');
        //     // $("#campaign_id").val(delete_id);

        // });
            // Assuming your table has id="campaignTable"
$('#user_table').on('click', '.reloadHopper', function(e) {

            e.preventDefault();
            var url = $(this).data('url');
            //alert(url);
            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    console.log(response);
                    toastr.success(response.message);
                },
                error: function(jqXHR, exception) {
                    console.log(jqXHR.responseText);
                    var resp = JSON.parse(jqXHR.responseText);
                    toastr.error("Failed to send the campaign reload request.\n" + resp.message);
                }
            });
        });
        $(document).on("click", ".deleteCampaign", function() {
            // if (confirm("Are you sure you want to delete this record?")) {
            var campaign = $("#campaign_id").val();
            //alert(campaign);
            //var account_no = $(this).data('account_no');
            //alert(account_no);
            var el = this;
            $.ajax({
                url: 'deleteCampaign/' + campaign,
                type: 'get',
                success: function(response) {
                    toastr.success('Campaign has been deleted successfully');
                    window.location.reload(1);
                }
            });
        });
    </script>




    <script>
        $(function() {
            $("#user_table").on("click", ".btn-toggle", function() {
                console.log('hi');
                var status = $(this).hasClass('active') ? 1 : 0;
                var listid = $(this).data('listid');


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

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

                        }

                        console.log(data.success);
                        window.location.reload(1);
                    }
                });
            })
        })
    </script>
    <script>
        $(document).ready(function() {
            $("#user_table").on("click", ".toggle", function() {
                console.log('Toggle clicked');

                // Get the associated checkbox element
                var checkbox = $(this).find(".hooper-toggle");
                console.log('Toggle found');
                // Get the new status (before it gets changed by the plugin)
                var newStatus = !checkbox.prop("checked") ? 1 : 0;
                console.log(newStatus);

                var listid = checkbox.data('listid');
                console.log(listid);

                $.ajax({
                    type: "GET",
                    dataType: "json",
                    url: '/updateCampaignHopper/' + listid + '/' + newStatus,
                    success: function(data) {
                        if (data.status == 'true') {
                            toastr.success(data.message);
                        } else {
                            toastr.error(data.message);
                        }
                        $('#loading').show();

                        console.log(data.success);
                        window.location.reload(1);
                    }
                });
            });
        });
    </script>
<script>
    // Use :id as placeholder
    const reloadHopperRoute = @json(route('reloadHopper', ['campaign' => ':campaign']));
</script>

    <script>
        $(function() {

            $('#user_table').DataTable({
                destroy: true,
                processing: true,
                serverSide: true,
                ajax: '{{ url('get-campaign') }}',
                columns: [{
                        data: 'DT_RowIndex',
                        name: 'DT_RowIndex'
                    },
                    {
                        data: 'title',
                        name: 'title'
                    },
                    {
                        data: null,
                        name: 'call_time',
                        render: function(data) {
                                if (!data.call_time_start || !data.call_time_end) {
        return 'N/A'; // return empty if either is null or missing
    }
                            return formatTime(data.call_time_start) + ' to ' + formatTime(data
                                .call_time_end);
                        }
                    },
                    {
                        data: 'rowList',
                        render: function(data, type, row) {
                            return `<a href="/campaign/list/${row.id}">${data}</a>`;
                        }
                    },
                    {
                        data: null,
                        render: function(data, type, row) {
                            return `${row.rowLeadReport} / ${row.rowListData}`;
                        }
                    },
                    {
                        data: 'rowLeadTemp',
                        name: 'rowLeadTemp'
                    },
            {
    data: 'hopper_mode',
    render: function(data, type, row) {
        // If hopper_mode = 1 → show Linear (checked)
        // If hopper_mode = 0 → show Random (unchecked)
        const checked = (data == 1);

        return checked
            ? `<label class="switch">
                <div class="toggle btn btn-primary" data-toggle="toggle" role="button" style="width:108.067px;height:46.6px;">
                    <input type="checkbox" data-listid="${row.id}" class="hooper-toggle filled-in chk-col-primary"
                        data-toggle="toggle" id="hooper_id_${row.id}"
                        data-on="Linear" data-off="Random"
                        data-onstyle="primary" data-offstyle="danger" checked>
                    <div class="toggle-group">
                        <label for="hooper_id_${row.id}" class="btn btn-primary toggle-on">Linear</label>
                        <label for="hooper_id_${row.id}" class="btn btn-danger toggle-off">Random</label>
                        <span class="toggle-handle btn btn-light"></span>
                    </div>
                </div>
            </label>`
            : `<label class="switch">
                <div class="toggle btn btn-danger off" data-toggle="toggle" role="button" style="width:108.067px;height:46.6px;">
                    <input type="checkbox" data-listid="${row.id}" class="hooper-toggle filled-in chk-col-primary"
                        data-toggle="toggle" id="hooper_id_${row.id}"
                        data-on="Linear" data-off="Random"
                        data-onstyle="primary" data-offstyle="danger">
                    <div class="toggle-group">
                        <label for="hooper_id_${row.id}" class="btn btn-primary toggle-on">Linear</label>
                        <label for="hooper_id_${row.id}" class="btn btn-danger toggle-off">Random</label>
                        <span class="toggle-handle btn btn-light"></span>
                    </div>
                </div>
            </label>`;
    }
}
,
               {
    data: 'updated',
    render: function(data) {
        if (!data) return '';

        const date = new Date(data);

        return date.toLocaleString('en-GB', { // 'en-GB' uses 24-hour clock
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false  // ensures 24-hour format
        });
    }
},

                    {
                        data: 'status',
                        render: function(data, type, row) {
                            const active = data == '1' ? 'active' : '';
                            let html = `<button type="button" data-listid="${row.id}" class="btn btn-sm btn-toggle ${active}" data-bs-toggle="button" aria-pressed="true" autocomplete="off">
                                    <div class="handle"></div>
                                </button>`;

                            // Show pause reason badge when campaign is inactive and has a system pause_reason
                            if (data == '0' && row.pause_reason) {
                                const reasonMap = {
                                    'insufficient_wallet': { label: 'Low Balance', color: '#ff9800', icon: 'fa-exclamation-triangle' },
                                    'ai_quota_exhausted':  { label: 'AI Quota Exhausted', color: '#f44336', icon: 'fa-server' },
                                    'no_subscription':     { label: 'No Subscription', color: '#f44336', icon: 'fa-ban' }
                                };
                                const info = reasonMap[row.pause_reason] || { label: row.pause_reason, color: '#9e9e9e', icon: 'fa-info-circle' };
                                html += `<div style="margin-top:4px;">
                                    <span style="display:inline-block;background:${info.color};color:#fff;font-size:0.7rem;padding:2px 8px;border-radius:10px;font-weight:500;">
                                        <i class="fa ${info.icon}" style="margin-right:3px;"></i>${info.label}
                                    </span>
                                </div>`;
                            }

                            return html;
                        }
                    },
                    {
                        data: 'id',
                        render: function(data, type, row) {
                              const url = reloadHopperRoute.replace(':campaign', data); // replace placeholder
                            return `
                        <div class="list-icons d-inline-flex">
                            <a data-bs-toggle="modal" data-bs-target="#myModal${row.id}" class="list-icons-item me-10"><i class="fa fa-eye fa-lg"></i></a>
                            <a href="#" class="list-icons-item me-10 health-check-icon" data-campaign-id="${data}" title="Check Campaign Health"><i class="fa fa-heartbeat fa-lg" style="color:#17a2b8;"></i></a>
                            <div class="list-icons-item dropdown">
                                <a href="#" class="dropdown-toggle" data-bs-toggle="dropdown"><i class="fa fa-file-text"></i></a>
                                <div class="dropdown-menu dropdown-menu-end">
                                    <a class="dropdown-item" href="/campaign/${data}"><i class="fa fa-edit fa-lg"></i> Edit</a>
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item" href="/copy-campaign/${data}"><i class="fa fa-copy fa-lg"></i> Copy</a>
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item reloadHopper" data-campaign="${data}" data-url="${url}"><i class="fa fa-refresh fa-lg"></i> Reset</a>
                                    <div class="dropdown-divider"></div>
                                    <a class="dropdown-item openCampaignDelete" data-campaignid="${data}" onclick="showConfrom(${data})"><i class="fa fa-trash-o fa-lg"></i> Delete</a>
                                </div>
                            </div>
                        </div>`;
                        }
                    }
                ],
language: {
    processing: `
        <span style="display:flex; align-items:center; justify-content:center; gap:8px;">
            <img src="https://i.gifer.com/ZZ5H.gif"
                 alt="Loading..." style="width:20px; height:20px;">
            Processing...
        </span>
    `
}
            });

    // Format time helper
function formatTime(timeStr) {
    if (!timeStr || timeStr.trim() === "" || timeStr.toLowerCase() === "invalid") {
        return "";
    }

    // Split manually instead of using Date (to avoid timezone conversion)
    const [hour, minute, second] = timeStr.split(':').map(Number);
    let hours = hour;
    const minutes = minute;
    const ampm = hours >= 12 ? 'PM' : 'AM';
    hours = hours % 12;
    hours = hours ? hours : 12; // convert 0 to 12 for 12-hour format

    return `${hours}:${minutes.toString().padStart(2, '0')} ${ampm}`;
}

        });
    </script>

    <script>
    // Health check inside modal (button click)
    $(document).on('click', '.check-health-btn', function() {
        var btn = $(this);
        var campaignId = btn.data('campaign-id');
        var resultDiv = $('#health-result-' + campaignId);

        btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Checking...');
        resultDiv.hide();

        $.ajax({
            url: '/campaign-health/' + campaignId,
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success && response.data) {
                    var d = response.data;
                    var bgColor = getHealthColor(d.status);
                    var html = buildHealthHtml(d, bgColor);
                    resultDiv.html(html).show();
                } else {
                    resultDiv.html('<span class="text-danger">Unable to check health.</span>').show();
                }
            },
            error: function() {
                resultDiv.html('<span class="text-danger">Health check request failed.</span>').show();
            },
            complete: function() {
                btn.prop('disabled', false).html('<i class="fa fa-heartbeat"></i> Check Campaign Health');
            }
        });
    });

    // Health check inline from DataTable action column (heartbeat icon)
    $('#user_table').on('click', '.health-check-icon', function(e) {
        e.preventDefault();
        e.stopPropagation();

        // Close any existing popovers
        $('.health-popover').remove();

        var el = $(this);
        var campaignId = el.data('campaign-id');
        var td = el.closest('td');
        td.css('position', 'relative');

        // Create popover with loading state
        var popover = $('<div class="health-popover">' +
            '<div class="health-popover-header">' +
                '<span><i class="fa fa-heartbeat"></i> Campaign Health</span>' +
                '<button class="health-popover-close">&times;</button>' +
            '</div>' +
            '<div class="health-popover-body" style="text-align:center;padding:16px;">' +
                '<i class="fa fa-spinner fa-spin"></i> Checking...' +
            '</div>' +
        '</div>');

        td.append(popover);

        // Close button handler
        popover.find('.health-popover-close').on('click', function() {
            popover.remove();
        });

        $.ajax({
            url: '/campaign-health/' + campaignId,
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success && response.data) {
                    var d = response.data;
                    var bgColor = getHealthColor(d.status);
                    var html = buildHealthHtml(d, bgColor);
                    popover.find('.health-popover-body').html(html);
                } else {
                    popover.find('.health-popover-body').html(
                        '<span class="text-danger"><i class="fa fa-times-circle"></i> Unable to check health.</span>'
                    );
                }
            },
            error: function() {
                popover.find('.health-popover-body').html(
                    '<span class="text-danger"><i class="fa fa-times-circle"></i> Health check failed.</span>'
                );
            }
        });
    });

    // Close health popover when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.health-check-icon, .health-popover').length) {
            $('.health-popover').remove();
        }
    });

    // Shared helpers
    function getHealthColor(status) {
        var colorMap = {
            'RUNNING': '#28a745',
            'PAUSED': '#6c757d',
            'BLOCKED': '#ff9800',
            'IDLE': '#2196f3',
            'SYSTEM_ISSUE': '#f44336',
            'NOT_FOUND': '#f44336'
        };
        return colorMap[status] || '#9e9e9e';
    }

    function buildHealthHtml(d, bgColor) {
        var iconMap = {
            'RUNNING': 'fa-check-circle',
            'PAUSED': 'fa-pause-circle',
            'BLOCKED': 'fa-exclamation-triangle',
            'IDLE': 'fa-info-circle',
            'SYSTEM_ISSUE': 'fa-times-circle',
            'NOT_FOUND': 'fa-question-circle'
        };
        var icon = iconMap[d.status] || 'fa-info-circle';

        var html = '<div style="background:' + bgColor + ';color:#fff;padding:10px 12px;border-radius:6px;font-size:0.82rem;">';
        html += '<div style="margin-bottom:4px;"><i class="fa ' + icon + '" style="margin-right:4px;"></i> <strong>' + d.status + '</strong></div>';
        html += '<div>' + d.message + '</div>';
        if (d.action_hint) {
            html += '<div style="margin-top:6px;padding-top:6px;border-top:1px solid rgba(255,255,255,0.3);font-size:0.78rem;opacity:0.95;">';
            html += '<i class="fa fa-lightbulb-o" style="margin-right:3px;"></i> ' + d.action_hint;
            html += '</div>';
        }
        html += '</div>';
        return html;
    }
    </script>

@endsection
