<?php
if ( ! defined( 'ABSPATH' ) ) exit;

// ADD COURIER LOADSHEET IN DB
function dvs_ucp_add_loadsheet($loadsheet){
    global $wpdb;
    $table_name = $wpdb->prefix . 'dvs_ucp_loadsheet';
    $wpdb->insert($table_name, array(
        'shop_url'          => get_home_url(),
        'courier_name'      => $loadsheet['courier_name'],
        'courier_datetime'  => $loadsheet['courier_datetime'],
        'courier_count'     => $loadsheet['courier_count'],
        'courier_total'     => $loadsheet['courier_total'],
        'courier_cod'       => $loadsheet['courier_cod'],
        'courier_ids'       => $loadsheet['courier_ids'],
    ));
}


// ADD COURUER LOGS IN DB
function dvs_ucp_logs($order, $courier_tracking, $courier_name){
    global $wpdb;
    $wpdb->insert('dvs_ucp_logs', array(
        'shop_url' => get_home_url(),
        'courier_name' => $courier_name,
        'order_id' => $order['order_id'],
        'order_name' => $order['order_number'],
        'shipper_name' => '-',
        'shipper_address' => '-',
        'shipper_phone' => '-',
        'consignee_name' => $order['name'],
        'consignee_address' => $order['address'],
        'consignee_phone' => $order['phone'],
        'consignee_email' => $order['email'],
        'courier_type' => $order['type'],
        'courier_service' => $order['type_display'],
        'courier_handling' => $order['handling'],
        'courier_payment' => 'COD',
        'courier_origin' => '-',
        'courier_destination' => $order['hxs_city_display'],
        'courier_datetime' => current_time('mysql'),
        'order_type' => '-',
        'order_amount' => $order['amount'],
        'order_pieces' => $order['pieces'],
        'order_qty' => $order['pieces'],
        'order_remarks' => $order['remarks'],
        'order_products' => $order['products'],
        'order_weight' => $order['weight'],
        'order_cost' => 0,
        'order_total' => $order['total'],
        'courier_tracking' => $courier_tracking,
        'courier_status' => 'active',
    ));

    update_post_meta($order['order_id'], '_dvs_courier_datetime', current_time('mysql') );
}

function get_courier_key($name){
    global $couriers;
    foreach($couriers as $key => $courier){
        if($courier == $name)
            return $key;
    }
}

// Courier searchable from the admin order list search field
add_filter( 'woocommerce_shop_order_search_fields', 'marketing_search_fields', 10, 1 );
function marketing_search_fields( $meta_keys ){
    $meta_keys[] = '_dvs_courier_list';
    return $meta_keys;
}

// Add Courier Filter
add_action( 'restrict_manage_posts', 'dvs_ct_add_filter_options' );
function dvs_ct_add_filter_options(){
    global $pagenow, $post_type;

    if( 'shop_order' === $post_type && 'edit.php' === $pagenow ) {
        $domain    = 'woocommerce';
        $current   = isset($_GET['dvs_filter_by_courier'])? $_GET['dvs_filter_by_courier'] : '';

        echo '<select name="dvs_filter_by_courier">
        <option value="">' . __('Filter by Courier', $domain) . '</option>';

        $options = [
            'TCS' => __('TCS Courier'), 
            'Leopards Courier' => __('Leopards Courier'), 
            'Trax' => __('Trax Courier'),
            'MNP' => __('MNP Courier'),
            'Call Courier' => __('Call Courier'),
            'BlueEx' => __('BlueEx'),
            'Daewoo Courier' => __('Daewoo Courier'), 
            'PostEx' => __('PostEx'),                         
            'Rider' => __('Rider'),
            'Insta World' => __('Insta World'),
            'Do Deliver' => __('Do Deliver'),
            'Barq Raftar' => __('Barq Raftar'),
            'Bouraq Express' => __('Bouraq Express'),
            'Oshi Courier' => __('Oshi Courier'),
            'Zaaf Courier' => __('Zaaf Courier'),
            'Couriers Next' => __('Couriers Next'), 
            'Falcomail' => __('Falcomail'), 
            'Ship NOC' => __('Ship NOC'),            
            'AHL Courier' => __('AHL Courier'),                   
            'Rocket Courier' => __('Rocket Courier'),
            'RGS Logistics' => __('RGS Logistics'),
            'Active Courier' => __('Active Courier'),
            'Covered Logistics' => __('Covered Logistics'),
            'Pakistan Post' => __('Pakistan Post'),                                   
        ];            

        foreach ( $options as $key => $label ) {
            printf( '<option value="%s"%s>%s</option>', $key, 
                $key === $current ? '" selected="selected"' : '', $label );
        }
        echo '</select>';
    }
}

add_filter( 'request', 'dvs_ct_process_filter_options', 99 );
function dvs_ct_process_filter_options( $vars ) {
    global $pagenow, $typenow;

    if ( $pagenow == 'edit.php' && isset( $_GET['dvs_filter_by_courier'] ) 
        && $_GET['dvs_filter_by_courier'] != '' && 'shop_order' === $typenow ) {
        $vars['meta_key']   = '_dvs_courier_list';
        $vars['meta_value'] = wc_clean( $_GET['dvs_filter_by_courier'] );
    }
    return $vars;
}

add_filter ( 'woocommerce_account_menu_items', 'dvs_myaccount_order_tracking_page' );
function dvs_myaccount_order_tracking_page( $menu_links ){
    $new = array( 'dvsordertrackinglink' => 'Track Order' );
    $menu_links = array_slice( $menu_links, 0, 2, true ) 
    + $new 
    + array_slice( $menu_links, 1, NULL, true );
    return $menu_links;
}

add_filter( 'woocommerce_get_endpoint_url', 'dvs_myaccount_order_tracking_endpoint', 10, 4 );
function dvs_myaccount_order_tracking_endpoint( $url, $endpoint, $value, $permalink ){
    if( $endpoint === 'dvsordertrackinglink' ) {
        $url = site_url()."/track";
    }
    return $url;
}

add_action( 'woocommerce_order_details_after_order_table', 'dvs_display_tracking_text_single_order', 10, 1 );
function dvs_display_tracking_text_single_order( $order ) {
    $dvs_courier_list = get_post_meta( $order->get_id(), '_dvs_courier_list', true );
    $dvs_courier_tracking = get_post_meta( $order->get_id(), '_dvs_courier_tracking', true );
    if( ! empty( $dvs_courier_list ) && is_account_page() )
        echo '<p>Your order has been shipped via '. $dvs_courier_list .' and Tracking # is '. $dvs_courier_tracking .' </p>';
}

add_filter( 'manage_edit-shop_order_columns', 'dvs_add_tracking_admin_list_column' );
function dvs_add_tracking_admin_list_column( $columns ) {
    $columns['dvs_show_tracking'] = 'Tracking';
    return $columns;
}

add_action( 'manage_shop_order_posts_custom_column', 'dvs_add_tracking_admin_list_column_content' );
function dvs_add_tracking_admin_list_column_content( $column ) {
    global $post;
    global $the_order;
    if ( 'dvs_show_tracking' === $column ) {
        $order = wc_get_order( $post->ID );
        $order_id = $order->get_id();

        $dvs_courier_list = get_post_meta( $order_id, '_dvs_courier_list', true );
        $dvs_courier_tracking = get_post_meta( $order_id, '_dvs_courier_tracking', true );
        $dvs_courier_link = get_post_meta( $order_id, '_dvs_courier_link', true );
        $dvs_courier_status = get_post_meta( $order_id, '_dvs_courier_status', true );

        if(!empty($dvs_courier_list)) {

            if($order->get_billing_last_name()) {
                $consignee_name = $order->get_billing_first_name() . ' ' . $order->get_billing_last_name();
            }
            else {
                $consignee_name = $order->get_billing_first_name();
            }

            $order_name     = $order->get_order_number();
            $order_total    = $order->get_total();
            $custphone      = $order->get_billing_phone();

            $custphone = trim($custphone);
            $custphone = str_replace(["O","o"],['0','0'],$custphone);
            $custphone = preg_replace("/[^0-9]/", "", $custphone);

            $whatsappnum = WC()->countries->get_country_calling_code( $order->get_billing_country() ) . $custphone;

            $dvs_ucp_wa_text = get_option('dvs_ucp_wa_tracking_text');

            if($dvs_ucp_wa_text) {
                $whatsapp_text = $dvs_ucp_wa_text;
                $whatsapp_text = str_replace("[order_number]", $order_name, $whatsapp_text);
                $whatsapp_text = str_replace("[order_total]", (int)$order_total, $whatsapp_text);
                $whatsapp_text = str_replace("[customer_name]", $consignee_name, $whatsapp_text);
                $whatsapp_text = str_replace("[courier_name]", $dvs_courier_list, $whatsapp_text);
                $whatsapp_text = str_replace("[courier_tracking]", $dvs_courier_tracking, $whatsapp_text);
                $whatsapp_text = str_replace("[courier_link]", $dvs_courier_link, $whatsapp_text);
            }
            else {
                $whatsapp_text = "Dear ".$consignee_name.", your order #".$order_name." has been shipped. Courier is ".$dvs_courier_list." with Tracking ".$dvs_courier_tracking.". Get Live tracking: ".site_url()."/track/";
            }

            $whatsapp_text = urlencode($whatsapp_text);

            $sendwhatsapp = 'https://wa.me/'.$whatsappnum.'?text='.$whatsapp_text;

            echo '<a href="'.$sendwhatsapp.'" class="dvs-courier-whatsapp" style="background-color:#dedee0;color:#000000;padding:2px 10px;border-radius:5px;font-size:12px" target="blank">'.$dvs_courier_list.'</a>';

            echo '<br>';

            add_thickbox();
            echo '<a href="#TB_inline?width=600&height=550&inlineId=dvs-content-track" class="thickbox" onclick="dvstrackparcel(\'' . $order->get_id() . '\', \'' . $dvs_courier_list . '\', \'' . $dvs_courier_tracking . '\')">'.$dvs_courier_tracking.'</a>';

            echo '<br><span style="font-size:12px">' .$dvs_courier_status . '</span>';

            $dvs_ucp_display_average = get_option( 'dvs_ucp_display_average' );
            if($dvs_ucp_display_average == 1 ) {
                $dvs_courier_datetime   = get_post_meta( $order_id, '_dvs_courier_datetime', true );
                $dvs_shipped_datetime   = get_post_meta( $order_id, '_dvs_shipped_datetime', true );
                $dvs_received_datetime  = get_post_meta( $order_id, '_dvs_received_datetime', true );
                $dvs_parcel_days        = get_post_meta( $order_id, '_dvs_parcel_days', true );

                if($dvs_courier_datetime) {
                    echo '<hr><div style="font-size: 10px; line-height: 15px">';
                    echo '<div><strong>Booked:</strong> ' . date('d-m-Y', strtotime($dvs_courier_datetime)) . '</div>';
                }
                if($dvs_shipped_datetime) {
                    echo '<div><strong>Shipped:</strong> ' . date('d-m-Y', strtotime($dvs_shipped_datetime)) . '</div>';
                }
                if($dvs_received_datetime) {
                    echo '<div><strong>Received:</strong> ' . date('d-m-Y', strtotime($dvs_received_datetime)) . '</div>';
                }
                if($dvs_parcel_days) {
                    echo '<div><strong>Duration:</strong> ' . $dvs_parcel_days . ' Days</div>';
                }                
                echo '</div>';
            }

            ?>

            <div id="dvs-content-track" style="display:none;">
                <div class="track-thickbox">
                    <center><img src="<?php echo plugin_dir_url( __DIR__ ) . 'images/loader.gif'; ?>"></center>
                </div>
            </div>

            <div id="dvs-content-cancel" style="display:none;">
                <div class="cancel-thickbox">
                    <center><img src="<?php echo plugin_dir_url( __DIR__ ) . 'images/loader.gif'; ?>"></center>
                </div>
            </div> 

        <?php
        }
    }
}


add_action( 'admin_head', 'dvs_admin_tracking_js' );
function dvs_admin_tracking_js() {
    global $pagenow;
    $dvs_check_page = 'dvs_ucp';
    $dvs_result_page = '';
    if(!empty($_GET['page'])){
        $dvs_current_page = $_GET['page'];
        $dvs_result_page = strpos($dvs_current_page, $dvs_check_page);
    }

    if ( $pagenow === 'edit.php' && isset($_GET['post_type']) && 'shop_order' === $_GET['post_type'] || $pagenow === 'post.php' || $pagenow === 'admin.php' && $dvs_result_page !== false ) :
    ?>

    <script type='text/javascript'>
    function dvstrackparcel(orderId, courier, tracking) {
        loading = "<center><img src=\"<?php echo plugin_dir_url( __DIR__ ) . 'images/loader.gif'; ?>\"></center>"
        jQuery(".track-thickbox").html(loading);
        jQuery.ajax({
            type: 'POST',
            url: '<?php echo admin_url('/admin-ajax.php'); ?>',
            data: {
                'action':   'dvs_courier_live_tracking',
                'dvs_order_id' : orderId,
                'dvs_courier_list' : courier,                                     
                'dvs_courier_tracking' : tracking,
            },                     
            success: function (response) {
            //  console.log(response);
                jQuery(".track-thickbox").html(response);
            }                
        });
    }
    </script>    

    <script type='text/javascript'>
    function dvscancelparcel(orderId, courier, tracking) {
        loading = "<center><img src=\"<?php echo plugin_dir_url( __DIR__ ) . 'images/loader.gif'; ?>\"></center>"
        jQuery(".cancel-thickbox").html(loading);
        jQuery.ajax({
            type: 'POST',
            url: '<?php echo admin_url('/admin-ajax.php'); ?>',
            data: {
                'action':   'dvs_courier_cancel_tracking',
                'dvs_order_id' : orderId,
                'dvs_courier_list' : courier,                                     
                'dvs_courier_tracking' : tracking,
            },                     
            success: function (response) {
            //  console.log(response);
                jQuery(".cancel-thickbox").html(response);
            }                
        });
    }
    </script>    
    
    <style>
    .track-thickbox {
        color: #000000; 
    }

    .track-thickbox .order-details,
    .track-thickbox .tracking-details {
    margin-top: 20px;    
    width: 50%;
    float: left;
    }

    .track-thickbox .order,
    .track-thickbox .name,
    .track-thickbox .phone,
    .track-thickbox .courier,
    .track-thickbox .tracking,
    .track-thickbox .city {
        width: 90%;
        float: left;
        border: 1px solid #eeeeee;
        padding: 10px;
        font-size: 14px;
    }

    .track-thickbox .status {
        width: 100%;
        float: left;
        text-align: center;
        font-size: 16px;
        margin: 15px 0px;     
        background-color: #f6e679;
        padding: 10px 0px;
    }


    .track-thickbox table {
      border-collapse: collapse;
      width: 100%;
    }

    .track-thickbox td, 
    .track-thickbox th {
      border: 1px solid #dddddd;
      text-align: left;
      padding: 8px;
      font-size: 14px !important;
    }

    .track-thickbox tr:nth-child(even) {
      background-color: #f9f9f9;
    }

    .dvs-back-btn {
        width: 125px;
        margin: 10px 0px;
        border: 1px solid #000000;
        border-radius: 2px;
        padding: 5px 10px;
        text-align: center;
        text-decoration: none;
        background-color: #eeeeee;
        color: #000000;
        font-size: 14px;        
    }
    .dvs-100 {
        width: 100%;
        position: relative;
        margin: 20px 0px;
        text-align: center;
    }
    </style>
    <?php
    endif;
}

add_action('wp_ajax_dvs_courier_copy_tracking', 'get_dvs_courier_copy_tracking');
function get_dvs_courier_copy_tracking() {
    $order_id = $_POST['dvs_order_id'];
    $order = new WC_Order( $order_id );
    $order_no = $order->get_order_number();
    $courier = $_POST['dvs_courier_list'];    
    $tracking = $_POST['dvs_courier_tracking'];

    echo '<div style="width:100%;position:relative;float:left">';
        echo '<h3>Customer Details</h3>';
        echo '<span><strong>Name: </strong>'.$order->get_billing_first_name(). ' ' .$order->get_billing_last_name().'</span><br>';
        echo '<span><strong>Phone: </strong>'.$order->get_billing_phone().'</span><br>';
        echo '<span><strong>Address: </strong>'.$order->get_billing_address_1(). ' ' .$order->get_billing_address_2().'</span><br>';
        echo '<span><strong>City: </strong>'.$order->get_billing_city().'</span>';
    echo '</div>';    

    echo '<div style="width:100%;position:relative;float:left">';
        echo '<h3>Tracking Details</h3>';
        echo '<span><strong>Courier: </strong>'.$courier.'</span><br>';
        echo '<span><strong>Tracking: </strong>'.$tracking.'</span><br><br>';
        $msg = sprintf( __("Hello %s %s, your order #%s has been shipped via %s and tracking number is %s - Get live tracking: %s", "woocommerce"),
            $order->get_billing_first_name(),
            $order->get_billing_last_name(),
            $order->get_order_number(),
            get_post_meta($order->id, '_dvs_courier_list', true),
            get_post_meta($order->id, '_dvs_courier_tracking', true),
            get_option('home').'/track'
        );
        echo $msg;
    echo '</div>';
    
        $custphone = $order->get_billing_phone();
        $custphone = trim($custphone);
        $custphone = str_replace(["O","o"],['0','0'],$custphone);
        $custphone = preg_replace("/[^0-9]+/", "", $custphone);
        $whatsappnum = WC()->countries->get_country_calling_code( $order->get_billing_country() ) . $custphone;
        $sendwhatsapp = 'https://api.whatsapp.com/send/?phone=' . $whatsappnum . '&text=' . urlencode($msg);

        echo '<a href="'.$sendwhatsapp.'" style="width: 50%;
        position: relative;
        float: left;
        text-align: center;
        margin: 20px 23%;
        padding: 10px;
        background-color: #22c04a;
        color: #ffffff;
        text-decoration: none;
        border-radius: 5px;" target="blank">Send WhatsApp</a>';
    echo '</div>';    
}

add_action('wp_ajax_dvs_courier_live_tracking', 'get_dvs_courier_live_tracking');
function get_dvs_courier_live_tracking() {
    $order_id = $_POST['dvs_order_id'];
    $courier = $_POST['dvs_courier_list'];    
    $tracking = $_POST['dvs_courier_tracking'];
    dvs_track_shipment($order_id, $courier, $tracking);
    exit();
}


add_filter( 'woocommerce_reports_get_order_report_data_args', 'wc_reports_get_order_custom_report_data_args' );
function wc_reports_get_order_custom_report_data_args( $args ) {
    $args['order_status'] = array( 'processing', 'completed', 'booked', 'shipped', 'refused', 'delivered' );
    return $args;
}