<?php
function add_notice_ticker_css() {
    $plugin_url = plugin_dir_url( __FILE__ );
    wp_enqueue_style( 'style',  $plugin_url . "notice-ticker.css");
}

add_action( 'wp_enqueue_scripts', 'add_notice_ticker_css' );


add_shortcode('STATIC-NOTICE-HEADER-SETTING-PAGE', 'static_notice_header_setting_page_callback');
function static_notice_header_setting_page_callback()
{
    $html = "";
    ob_start();
    $csr_launch_on_static_notice_status = get_option('csr_launch_on_notice');
    $csr_launch_on_lable = $csr_launch_on_static_notice_status ?  'Enabled' : 'Disabled';

    $original_csr_allocation_status = get_option('original_csr_allocation_notice');
    $original_csr_allocation_lable = $original_csr_allocation_status ?  'Enabled' : 'Disabled';

    ?>
    <div class="custom-control custom-switch mb-0 p-0 static_notice_setting_wrapper">
        <h5 class="text-left">CSR Notices</h5>
            <div class="d-flex" style="justify-content: start;gap: 120px;">
                <div class="form-group">
                    <label>CSR-25 Launch on notice:</label>
                    <div class="custom-control custom-switch mb-0">
                        <input type="checkbox" class="custom-control-input staic_csr_notice_toggle" name="csr_launch_on_notice" value="<?=$csr_launch_on_static_notice_status?>" <?=($csr_launch_on_static_notice_status == 1) ? 'checked' : ''?> id="csr_launch_on_notice" data-_micro="ebd73bb2cd">
                        <label class="custom-control-label" for="csr_launch_on_notice"><?=$csr_launch_on_lable?></label>
                    </div>
                </div>
                <div class="form-group">
                    <label>Original CSR Allocation notice:</label>
                    <div class="custom-control custom-switch mb-0">
                        <input type="checkbox" class="custom-control-input staic_csr_notice_toggle" name="original_csr_allocation_notice" value="<?=$original_csr_allocation_status?>" <?=($original_csr_allocation_status == 1) ? 'checked' : ''?> id="original_csr_allocation_notice" data-_micro="ebd73bb2cd">
                        <label class="custom-control-label" for="original_csr_allocation_notice"><?=$original_csr_allocation_lable?></label>
                    </div>
                </div>

            </div>
    </div>
    <?php
    $html .= ob_get_clean();
    return $html;
}

add_shortcode('NOTICE-HEADER-SETTING-PAGE', 'notice_header_setting_page_callback');
function notice_header_setting_page_callback()
{
    $html = "";
    wp_enqueue_style( 'cip-css' );
    wp_enqueue_style( 'bs-table' );
    wp_enqueue_style( 'bs-sticky-header' );
    wp_enqueue_script('bs-table');
    wp_enqueue_script('bs-sticky-header');
    wp_enqueue_script('bs-table-filter-control');
    ob_start();
    ?>
    <?php
        // echo do_shortcode('[STATIC-NOTICE-HEADER-SETTING-PAGE]');
    ?>

    <div class="promotion_notice_setting_wrapper">
        <!-- <hr class="m-3"> -->
        <!-- <h5 class="text-left">Promotion Notices</h5> -->
        <div class="text-right">
            <button type="button" id="create_notice_header" class="text-right mb-2" data-toggle="modal" data-target="#createNoticeHeader"><i class="fa fa-plus" aria-hidden="true"></i> <?php _e('Add Notice', CIP_TXTDOMAIN); ?></button>
        </div>
        <table id="cip_notice_header_setting_table" data-filter-control="true" data-show-search-clear-button="false" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" data-click-to-select="false" class="table table-bordered" data-side-pagination="server" data-pagination="true" data-page-list="[10, 20, 50, 100]">
        <thead>
            <tr>
                <th data-field="id" class="id" data-switchable="false"><?php _e('ID','corsair-login'); ?></th>
                <th data-field="title" data-filter-control="input" data-sortable="true" class="title" data-switchable="false"><?php _e('Title','corsair-login'); ?></th>
                <th data-field="description" data-filter-control="input" data-sortable="true" class="description" data-switchable="false"><?php _e('Description','corsair-login'); ?></th>
                <th data-field="notice_datetime" class="notice_datetime" data-switchable="false"><?php _e('Notice DateTime','corsair-login'); ?></th>
                <th data-field="starting_at" class="starting_at" data-switchable="false"><?php _e('Starting At','corsair-login'); ?></th>
                <th data-field="ending_at" class="ending_at" data-switchable="false"><?php _e('Ending At','corsair-login'); ?></th>
                <th data-field="toggle" class="toggle" data-switchable="false"><?php _e('Status','corsair-login'); ?></th>
                <th data-field="action" class="action" data-switchable="false"><?php _e('Action','corsair-login'); ?></th>
            </tr>
        </thead>
        <tbody>
        </tbody>
        </table>

    </div>
    <div class="modal fade" id="createNoticeHeader" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <form class="create_notice_header" id="create_notice_header" name="create_notice_header">
                        <div class="form-group">
                            <h5><?php _e('Add Notice', CIP_TXTDOMAIN); ?></h5>
                        </div>
                        <div class="form-group">
                            <label for="notice_title"><?php echo __('Title', CIP_TXTDOMAIN); ?></label>
                            <input type="text" class="form-control" id="notice_title" name="notice_title" required/>
                        </div>
                        <div class="form-group">
                            <!-- <div class="otp_section pb-3"> -->
                                <label class="desc_notice" for="notice_description"><?php echo __('Description', CIP_TXTDOMAIN); ?></label> <label style="color: #00000085;">
                                    <!-- make banner at 1 place -->
                                    <ul class="notice_desc_ul">
                                    <li>Add [date] in the description to add a countdown period.</li>
                                    <li>Add <span>[</span>CSRRemain<span>]</span> in the description to add a circulating supply. Please <a href="<?php echo get_permalink( 9451 ); ?>" target="_blank"> click here </a></li>to add CSRRemain address.
                                    </ul>
                                    <!-- make banner at 1 place END -->
                                </label>
                                <input type="text" name="notice_description" id="notice_description" class="form-control"  required/>
                                <!-- <small class="form-text text-muted"><?php _e('Enter dates or times in the format [yyyy-mm-dd H:i:s]; you may include either a full date, a time, or both.') ?></small> -->
    

                            <!-- </div> -->
                        </div>
                        <div class="row">
                            <div class="form-group col-6">
                                <label for="notice_date"><?php echo __('Notice Date', CIP_TXTDOMAIN); ?></label>
                                <input type="date" name="notice_date" id="notice_date">
                                <!-- <input type="datetime-local" class="form-control" id="notice_time" name="notice_time"/> -->
                            </div>
                            <div class="form-group col-6">
                                <label for="notice_time"><?php echo __('Notice Time', CIP_TXTDOMAIN); ?></label>
                                <input type="time" name="notice_time" id="notice_time" step="1">
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="starting_at"><?php echo __('Starting At', CIP_TXTDOMAIN); ?></label>
                            <input type="datetime-local" class="form-control" id="starting_at" name="starting_at" required />
                        </div>
                        <div class="form-group">
                            <label for="ending_at"><?php echo __('Ending At', CIP_TXTDOMAIN); ?></label>
                            <input type="datetime-local" class="form-control" id="ending_at" name="ending_at" required/>
                        </div>
                        <button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
                        <input type="hidden" name="action" value="create_notice_header_action" />
                        <input type="hidden" name="pageid" value="<?php echo get_the_id(); ?>" />
                        <input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_YCIPCreateNoticeHeader_'); ?>" />
                    </form>
                </div>
            </div>
        </div>
    </div>


    <div class="modal fade" id="editNoticeHeader" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <form class="edit_notice_header" id="edit_notice_header" name="edit_notice_header">
                        <div class="form-group">
                            <h5><?php _e('Edit Notice', CIP_TXTDOMAIN); ?></h5>
                        </div>
                        <div class="form-group">
                            <label for="notice_title"><?php echo __('Title', CIP_TXTDOMAIN); ?></label>
                            <input type="text" class="form-control" id="notice_title" name="notice_title" required/>
                        </div>
                        <div class="form-group">
                        <!-- <div class="otp_section pb-3"> -->
                            <!-- make banner at 1 place added class="desc_notice" -->
                            <label class="desc_notice" for="notice_description"><?php echo __('Description', CIP_TXTDOMAIN); ?></label> <label style="color: #00000085;"><!-- make banner at 1 place -->
                            <ul class="notice_desc_ul">
                                    <li>Add [date] in the description to add a countdown period.</li>
                                    <li>Add <span>[</span>CSRRemain<span>]</span> in the description to add a circulating supply. Please <a href="<?php echo get_permalink( 9451 ); ?>" target="_blank"> click here </a></li>to add CSRRemain address.
                                    </ul>
                                    <!-- make banner at 1 place END -->

                            </label>
                            <input type="text" name="notice_description" id="notice_description" class="form-control"  required/>
                            <!-- <small class="form-text text-muted"><?php _e('Enter dates or times in the format [yyyy-mm-dd H:i:s]; you may include either a full date, a time, or both.') ?></small> -->

                        <!-- </div> -->
                        </div>
                        <div class="row">
                            <div class="form-group col-6">
                                <label for="notice_date"><?php echo __('Notice Date', CIP_TXTDOMAIN); ?></label>
                                <input type="date" name="notice_date" id="notice_date">
                                <!-- <input type="datetime-local" class="form-control" id="notice_time" name="notice_time"/> -->
                            </div>
                            <div class="form-group col-6">
                                <label for="notice_time"><?php echo __('Notice Time', CIP_TXTDOMAIN); ?></label>
                                <input type="time" name="notice_time" id="notice_time" step="1">
                            </div>
                        </div>
                         <div class="form-group">
                            <label for="starting_at"><?php echo __('Starting At', CIP_TXTDOMAIN); ?></label>
                            <input type="datetime-local" class="form-control" id="starting_at" name="starting_at" required/>
                        </div>
                        <div class="form-group">
                            <label for="ending_at"><?php echo __('Ending At', CIP_TXTDOMAIN); ?></label>
                            <input type="datetime-local" class="form-control" id="ending_at" name="ending_at" required/>
                        </div>
                        <input type="hidden" name="notice_id" id="notice_id" value="" />
                        <button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>
                        <input type="hidden" name="action" value="edit_notice_header_action" />
                        <input type="hidden" name="pageid" value="<?php echo get_the_id(); ?>" />
                        <input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_YCIPEditNoticeHeader_'); ?>" />
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    
    <?php
    $html .= ob_get_clean();
    return $html;
}


function wpb_hook_javascript_footer() {
    ?>
        <script>
            jQuery(document).ready(function($){
                const swalToast1 = Swal.mixin({
                    toast: true,
                    animation: true,
                    position: 'bottom',
                    showConfirmButton: false,
                    timer: 4000,
                    timerProgressBar: true,
                    didOpen: (toast) => {
                      toast.addEventListener('mouseenter', Swal.stopTimer)
                      toast.addEventListener('mouseleave', Swal.resumeTimer)
                    }
                });
                $(document).on('submit', '#createNoticeHeader #create_notice_header', function(){
                    var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
                    
                    $form = $(this);
                    
                    var data = $(this).serialize();
                    $.blockUI(block_config);
                    $.post(cipscript.ajax_url, data, function(response) {
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
                            swalToast1({ type: 'success', title: obj.msg });
                            $("#createNoticeHeader").modal('hide');
                            $form[0].reset();
                            let eve = jQuery.Event("keyup");
                            eve.which = 13
                            eve.keyCode = 13
                            $('#cip_notice_header_setting_table input[type="search"].form-control.search-input').val('').trigger(eve);
                        }else{
                            swalToast1({ type: 'error', title: obj.msg });
                        }
                        $.unblockUI();
                    });
                    return false;
                });

                $(document).on('change', '#cip_notice_header_setting_table .notice_status_manage_chkbox', function(){
                    var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
                    var isEnabling = 0;
                    if( $(this).is(':checked') ){
                        isEnabling = 1;
                    }
                    var thisElem = $(this);
                    var data = {};
                    data['action'] = 'notice_status_checkbox_action';
                    data['thisNotice'] = $(this).val();
                    data['isEnabling'] = isEnabling;
                    data['_micro'] = $(this).attr('data-_micro');

                    $.blockUI(block_config);
                    $.post(cipscript.ajax_url, data, function(response) {
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
                            // window.location.reload();
                            thisElem.next('label').html( obj.label );
                            swalToast1({ type: 'success', title: obj.msg });
                        }else{
                            Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
                        }
                        $.unblockUI();
                    });
                    return false;
                });

                $(document).on('click', '#cip_notice_header_setting_table .edit-notice-header', function(){
                    var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
                    var thisElem = $(this);
                    var data = {};
                    data['action'] = 'get_notice_record_by_id_action';
                    data['thisNotice'] = $(this).attr('data-edit');
                    data['_micro'] = $(this).attr('data-_micro');
                    $.blockUI(block_config);
                    $.post(cipscript.ajax_url, data, function(response) {
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
                            if(obj.data)
                            {   
                                var data = obj.data;
                                var title = data.title;
                                var description = data.description;
                                var notice_datetime = data.notice_time;
                                var notice_id = data.id;
                                var starting_at = data.starting_at;
                                var ending_at = data.ending_at;
                                var notice_datetime_array = notice_datetime.split(' ')


                                $('#edit_notice_header #notice_title').val(title)
                                $('#edit_notice_header #notice_description').val(description)
                                $('#edit_notice_header #notice_date').val(notice_datetime_array[0])
                                $('#edit_notice_header #notice_time').val(notice_datetime_array[1])
                                $('#edit_notice_header #notice_id').val(notice_id)
                                $('#edit_notice_header #starting_at').val(starting_at)
                                $('#edit_notice_header #ending_at').val(ending_at)
                            }
                            $('#editNoticeHeader').modal('show')                
                        }else{
                            Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
                        }
                        $.unblockUI();
                    });

                    return false;
                });

                $(document).on('submit', '#editNoticeHeader #edit_notice_header', function(){
                    var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
                    
                    $form = $(this);
                    var data = $(this).serialize();
                    $.blockUI(block_config);
                    $.post(cipscript.ajax_url, data, function(response) {
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
                            swalToast1({ type: 'success', title: obj.msg });
                            $("#editNoticeHeader").modal('hide');
                            $form[0].reset();
                            let eve = jQuery.Event("keyup");
                            eve.which = 13
                            eve.keyCode = 13
                            $('#cip_notice_header_setting_table input[type="search"].form-control.search-input').val('').trigger(eve);
                        }else{
                            swalToast1({ type: 'error', title: obj.msg });
                        }
                        $.unblockUI();
                    });
                    return false;
                });

                $(document).on('click', '#cip_notice_header_setting_table .delete-notice-header', function(){
                    var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
                    var thisElem = $(this);

                    Swal({
                        title: 'Are you sure?',
                        text: "Do you want to remove notice?",
                        type: 'warning',
                        showCancelButton: true,
                        confirmButtonText: 'Yes'
                      }).then((result) => {
                        if (result.value) {
                            var data = { 'action' : 'delete_notice_record_action', 'thisNotice' : $(this).attr('data-delete'), '_micro' : $(this).attr('data-micro') };
                            $.blockUI(block_config);
                            $.post(cipscript.ajax_url, data, function(response) {
                                var obj = JSON.parse( response );
                                if( obj.error == 0 ){
                                    swalToast1({ type: 'success', title: obj.msg });
                                    let eve = jQuery.Event("keyup");
                                    eve.which = 13
                                    eve.keyCode = 13
                                    $('#cip_notice_header_setting_table input[type="search"].form-control.search-input').val('').trigger(eve);
                                }else{
                                    Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
                                }
                                $.unblockUI();
                            });
                            return false;
                        }
                    });
                });

                $(document).on('change', '.staic_csr_notice_toggle', function(){
                    var block_config = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
                    var isEnabling = 0;
                    if( $(this).is(':checked') ){
                        isEnabling = 1;
                    }
                    var thisElem = $(this);
                    var data = {};
                    data['action'] = 'static_notice_manager_action';
                    data['thisNotice'] = $(this).val();
                    data['isEnabling'] = isEnabling;
                    ;data['toggleName'] = $(this).attr('id')

                    $.blockUI(block_config);
                    $.post(cipscript.ajax_url, data, function(response) {
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
                            // window.location.reload();
                            thisElem.next('label').html( obj.label );
                            swalToast1({ type: 'success', title: obj.msg });
                        }else{
                            Swal.fire({ type: 'error', title: obj.msg, text: '',allowOutsideClick: false});
                        }
                        $.unblockUI();
                    });
                    return false;
                });
            })

        </script>
    <?php
}
add_action('wp_footer', 'wpb_hook_javascript_footer');

// notice header
add_action('wp_ajax_cip_notice_header_setting_loader','cip_notice_header_setting_loader');
function cip_notice_header_setting_loader(){
    global $wpdb;
    $tableNoticeHeader = $wpdb->prefix.'notice_ticker';
    
    $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableNoticeHeader WHERE 1=1");
    
    $limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
    $offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
    $orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
    $order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';
    
    $filter_qry = "";
    $filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
    if( !empty( $filters ) ){
        foreach( $filters as $filterKey => $filterData ){
            $filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
        }
        $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableNoticeHeader WHERE 1=1 $filter_qry");
    }
    
    $getNoticeHeader = $wpdb->get_results("SELECT * FROM $tableNoticeHeader WHERE 1=1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset");
    
    $rows = array();
    if( $getNoticeHeader ){
        $sno= $_REQUEST['offset'] + 1;
        foreach( $getNoticeHeader as $getNotice ){
            $row = array();
            $row['id'] = $sno;
            $columnsArr = array(
                'title' =>  __('title', CIP_TXTDOMAIN),
                'description' =>    __('description', CIP_TXTDOMAIN),
                'notice_datetime' =>    __('notice_datetime', CIP_TXTDOMAIN),
                'toggle' => __('toggle', CIP_TXTDOMAIN),
                'starting_at' => __('starting_at', CIP_TXTDOMAIN),
                'ending_at' => __('ending_at', CIP_TXTDOMAIN),
            );
            if( $columnsArr ){
                foreach( $columnsArr as $columnKey => $columnsVal ){                
                    
                    $label = ( $getNotice->toggle ) ? 'Enabled' : 'Disabled';
                    $encryptId = $getNotice->id;

                    if($columnKey == 'toggle')
                    {
                        $row[$columnKey] = '<div class="custom-control custom-switch mb-0"><input type="checkbox" class="custom-control-input notice_status_manage_chkbox" name="noticeHeader" value="'.$getNotice->id.'" id="country_'. $getNotice->id .'" data-_micro="'.wp_create_nonce('_Micro_NoticeHeaderCreate_Micro_').'" '. checked( 1, $getNotice->toggle, false ).' /><label class="custom-control-label" for="country_'. $getNotice->id .'">'. $label .'</label></div>';                        
                    }
                    else
                    {
                        $columnsDataVal = $getNotice->$columnKey;
                        $row[$columnKey] = $columnsDataVal;
                    }
                    if($columnKey == 'notice_datetime')
                    {
                        if($getNotice->notice_time != null && $getNotice->notice_time != "0000-00-00 00:00:00")
                        {
                            $timestamp = strtotime($getNotice->notice_time);
                            $row[$columnKey] = date("d/m/Y H:i:s A", $timestamp);
                        }
                    }
                    if($columnKey == 'starting_at')
                    {
                        if($getNotice->starting_at != null && $getNotice->starting_at != "0000-00-00 00:00:00")
                        {
                            $timestamp = strtotime($getNotice->starting_at);
                            $row[$columnKey] = date("d/m/Y H:i A", $timestamp);
                        }
                    }
                    if($columnKey == 'ending_at')
                    {
                        if($getNotice->ending_at != null && $getNotice->ending_at != "0000-00-00 00:00:00")
                        {
                            $timestamp = strtotime($getNotice->ending_at);
                            $row[$columnKey] = date("d/m/Y H:i A", $timestamp);                        
                        }
                    }
                    if($columnKey == 'description')
                    {
                        $row[$columnKey] = "<div class='description_wrapper'>".$getNotice->$columnKey."</div>";
                    }

                    $row['action'] = '<a href="javascript:void(0);" class="edit-notice-header " data-edit="'. $getNotice->id .'" data-_micro="'.wp_create_nonce('_Micro_NoticeHeaderEdit_Micro_').'" data-toggle-tt="tooltip" data-placement="top" title="'.__('Edit', CIP_TXTDOMAIN).'"><i class="fas fa-pencil-alt"></i></a> 
                                    <a href="javascript:void(0);" class="delete-notice-header ml-3" data-delete="'. $getNotice->id .'" data-micro="'.wp_create_nonce('_Micro_NoticeHeaderDelete_Micro_').'" data-toggle-tt="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt"></i></a>';
                }
            }
            $rows[] = $row;
            $sno=$sno+1;
        }
    }
    $out = array(
        'total'         =>  $total_items,
        'rows'          =>  $rows,
    );
    echo wp_json_encode( $out );
    exit;
}

add_action('wp_ajax_create_notice_header_action', 'create_notice_header_action_callback');
function create_notice_header_action_callback(){
    $out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
    if( wp_verify_nonce( $_POST['_micro'],'_YCIPCreateNoticeHeader_' )){
        global $wpdb;
        $tableSmsAlert = $wpdb->prefix.'notice_ticker';

        $current_user = wp_get_current_user();
        $user_id = $current_user->ID;

        $status = 1;

        $start_datetime = $_POST['starting_at'];
        $end_datetime = $_POST['ending_at'];
        $notice_title = $_POST['notice_title'];
        $notice_description = $_POST['notice_description'];
        $notice_date = ($_POST['notice_date'] != '') ? $_POST['notice_date'] : '0000-00-00';
        $notice_time = ($_POST['notice_time'] != '') ? $_POST['notice_time'] : '00:00:00';
        $notice_datetime = $notice_date.' '.$notice_time;

        if($notice_title == '' || $notice_description =='')
        {
            $out = array( "error" => 1,'msg' => __('Title and Description are required.',CIP_TXTDOMAIN) );                   
        }

        if($start_datetime == null || $end_datetime == null || $start_datetime == '' || $end_datetime == '')
        {
            $out = array( "error" => 1,'msg' => __('Starting and ending time are required.',CIP_TXTDOMAIN) );                   
        }
        
        $insert = $wpdb->insert( $tableSmsAlert, ['title' => $_POST['notice_title'],'description' => $_POST['notice_description'],'notice_time' => $notice_datetime, 'toggle' => 0,'starting_at'=> $_POST['starting_at'],'ending_at'=> $_POST['ending_at'] ,'create_date' => date_i18n('Y-m-d H:i:s')] );
        if( $insert ){
            $statusLable = $status == 1? 'Enabled' : 'Disabled';
            $logs = sprintf( __('Header notice Added by %s at %s. details: 
                Title: %s
                Description: %s
                Notice Time: %s
                Status: %s
                Starting At: %s
                Ending At: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $_POST['notice_title'],sanitize_text_field($_POST['notice_description']),date("d/m/Y H:i A", strtotime($notice_datetime)),$statusLable,date("d/m/Y H:i A", strtotime($_POST['starting_at'])),date("d/m/Y H:i A", strtotime($_POST['ending_at'])));
            create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
            $out = array( "error" => 0,'msg' => __('Notice header added',CIP_TXTDOMAIN) );
        }

    }
    echo wp_json_encode( $out );
    exit;
}
add_action('wp_ajax_edit_notice_header_action', 'edit_notice_header_action_callback');
function edit_notice_header_action_callback(){
    $out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
    if( wp_verify_nonce( $_POST['_micro'],'_YCIPEditNoticeHeader_' )){
        global $wpdb;
        $tableSmsAlert = $wpdb->prefix.'notice_ticker';


        $current_user = wp_get_current_user();
        $user_id = $current_user->ID;
        
        $noticeId = $_POST['notice_id'];
        $title = $_POST['notice_title'];
        $description = $_POST['notice_description'];
        $starting_at = $_POST['starting_at'];
        $ending_at = $_POST['ending_at'];
        $notice_date = ($_POST['notice_date'] != '') ? $_POST['notice_date'] : '0000-00-00';
        $notice_time = ($_POST['notice_time'] != '') ? $_POST['notice_time'] : '00:00:00';
        $notice_datetime = $notice_date.' '.$notice_time;
        

        if($title == '' || $description =='')
        {
            $out = array( "error" => 1,'msg' => __('Title and Description are required.',CIP_TXTDOMAIN) );                   
        }

        if($starting_at == null || $ending_at == null || $starting_at == '' || $ending_at == '')
        {
            $out = array( "error" => 1,'msg' => __('Starting and ending time are required.',CIP_TXTDOMAIN) );                   
        }

        $noticeItem = $wpdb->get_row("SELECT * FROM $tableSmsAlert WHERE id = $noticeId");

        if(!$noticeItem)
        {
            $out = array( "error" => 1,'msg' => __('Record not found',CIP_TXTDOMAIN));
        }
        else{

            $status = 1;

            $update = $wpdb->query( $wpdb->prepare("UPDATE $tableSmsAlert SET title = %s, description = %s, notice_time = %s, starting_at = %s,ending_at = %s WHERE id = %s",$title, $description,$notice_datetime,$starting_at, $ending_at, $noticeId));
            
            $status = $noticeItem->toggle == 1 ? 'Enabled' : 'Disabled'; 
            $logs = sprintf( __('Header notice updated by %s at %s. details: 
                Id: %s
                Old Title: %s
                Old Description: %s
                Old Notice Time: %s
                Old Starting At: %s
                Old Ending At: %s
                Title: %s
                Description: %s
                Notice Time: %s
                Status: %s
                Starting At: %s
                Ending At: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'),$noticeId,$noticeItem->title,sanitize_text_field($noticeItem->description),date("d/m/Y H:i A", strtotime($noticeItem->notice_time)),date("d/m/Y H:i A", strtotime($noticeItem->starting_at)),date("d/m/Y H:i A", strtotime($noticeItem->ending_at)),$_POST['notice_title'], sanitize_text_field($_POST['notice_description']),date("d/m/Y H:i A", strtotime($notice_datetime)),$status,date("d/m/Y H:i A", strtotime($_POST['starting_at'])),date("d/m/Y H:i A", strtotime($_POST['ending_at'])));
            create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
            $out = array( "error" => 0,'msg' => __('Notice header updated',CIP_TXTDOMAIN) );
        }


    }
    echo wp_json_encode( $out );
    exit;
}

add_action('wp_ajax_notice_status_checkbox_action', 'notice_status_checkbox_action_callback');
function notice_status_checkbox_action_callback(){

    $out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
    if( wp_verify_nonce( $_POST['_micro'],'_Micro_NoticeHeaderCreate_Micro_' )){
        global $wpdb;
        $tableSmsAlert = $wpdb->prefix.'notice_ticker';

        $noticeId = $_POST['thisNotice'];
        $statusVal = $_POST['isEnabling'];

        $noticeItem = $wpdb->get_row("SELECT * FROM $tableSmsAlert WHERE id = $noticeId");

        if(!$noticeItem)
        {
            $out = array( "error" => 1,'msg' => __('Record not found',CIP_TXTDOMAIN));
        }
        else
        {
            $update = $wpdb->query( $wpdb->prepare("UPDATE $tableSmsAlert SET toggle = %s WHERE id = %s",$statusVal, $noticeId));
            if($update)
            {
                $current_user = wp_get_current_user();
                $user_id = $current_user->ID;
                $status = $statusVal == 1 ? 'Enabled' : 'Disabled'; 
                $logs = sprintf( __('Header notice status %s by %s at %s details: 
                    Title: %s
                    Description: %s
                    Status: %s', CIP_TXTDOMAIN), $status, $current_user->user_email, date_i18n('d/m/Y H:i A'), $noticeItem->title,sanitize_text_field($noticeItem->description),$status);
                create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
                $out = array( "error" => 0,'label'=>$status,'msg' => __('Notice header status updated',CIP_TXTDOMAIN) );
            }else{
                $out = array( "error" => 0,'msg' => __('Failed to update',CIP_TXTDOMAIN) );
            }
        }
    }
    echo wp_json_encode( $out );
    exit;
}
add_action('wp_ajax_get_notice_record_by_id_action', 'get_notice_record_by_id_action_callback');
function get_notice_record_by_id_action_callback(){

    $out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
    if( wp_verify_nonce( $_POST['_micro'],'_Micro_NoticeHeaderEdit_Micro_' )){
        global $wpdb;
        $tableSmsAlert = $wpdb->prefix.'notice_ticker';

        $noticeId = $_POST['thisNotice'];       

        $noticeItem = $wpdb->get_row("SELECT * FROM $tableSmsAlert WHERE id = $noticeId");

        if(!$noticeItem)
        {
            $out = array( "error" => 1,'msg' => __('Record not found',CIP_TXTDOMAIN));
        }
        else
        {
            $out = array( "error" => 0,'data'=> $noticeItem,'msg' => __('Notice header',CIP_TXTDOMAIN) );
        }
    }
    echo wp_json_encode( $out );
    exit;
}
add_action('wp_ajax_delete_notice_record_action', 'delete_notice_record_action_callback');
function delete_notice_record_action_callback(){

    $out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
    if( wp_verify_nonce( $_POST['_micro'],'_Micro_NoticeHeaderDelete_Micro_' )){
        global $wpdb;
        $tableSmsAlert = $wpdb->prefix.'notice_ticker';

        $noticeId = $_POST['thisNotice'];       

        $noticeItem = $wpdb->get_row("SELECT * FROM $tableSmsAlert WHERE id = $noticeId");
        $delterecord = $wpdb->delete( $tableSmsAlert, array( 'id' => $noticeId ) );

        if(!$delterecord)
        {
            $out = array( "error" => 1,'msg' => __('Record not found',CIP_TXTDOMAIN));
        }
        else
        {
            $logs = sprintf( __('Header notice deleted by %s at %s details: 
                Title: %s
                Description: %s.', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $noticeItem->title,sanitize_text_field($noticeItem->description));
            create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
            
            $out = array( "error" => 0,'data'=> $noticeItem,'msg' => __('Notice header deleted.',CIP_TXTDOMAIN) );
        }
    }
    echo wp_json_encode( $out );
    exit;
}

add_action('wp_ajax_static_notice_manager_action', 'static_notice_manager_action_callback');
function static_notice_manager_action_callback(){
    $out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
    
    if(isset($_POST['toggleName']) )
    {
        $old_csr_launch_on_notice = $_POST['isEnabling'];
        update_option( $_POST['toggleName'], $old_csr_launch_on_notice);
        $status = $old_csr_launch_on_notice == 1 ? 'Enabled' : 'Disabled';
        $headerName = str_replace('_', " ", $_POST['toggleName']);
        $logs = sprintf( __('Header notice "%s" %s by %s at %s.', CIP_TXTDOMAIN), ucfirst($headerName),$status, $current_user->user_email, date_i18n('d/m/Y H:i A'));        
        create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
        $out = array( "error" => 0,'label'=> $status,'msg' => __('Status updated.',CIP_TXTDOMAIN) );
    }
    
    echo wp_json_encode( $out );
    exit;
}


function validate_header_notice_expiry_script() {
    global $wpdb;
    $tableNoticeHeader = $wpdb->prefix.'notice_ticker';

    $getNoticeHeader = $wpdb->get_results("SELECT * FROM $tableNoticeHeader");    
    
    $disabledNotice = [];
    $enabledNotice = [];

    $disabledNoticeDetail = [];
    $enabledNoticeDetail = [];

    foreach ($getNoticeHeader as $key => $notice) {
        if($notice->starting_at != '' && $notice->ending_at != '')
        {
            $start_datetime = $notice->starting_at;
            $end_datetime = $notice->ending_at;

            $start = new DateTime($start_datetime, new DateTimeZone('GMT'));
            $end = new DateTime($end_datetime, new DateTimeZone('GMT'));

            $current_time = new DateTime('now', new DateTimeZone('GMT'));

            // if ($current_time >= $start && $current_time <= $end) {
            if ($current_time < $start || $current_time > $end) {
                if($notice->toggle != '0')
                {
                    array_push($disabledNotice, $notice->id);
                    array_push($disabledNoticeDetail, $notice);
                }
            }else {
                if($notice->toggle != '1')
                {
                    array_push($enabledNotice, $notice->id);
                    array_push($enabledNoticeDetail, $notice);
                }
            }            
        }
    }

    if(!empty($disabledNotice))
    {
        $disabledNoticeIds = implode(',', array_map('intval', $disabledNotice));
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE $tableNoticeHeader SET toggle = 0 WHERE id IN ($disabledNoticeIds)"
            )
        );
        foreach ($disabledNoticeDetail as $key => $notice) {
            $logs = sprintf( __('Header notice "%s" Disabled by automation due to time expiretion at %s.', CIP_TXTDOMAIN), sanitize_text_field($notice->description), date_i18n('d/m/Y H:i A'));        
            create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
        }
    }
    if(!empty($enabledNotice))
    {
        $enabledNoticeIds = implode(',', array_map('intval', $enabledNotice));
        $wpdb->query(
            $wpdb->prepare(
                "UPDATE $tableNoticeHeader SET toggle = 1 WHERE id IN ($enabledNoticeIds)"
            )
        );
        foreach ($enabledNoticeDetail as $key => $notice) {
            $logs = sprintf( __('Header notice "%s" Enabled at scheduled time by automation at %s.', CIP_TXTDOMAIN), sanitize_text_field($notice->description), date_i18n('d/m/Y H:i A'));        
            create_cip_logs_entery( $user_id, 'sa', '','sa', $logs, true );
        }
    }
    wp_die(); // This is required to properly terminate the AJAX request
}
add_action('wp_ajax_validate_header_notice_expiry_script', 'validate_header_notice_expiry_script');
add_action('wp_ajax_nopriv_validate_header_notice_expiry_script', 'validate_header_notice_expiry_script');


add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/header_notices', array(
        'methods' => 'GET',
        'callback' => 'get_notices',
        'permission_callback' => '__return_true',
    ));
});

function get_notices() {
    // Replace this with your actual logic to retrieve notices
    global $wpdb;
    $tableNoticeHeader = $wpdb->prefix.'notice_ticker';

    $getNoticeHeader = $wpdb->get_results("SELECT * FROM $tableNoticeHeader WHERE toggle=1");    
    $jsonNotice = [];
    foreach ($getNoticeHeader as $key => $notice) {
            
        $description = $notice->description;
        $pattern = '[date]';
        $patternCSRRemain = '[CSRRemain]';

        $Finelnotice = $description;
        if (str_contains($description,$pattern)) {
            

            $currentDate =  date("Y-m-d H:i:s");

            $now = new DateTime($currentDate, new DateTimeZone('GMT'));

            $datetimeString = '';

            $notice_datetime = $notice->notice_time;
            $noticeTimeArray = explode(" ",$notice_datetime);
            $noticeDate = $noticeTimeArray[0];
            $noticeTime = $noticeTimeArray[1];

            if($noticeTime != '00:00:00' && $noticeDate != '0000-00-00')
            {

                // Handle datetime
                $targetDate = new DateTime($notice_datetime, new DateTimeZone('GMT'));

                if ($now <= $targetDate) {
                    $interval = $now->diff($targetDate);
                    $datetimeString = "<span class='notice_remainig_day_countdown'>";
                    $datetimeString .= "<span class='day_wrapper " . ($interval->days == 0 ? 'hidden' : '') . "'><span>" . $interval->days . "</span> Days</span>";
                    $datetimeString .= " <span class='hours_wrapper " . ($interval->h == 0 ? 'hidden' : '') . "'><span>" . $interval->h . "</span> Hours</span>";
                    $datetimeString .= " <span class='minutes_wrapper " . ($interval->i == 0 ? 'hidden' : '') . "'><span>" . $interval->i . "</span> Minutes</span>";             
                    $datetimeString .= "</span>";
                }

            } elseif ($noticeTime == '00:00:00' && $noticeDate != '0000-00-00') {
                
                // Handle date only
                $targetDate = new DateTime($notice_datetime , new DateTimeZone('GMT'));
                
                if ($now <= $targetDate) {
                    $interval = $now->diff($targetDate);
                    $datetimeString = "<span class='notice_remainig_day_countdown'>";
                    $datetimeString .= "<span class='day_wrapper " . ($interval->days == 0 ? 'hidden' : '') . "'><span>".$interval->days . "</span> Days</span>";
                    $datetimeString .= "</span>";
                }
                
            } elseif($noticeDate == '0000-00-00' && $noticeTime != '00:00:00') {
                
                // Handle time only

                $targetDate = new DateTime($now->format('Y-m-d')." ".$noticeTime, new DateTimeZone('GMT'));

                $interval = $now->diff($targetDate);
                if ($interval->invert) {
                    // Time has passed for today, add one day
                    $targetDate->modify('+1 day');
                    $interval = $now->diff($targetDate);
                }

                if ($now <= $targetDate) {
                    $datetimeString = "<span class='notice_remainig_day_countdown'>";
                    $datetimeString .= "<span class='hours_wrapper " . ($interval->h == 0 ? 'hidden' : '') . "'><span>".$interval->h . "</span> Hours</span>";
                    $datetimeString .= " <span class='minutes_wrapper " . ($interval->i == 0 ? 'hidden' : '') . "'><span>" . $interval->i . "</span> Minutes</span>";                    
                    $datetimeString .= "</span>";
                    // $remaining = "<span class='notice_remainig_day_countdown'><span class='hours_wrapper'>".$interval->h . "</span> Hours <span class='minutes_wrapper'>" . $interval->i . "</span> Minutes</span>";
                }

            }else {
                $remaining = $pattern;
            }

            if($datetimeString != '')
            {
                $Finelnotice = str_replace($pattern,$datetimeString,$description);
            }

        }
        //for CSRRemain
        if (str_contains($Finelnotice, $patternCSRRemain)) {
            $csrRemainText = do_shortcode($patternCSRRemain);
            $Finelnotice = str_replace($patternCSRRemain, $csrRemainText, $Finelnotice);
        }

        $newNotice = [
            "prefix" => ucfirst($notice->title),
            "heading" => $Finelnotice,
            "url" => "javascript:void(0);"
        ];

        $jsonNotice[] = $newNotice;
    }

    return new WP_REST_Response($jsonNotice, 200);
}

function get_notice_ticker_callback(){
    $html = "";
    ob_start();
	?>
    <div id="newsTicker1" class="newsTicker1"></div>
    <?php
    $html .= ob_get_clean();
	return $html;
}
add_action('wp_footer', 'notice_ticker_script');

function notice_ticker_script(){
    $jsonNotice = get_notices();
    if($jsonNotice)
    {
        $jsonNotice = $jsonNotice->data;
    }
    ?>
    <script>
        jQuery(document).ready(function($) {
            $(function() {
                function getCounterData(obj) {
                    var days = parseInt($('.day_wrapper span', obj).text()) || 0; 
                    var hours = parseInt($('.hours_wrapper span', obj).text()) || 0;
                    var minutes = parseInt($('.minutes_wrapper span', obj).text()) || 0;

                    // Calculate total minutes
                    return minutes + (hours * 60) + (days * 24 * 60);
                }

                function setCounterData(s, obj) {
                    var days = Math.floor(s / (60 * 24));
                    var hours = Math.floor((s % (60 * 24)) / 60);
                    var minutes = Math.floor(s % 60);

                    // console.log(days, hours, minutes); // Log without seconds

                    var rhtml = "";
                    rhtml += "<span class='day_wrapper " + (days === 0 ? 'hidden' : '') + "'><span>" + days + "</span> Days</span>";
                    rhtml += " <span class='hours_wrapper " + (hours === 0 ? 'hidden' : '') + "'> <span>" + hours + "</span> Hours</span>";
                    rhtml += " <span class='minutes_wrapper " + (minutes === 0 ? 'hidden' : '') + "'><span>" + minutes + "</span> Minutes</span>";

                    $(obj).html(rhtml)
                }

                var timer = setInterval(function() {
                    $(".notice_remainig_day_countdown").each(function() {
                        var $this = $(this); // Store the current context
                        if($(this).find('.minutes_wrapper').length)
                        {
                            var count = getCounterData($this);
                            if (count > 0) {
                                count--; 
                                setCounterData(count, $this);
                            } else {
                                $('.day_wrapper span', $this).html(0);
                                $('.hours_wrapper span', $this).html(0);
                                $('.minutes_wrapper span', $this).html(0);
                            }                            
                        }
                    });
                }, 60000); // Update every minute                
            });



            var jsonNotice = <?=json_encode($jsonNotice)?>;
            if(!jsonNotice.length)
            {
                $("#newsTicker1").parents('section.elementor-section').hide();
            }
            var fineArray = jsonNotice;
            if(jsonNotice.length <= 3)
            {
                var originalLength = fineArray.length;                
                while (fineArray.length < 6) {
                    fineArray.push($.extend(true, {}, fineArray[fineArray.length % originalLength]));
                }
            }
            // console.log(fineArray)
            var news = jsonNotice;
            $("#newsTicker1").easyNewsTicker({
                "animation": {
                    "effect": "scroll",
                    "scroll_speed": 100,
                    "easing": "easeOutCirc",
                    "duration": 100,
                    "delay": 1e1,
                },
                "label": {
                    "enable": 0,
                },
                "navigation": {
                    "enable": 0,
                },
                "data": news,
            });
        });
    </script>
<?php
}