<?php
/**
 * Plugin Name: Devsol Universal Courier For Woocommerce
 * Plugin URI: https://devsol.pk
 * Description: Create bulk shipment booking in TCS, Leopards Courier, Trax, MNP, Call Courier, BlueEx, PostEx, Daewoo FastEx, Rider TPL, Insta World, Do Deliver, RGS Logitics, Oshi Courier, Rocket Courier, Ship NOC, AHL Courier and many more in Woocommerce. Get live tracking updates, print custom labels and share tracking via Email, SMS and WhatsApp ( For Support: 0323-4152099 )
 * Version: 6.3.0
 * Author: Devsol
 * Author URI: https://devsol.pk
 * Developer: Anas Iqbal Khan
 * Requires at least: 4.7
**/

/* WooCommerce CRUD ready */

if ( ! defined( 'ABSPATH' ) ) exit;
    
$couriers = [
    'all' => 'All',
    'tcs' => 'TCS',
    'lcs' => 'Leopards Courier',
    'trax' => 'Trax',
    'mnp' => 'MNP',
    'blx' => 'BlueEx',    
    'postex' => 'PostEx',    
    'ccs' => 'Call Courier',
    'daewoo' => 'Daewoo Courier',       
    'rider' => 'Rider',
    'insta' => 'Insta World',
    'dodeliver' => 'Do Deliver',
    'oshi' => 'Oshi Courier',     
    'zaaf' => 'Zaaf Courier',     
    'rocket' => 'Rocket Courier',
    'csn' => 'Couriers Next',
    'falcomail' => 'Falcomail',
    'noc' => 'Ship NOC',
    'ahl' => 'AHL Courier',
    'rgs' => 'RGS Logistics', 
    'covered' => 'Covered Logistics', 
    'acs' => 'Active Courier',
];

include_once('inc/dvs-tcs-settings.php');
include_once('inc/dvs-lcs-settings.php');
include_once('inc/dvs-trax-settings.php');
include_once('inc/dvs-mnp-settings.php');
include_once('inc/dvs-ccs-settings.php');
include_once('inc/dvs-blx-settings.php');
include_once('inc/dvs-daewoo-settings.php');
include_once('inc/dvs-postex-settings.php');
include_once('inc/dvs-ccx-settings.php');
include_once('inc/dvs-acs-settings.php');
include_once('inc/dvs-rider-settings.php');
include_once('inc/dvs-insta-settings.php');
include_once('inc/dvs-dodeliver-settings.php');
include_once('inc/dvs-falcomail-settings.php');
include_once('inc/dvs-noc-settings.php');
include_once('inc/dvs-ahl-settings.php');
include_once('inc/dvs-rocket-settings.php');
include_once('inc/dvs-covered-settings.php');
include_once('inc/dvs-oshi-settings.php');
include_once('inc/dvs-csn-settings.php');
include_once('inc/dvs-zaaf-settings.php');
include_once('inc/dvs-rgs-settings.php');
include_once('inc/dvs-ucp-homepage.php');
include_once('inc/dvs-ucp-functions.php');
include_once('inc/dvs-ucp-meta-box.php');
include_once('inc/dvs-ucp-status.php');
include_once('inc/dvs-ucp-profile.php');
include_once('inc/dvs-ucp-logs.php');
include_once('inc/dvs-ucp-logs-page.php');
include_once('inc/dvs-ucp-track.php');
include_once('inc/dvs-ucp-cancel.php');
include_once('inc/dvs-ucp-cron.php');
include_once('inc/dvs-ucp-finance.php');
include_once('inc/dvs-ucp-finance-bulk.php');
include_once('inc/dvs-ucp-analytics.php');
include_once('inc/dvs-ucp-report.php');

add_action('admin_menu', 'dvs_ct_menu', 994);
function dvs_ct_menu() {
    add_menu_page(
        'Courier Settings', 
        'Courier Settings', 
        'manage_options', 
        'dvs_courier_settings', 
        '', 
        'dashicons-admin-site-alt3');
    add_menu_page(
        'Courier Logs', 
        'Courier Logs', 
        'manage_woocommerce', 
        'dvs_ucp_all_logs', 
        '', 
        'dashicons-list-view');
    add_submenu_page( 
        'dvs_courier_settings', 
        'Introduction', 
        'Introduction',
        'manage_options', 
        'dvs_courier_settings', 
        'dvs_courier_api_page');                  
}

add_action('admin_menu', 'dvs_tcs_menu', 995);
function dvs_tcs_menu() {

    add_submenu_page( 
        'dvs_courier_settings', 
        'Shipper Settings', 
        'Shipper Settings',
        'manage_options', 
        'dvs_label_shipper', 
        'dvs_label_shipper_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'TCS Courier', 
        'TCS Courier',
        'manage_options', 
        'dvs_tcs_api', 
        'dvs_tcs_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Leopards Courier', 
        'Leopards Courier',
        'manage_options', 
        'dvs_lcs_api', 
        'dvs_lcs_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Trax Courier', 
        'Trax Courier',
        'manage_options', 
        'dvs_trax_api', 
        'dvs_trax_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'M&P Courier', 
        'M&P Courier',
        'manage_options', 
        'dvs_mnp_api', 
        'dvs_mnp_api_page'); 

    add_submenu_page( 
        'dvs_courier_settings', 
        'BlueEx Courier', 
        'BlueEx Courier',
        'manage_options', 
        'dvs_blx_api', 
        'dvs_blx_api_page');            

    add_submenu_page( 
        'dvs_courier_settings', 
        'PostEx Courier', 
        'PostEx Courier',
        'manage_options', 
        'dvs_postex_api', 
        'dvs_postex_api_page');    

    add_submenu_page( 
        'dvs_courier_settings', 
        'Call Courier', 
        'Call Courier',
        'manage_options', 
        'dvs_ccs_api', 
        'dvs_ccs_api_page'); 

    add_submenu_page( 
        'dvs_courier_settings', 
        'Daewoo Courier', 
        'Daewoo Courier',
        'manage_options', 
        'dvs_daewoo_api', 
        'dvs_daewoo_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Rider Courier', 
        'Rider Courier',
        'manage_options', 
        'dvs_rider_api', 
        'dvs_rider_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Insta World', 
        'Insta World',
        'manage_options', 
        'dvs_insta_api', 
        'dvs_insta_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Do Deliver', 
        'Do Deliver',
        'manage_options', 
        'dvs_dodeliver_api', 
        'dvs_dodeliver_api_page');           

    add_submenu_page( 
        'dvs_courier_settings', 
        'Oshi Courier', 
        'Oshi Courier',
        'manage_options', 
        'dvs_oshi_api', 
        'dvs_oshi_api_page');          

    add_submenu_page( 
        'dvs_courier_settings', 
        'Zaaf Courier', 
        'Zaaf Courier',
        'manage_options', 
        'dvs_zaaf_api', 
        'dvs_zaaf_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Couriers Next', 
        'Couriers Next',
        'manage_options', 
        'dvs_csn_api', 
        'dvs_csn_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Rocket Courier', 
        'Rocket Courier',
        'manage_options', 
        'dvs_rocket_api', 
        'dvs_rocket_api_page');  

    add_submenu_page( 
        'dvs_courier_settings', 
        'Falcomail', 
        'Falcomail',
        'manage_options', 
        'dvs_falcomail_api', 
        'dvs_falcomail_api_page');  

    add_submenu_page( 
        'dvs_courier_settings', 
        'Ship NOC', 
        'Ship NOC',
        'manage_options', 
        'dvs_noc_api', 
        'dvs_noc_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'AHL Courier', 
        'AHL Courier',
        'manage_options', 
        'dvs_ahl_api', 
        'dvs_ahl_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'RGS Logistics', 
        'RGS Logistics',
        'manage_options', 
        'dvs_rgs_api', 
        'dvs_rgs_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Covered Logistics', 
        'Covered Logistics',
        'manage_options', 
        'dvs_covered_api', 
        'dvs_covered_api_page');

    add_submenu_page( 
        'dvs_courier_settings', 
        'Active Courier', 
        'Active Courier',
        'manage_options', 
        'dvs_acs_api', 
        'dvs_acs_api_page');                              

    global $couriers;

    foreach ($couriers as $key => $name) {
        $check_couriers = get_option('dvs_'.$key.'_enable');
        
        if ($key == "all" || $check_couriers == 1) {
            add_submenu_page(
                'dvs_ucp_all_logs',
                $name,
                $name,
                'manage_woocommerce',
                "dvs_ucp_{$key}_logs",
                function() use($name, $key) {
                    dvs_ucp_common_logs_page($name, $key);
                }
            );
        }
    }    

}


add_action('admin_menu', 'dvs_ucp_analytics_menu', 996);
function dvs_ucp_analytics_menu() {   
    add_menu_page(
        'Courier Analytics', 
        'Courier Analytics', 
        'manage_woocommerce', 
        'dvs_courier_analytics', 
        'dvs_courier_analytics_page',
        'dashicons-chart-bar'
    );
    add_menu_page(
        'Courier Reports', 
        'Courier Reports', 
        'manage_woocommerce', 
        'dvs_courier_report', 
        'dvs_courier_report_page',
        'dashicons-calendar-alt'
    );   
}




add_action('admin_menu', 'dvs_finance_menu', 997);
function dvs_finance_menu() {   
    add_menu_page(
        'Courier Finance', 
        'Courier Finance', 
        'manage_options', 
        'dvs_courier_finance', 
        '',
        'dashicons-bank'
    );

    add_submenu_page( 
        'dvs_courier_finance', 
        'CSV Upload Records', 
        'CSV Upload Records',
        'manage_options', 
        'dvs_courier_finance', 
        'dvs_courier_finance_upload'
    );

    add_submenu_page( 
        'dvs_courier_finance', 
        'Bulk Upload Records', 
        'Bulk Upload Records',
        'manage_options', 
        'dvs_courier_finance_bulk', 
        'dvs_courier_finance_bulk'
    );

    add_submenu_page( 
        'dvs_courier_finance', 
        'Finance Logs', 
        'Finance Logs',
        'manage_options', 
        'dvs_courier_finance_logs', 
        'dvs_courier_finance_logs'
    );
}

// Add stylesheet
function devsol_tracking_scripts() {
	if(is_page( 17914 )) {
    	wp_enqueue_style( 'devsol-tracking', plugin_dir_url( __FILE__ ) . 'css/devsol-tracking.css' );
	}
}
add_action( 'wp_enqueue_scripts', 'devsol_tracking_scripts' );

// Replace default woocommerce template
function dvs_locate_template_tracking( $template, $template_name, $template_path ) {
    $basename = basename( $template );
    if( $basename == 'customer-invoice.php' ) {
    $template = trailingslashit( plugin_dir_path( __FILE__ ) ) . 'templates/emails/customer-invoice.php';
    }	
    if( $basename == 'tracking.php' ) {
    $template = trailingslashit( plugin_dir_path( __FILE__ ) ) . 'templates/order/tracking.php';
    }
    if( $basename == 'form-tracking.php' ) {
    $template = trailingslashit( plugin_dir_path( __FILE__ ) ) . 'templates/order/form-tracking.php';
    }                     
    return $template;
}
add_filter( 'woocommerce_locate_template', 'dvs_locate_template_tracking', 10, 3 );


register_activation_hook( __FILE__, 'dvs_activation_hook' );
function dvs_activation_hook() {
    update_option('dvs_url', 'https://ucp-woo.devsol.org');
    $dvs_ucp_cron_track_time = get_option( 'dvs_ucp_cron_track_time' );
    if(empty($dvs_ucp_cron_track_time)) {
        update_option('dvs_ucp_cron_track_time', '21600');
    }
    $dvs_ucp_courier_pagination = get_option( 'dvs_ucp_courier_pagination' );
    if(empty($dvs_ucp_courier_pagination)) {
        update_option('dvs_ucp_courier_pagination', '50');
    }
    if ( empty(get_option( 'dvs_ucp_display_average' )) ) {
        update_option( 'dvs_ucp_display_average', 1 );
    }    
}

// Create a custom tracking shortcode
add_shortcode( 'dvs_order_tracking', 'dvs_tracking_request' );
function dvs_tracking_request() {
    if ( is_null( WC()->cart ) ) {
        return;
    }
    $nonce_value = wc_get_var( $_REQUEST['woocommerce-order-tracking-nonce'], wc_get_var( $_REQUEST['_wpnonce'], '' ) );

    if ( isset( $_REQUEST['orderid'] ) && wp_verify_nonce( $nonce_value, 'woocommerce-order_tracking' ) ) {
        $order_id    = empty( $_REQUEST['orderid'] ) ? 0 : ltrim( wc_clean( wp_unslash( $_REQUEST['orderid'] ) ), '#' );
        $order_email = empty( $_REQUEST['order_email'] ) ? '' : sanitize_text_field( wp_unslash( $_REQUEST['order_email'] ) );
        $order_phone = empty( $_REQUEST['order_phone'] ) ? '' : sanitize_text_field( wp_unslash( $_REQUEST['order_phone'] ) );
        $order_tracking = empty( $_REQUEST['order_tracking'] ) ? '' : sanitize_text_field( wp_unslash( $_REQUEST['order_tracking'] ) );   
        $dvs_ucp_track_phone = get_option( 'dvs_ucp_track_phone' );

        if ($order_phone && $order_phone != "1122") {
            $order_phone = trim($order_phone);
            $order_phone = preg_replace("/[^0-9]+/", "", $order_phone);
            if (strpos($order_phone, '+92') === 0) {
                $order_phone = substr($order_phone, 1);
            } else if (strpos($order_phone, '92') === 0) {
                $order_phone = $order_phone;
            } else if (strpos($order_phone, '03') === 0) {
                $order_phone = substr_replace($order_phone, '923', 0, 2);
            } else if (strpos($order_phone, '3') === 0) {
                $order_phone = '92'.$order_phone;
            }
            $order_phone = substr($order_phone, 2);
            if($order_phone) {
                $check_zero = $order_phone[0];
                if($check_zero != 0) {
                    $order_phone = '0'.$order_phone;
                }
            }            
        }

        if ($order_tracking) {
            $order_tracking = trim($order_tracking);
            global $wpdb;

            // $sql_tracking = $wpdb->get_row( "SELECT * FROM `dvs_ucp_logs` WHERE `courier_tracking` = '{$order_tracking}'" );

            $get_post_id = $wpdb->get_var( $wpdb->prepare(
                "SELECT post_id
                 FROM {$wpdb->postmeta}
                 WHERE meta_key = %s
                   AND meta_value = %s",
                '_dvs_courier_tracking',
                $order_tracking
            ));


            if ($get_post_id) {
                $order_id = $get_post_id;
                $order = wc_get_order($order_id);
                if ( $order && $order->get_id() ) {
                    do_action( 'woocommerce_track_order', $order->get_id() );
                    wc_get_template(
                        'order/tracking.php',
                        array(
                            'order' => $order,
                        )
                    );
                    return;
                }
                else {
                    wc_print_notice( __( 'Sorry: Invalid tracking number. Please contact support.', 'woocommerce' ), 'error' );
                }
            }
            else {
                wc_print_notice( __( 'Sorry: Invalid tracking number. Please contact support.', 'woocommerce' ), 'error' );
            }
        }
        else if ( current_user_can( 'manage_options' ) ) {
            if ( ! $order_id ) {
                wc_print_notice( __( 'Error: Order number is required', 'woocommerce' ), 'error' );
            }
            else {
                $order = wc_get_order( apply_filters( 'woocommerce_shortcode_order_tracking_order_id', $order_id ) );
                if ( $order && $order->get_id() ) {
                    do_action( 'woocommerce_track_order', $order->get_id() );
                    wc_get_template(
                        'order/tracking.php',
                        array(
                            'order' => $order,
                        )
                    );
                    return;
                } else {
                    wc_print_notice( __( 'Sorry: Invalid order details. Please contact support.', 'woocommerce' ), 'error' );
                }
            }
        }
        else if($dvs_ucp_track_phone == 1) {
            if ( ! $order_id ) {
                wc_print_notice( __( 'Error: Order number is required', 'woocommerce' ), 'error' );
            } elseif ( ! $order_phone ) {
                wc_print_notice( __( 'Error: Mobile Number is required', 'woocommerce' ), 'error' );
            } else {
                $order = wc_get_order( apply_filters( 'woocommerce_shortcode_order_tracking_order_id', $order_id ) );
                if ($order_phone == '1122') {
                    do_action( 'woocommerce_track_order', $order->get_id() );
                    wc_get_template(
                        'order/tracking.php',
                        array(
                            'order' => $order,
                        )
                    );
                    return;                    
                }

                if($order) {
                    $billing_phone = trim($order->get_billing_phone());
                    $billing_phone = preg_replace("/[^0-9]+/", "", $billing_phone);
                    if (strpos($billing_phone, '+92') === 0) {
                        $billing_phone = substr($billing_phone, 1);
                    } else if (strpos($billing_phone, '92') === 0) {
                        $billing_phone = $billing_phone;
                    } else if (strpos($billing_phone, '03') === 0) {
                        $billing_phone = substr_replace($billing_phone, '923', 0, 2);
                    } else if (strpos($billing_phone, '3') === 0) {
                        $billing_phone = '92'.$billing_phone;
                    }
                    $billing_phone = substr($billing_phone, 2);
                    $check_zero = $billing_phone[0];
                    if($check_zero != 0) {
                        $billing_phone = '0'.$billing_phone;
                    }

                    if ( $order && $order->get_id() && $billing_phone === $order_phone ) {
                        do_action( 'woocommerce_track_order', $order->get_id() );
                        wc_get_template(
                            'order/tracking.php',
                            array(
                                'order' => $order,
                            )
                        );
                        return;
                    }
                    else {
                        wc_print_notice( __( 'Sorry: Invalid order details. Please contact support.', 'woocommerce' ), 'error' );
                    }
                }
                else {
                    wc_print_notice( __( 'Sorry: Invalid order details. Please contact support.', 'woocommerce' ), 'error' );
                }
            }
        }
        else {
            if ( ! $order_id ) {
                wc_print_notice( __( 'Error: Order number is required', 'woocommerce' ), 'error' );
            } elseif ( ! $order_email ) {
                wc_print_notice( __( 'Error: Email Address is required', 'woocommerce' ), 'error' );
            } else {
                $order = wc_get_order( apply_filters( 'woocommerce_shortcode_order_tracking_order_id', $order_id ) );
                if ($order_email == '1122') {
                    do_action( 'woocommerce_track_order', $order->get_id() );
                    wc_get_template(
                        'order/tracking.php',
                        array(
                            'order' => $order,
                        )
                    );
                    return;                    
                }
                if ( $order && $order->get_id() && strtolower( $order->get_billing_email() ) === strtolower( $order_email ) ) {
                    do_action( 'woocommerce_track_order', $order->get_id() );
                    wc_get_template(
                        'order/tracking.php',
                        array(
                            'order' => $order,
                        )
                    );
                    return;
                } else {
                    wc_print_notice( __( 'Sorry: Invalid order details. Please contact support.', 'woocommerce' ), 'error' );
                }
            }            
        }
    }
    wc_get_template( 'order/form-tracking.php' );

?>

<?php }

add_filter('plugin_action_links_' . plugin_basename( __FILE__ ), 'dvs_courier_plugin_settings_link');
function dvs_courier_plugin_settings_link($links) {
    $plugin_links = array(
        '<a href="' . admin_url( 'admin.php?page=dvs_courier_settings' ) . '">' . __( 'Settings', '' ) . '</a>',
        '<a href="https://devsol.pk/universal-courier-woocommerce/" target="_blank">' . __( 'Video Guides & Updates', '' ) . '</a>'
    );
    return array_merge($plugin_links, $links);
}

register_activation_hook(__FILE__, 'dvs_ucp_activated');
function dvs_ucp_activated() {
    $url = get_option( 'dvs_url' )."/woo/license.php";$dvs_data = array('email' => get_option('admin_email'),'city' => get_option('woocommerce_store_city'),
    );$dvs_data = json_encode($dvs_data);$output = wp_remote_post( $url, array('method'=> 'POST','sslverify' => false,'timeout'=> 30, 'body'=> $dvs_data ));
}


global $dvs_ucp_db_version;
$dvs_ucp_db_version = '1.1';

function dvs_ucp_create_table() {
    global $wpdb;
    global $dvs_ucp_db_version;

//    $table_name = $wpdb->prefix . 'dvs_ucp_logs';

    $table_name = 'dvs_ucp_logs';

    $charset_collate = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table_name (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `shop_url` varchar(255) NOT NULL,
      `courier_name` varchar(100) NOT NULL,
      `order_id` varchar(256) NOT NULL,
      `order_name` varchar(50) NOT NULL,
      `shipper_name` varchar(50) NOT NULL,
      `shipper_address` text NOT NULL,
      `shipper_phone` varchar(50) NOT NULL,
      `consignee_name` varchar(50) NOT NULL,
      `consignee_address` text NOT NULL,
      `consignee_phone` varchar(50) NOT NULL,
      `consignee_email` varchar(100) DEFAULT NULL,
      `courier_type` varchar(50) NOT NULL,
      `courier_service` varchar(50) NOT NULL,
      `courier_payment` varchar(50) NOT NULL,
      `courier_handling` varchar(50) NOT NULL,
      `courier_origin` varchar(100) NOT NULL,
      `courier_destination` varchar(100) NOT NULL,
      `courier_datetime` datetime NOT NULL,
      `shipped_datetime` datetime DEFAULT NULL,
      `received_datetime` datetime DEFAULT NULL,
      `order_type` varchar(100) NOT NULL,
      `order_amount` decimal(19,2) NOT NULL,
      `order_pieces` int(11) NOT NULL,
      `order_qty` int(11) NOT NULL,
      `order_remarks` varchar(256) NOT NULL,
      `order_products` text NOT NULL,
      `courier_tracking` varchar(100) NOT NULL,
      `order_weight` varchar(100) NOT NULL,
      `order_cost` decimal(10,2) DEFAULT '0.00',
      `order_total` decimal(10,2) DEFAULT '0.00',
      `courier_status` varchar(100) NOT NULL,
      `courier_delivery` varchar(255) NULL,
      `courier_finance` text NULL,
      PRIMARY KEY (`id`),
      KEY `shop_url` (`shop_url`),
      KEY `courier_name` (`courier_name`)
    ) $charset_collate;";

    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );
    add_option( 'dvs_ucp_db_version', $dvs_ucp_db_version );
}
register_activation_hook( __FILE__, 'dvs_ucp_create_table' );
