<?php

    if ( ! defined( 'ABSPATH' ) ) exit;

    $dvs_ucp_cron_track_time = get_option( 'dvs_ucp_cron_track_time' );
    if($dvs_ucp_cron_track_time != 'disabled') {
        add_filter( 'cron_schedules', 'dvs_ucp_track_cron_schedule' );
        add_action( 'dvs_ucp_track_cron_hook', 'dvs_ucp_track_cron_function' );
        if ( ! wp_next_scheduled( 'dvs_ucp_track_cron_hook' ) ) {
            wp_schedule_event( time(), 'dvs_ucp_cron_time', 'dvs_ucp_track_cron_hook' );
        }               
    }

    function dvs_ucp_track_cron_schedule( $schedules ) {
        $dvs_ucp_cron_track_time = get_option( 'dvs_ucp_cron_track_time' );
        if($dvs_ucp_cron_track_time != 'disabled') {
            $schedules['dvs_ucp_cron_time'] = array(
                'interval' => $dvs_ucp_cron_track_time,
                'display'  => __( 'Universal Courier Auto Track' ),
                
            );
        }
        return $schedules;
    }

    function dvs_ucp_track_cron_function() {
        global $wpdb;
        $get_orders = $wpdb->get_results("SELECT * FROM dvs_ucp_logs WHERE courier_status NOT IN ('delivered', 'returned', 'cancelled') AND DATEDIFF(NOW(), courier_datetime) < 30 ORDER BY ID DESC");
        if (count($get_orders) > 0) {
            foreach($get_orders as $order ) {  
                $order_id   = $order->order_id;
                $courier    = $order->courier_name;
                $tracking   = $order->courier_tracking;
                dvs_track_shipment($order_id, $courier, $tracking, $print=false);
            }
        } 
    }