<?php

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

//register plugin field settings
add_action( 'admin_init', 'dvs_trax_plugin_settings' );
function dvs_trax_plugin_settings() {
	register_setting( 'dvs-trax-settings-group', 'dvs_trax_enable' );		
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_api' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_pickup' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_info' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_type' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_payment' );  
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_charges' ); 
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_box' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_item' );                
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_handling' );        
	register_setting( 'dvs-trax-settings-group', 'dvs_trax_consignee' );       
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_remarks' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_product' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_product_check' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_pieces_check' );     
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_sku_check' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_notes_check' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_weight_check' );
    register_setting( 'dvs-trax-settings-group', 'dvs_trax_cod_check' );                               
}


//Courier settings input fields
function dvs_trax_api_page() { ?>
<div class="wrap">
<form method="post" action="options.php">
    <?php 
	settings_fields( 'dvs-trax-settings-group' );
	do_settings_sections( 'dvs-trax-settings-group' );
    $dvs_trax_pickup = get_option('dvs_trax_pickup');
	$dvs_trax_info = get_option('dvs_trax_info');	
	$dvs_trax_type = get_option('dvs_trax_type');
	$dvs_trax_payment = get_option('dvs_trax_payment');
	$dvs_trax_charges = get_option('dvs_trax_charges');
	$dvs_trax_box = get_option('dvs_trax_box');	
	$dvs_trax_item = get_option('dvs_trax_item');				
	$dvs_trax_handling = get_option('dvs_trax_handling');
	$dvs_trax_consignee = get_option('dvs_trax_consignee');
 	?>
    <img src="<?php echo plugin_dir_url( __DIR__ ) . 'images/trax-label-logo.png'; ?>" height="50px">
    <h2>Trax Settings</h2>
    <table class="form-table">

        <tr>
        <th scope="row">Enable Trax API</th>
        <td>
	    <?php
	    echo '<input type="checkbox" name="dvs_trax_enable" value="1" ' . checked( 1, get_option( 'dvs_trax_enable' ), false ) . ' />';?>
        </td>
        </tr> 

        <tr>
        <th scope="row">API Key</th>
        <td><input class="regular-text" placeholder="" type="password" name="dvs_trax_api" value="<?php echo esc_attr( get_option('dvs_trax_api') ); ?>" required/></td>
        </tr>

        <?php 
        $get_dvs_trax_api = get_option('dvs_trax_api');

        if($get_dvs_trax_api) { 

            $curl = curl_init();
            curl_setopt_array($curl, array(
              CURLOPT_URL => 'https://sonic.pk/api/pickup_addresses',
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 10,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'GET',
              CURLOPT_HTTPHEADER => array(
                'Authorization: '.$get_dvs_trax_api
              ),
            ));
            $response = curl_exec($curl);
            curl_close($curl);
            $result = json_decode($response, true);
            
            if($result['status'] == '0') { ?>

                <tr>
                <th scope="row">Pickup Address</th>
                <td><select id="dvs_trax_pickup" name="dvs_trax_pickup" >
                    <?php
                    foreach ($result['pickup_addresses'] as $pickup) { ?>
                        <option value="<?php echo $pickup['id'] ?>" <?php selected($dvs_trax_pickup, $pickup['id']); ?>><?php echo $pickup['address'] ?></option>
                    <?php } ?></td>
                </select>
                </tr>

                <tr>
                <th scope="row">Shipper Info</th>
                <td>
                    <select id="dvs_trax_info" name="dvs_trax_info" required>
                    	<option value="1" <?php selected($dvs_trax_info,'1'); ?>>Show</option>
                    	<option value="0" <?php selected($dvs_trax_info,'0'); ?>>Hide</option>
                    </select>
                <td>        
                </tr>

                <tr>
                <th scope="row">Shipment Mode</th>
                <td>
                    <select>
                    	<option value="regular">Regular</option>
                    </select>
                <td>        
                </tr>            
         
                <tr>
                <th scope="row">Shipment Type</th>
                <td>
                    <select id="dvs_trax_type" name="dvs_trax_type" required>
                    	<option value="1" <?php selected($dvs_trax_type,'1'); ?>>Rush</option>
                    	<option value="2" <?php selected($dvs_trax_type,'2'); ?>>Saver Plus</option>            	
                    	<option value="3" <?php selected($dvs_trax_type,'3'); ?>>Swyft</option>
                    </select>
                <td>        
                </tr>


                <tr>
                <th scope="row">Payment Mode</th>
                <td>
                    <select id="dvs_trax_payment" name="dvs_trax_payment" required>
                    	<option value="1" <?php selected($dvs_trax_payment,'1'); ?>>COD</option>
                    	<option value="2" <?php selected($dvs_trax_payment,'2'); ?>>CCD</option>            	
                    	<option value="4" <?php selected($dvs_trax_payment,'4'); ?>>Prepaid</option>
                    </select>
                <td>        
                </tr>  

                <tr>
                <th scope="row">Charges Mode</th>
                <td>
                    <select id="dvs_trax_charges" name="dvs_trax_charges" required>
                    	<option value="4" <?php selected($dvs_trax_charges,'4'); ?>>Reimbursement (COD Account)</option>
                    	<option value="3" <?php selected($dvs_trax_charges,'3'); ?>>Invoice (Corporate)</option>
                    </select>
                <td>        
                </tr>

                <tr>
                <th scope="row">Allow Box Open</th>
                <td>
                    <select id="dvs_trax_box" name="dvs_trax_box" required>
                    	<option value="0" <?php selected($dvs_trax_box,'0'); ?>>No</option>            	
                    	<option value="1" <?php selected($dvs_trax_box,'1'); ?>>Yes</option>
                    </select>
                <td>        
                </tr>         


                <tr>
                <th scope="row">Item Type</th>
                <td>
                    <select id="dvs_trax_item" name="dvs_trax_item" required>
                    	<option value="1" <?php selected($dvs_trax_item,'1'); ?>>Apparel</option>
                    	<option value="2" <?php selected($dvs_trax_item,'2'); ?>>Automotive Parts</option>            	
                    	<option value="3" <?php selected($dvs_trax_item,'3'); ?>>Accessories</option>
                    	<option value="4" <?php selected($dvs_trax_item,'4'); ?>>Personal Electronics (Mobile Phones, Laptops, etc.)</option>
                    	<option value="5" <?php selected($dvs_trax_item,'5'); ?>>Electronics Accessories (Cases, Chargers, etc.)</option>
        				<option value="6" <?php selected($dvs_trax_item,'6'); ?>>Gadgets</option>
        				<option value="7" <?php selected($dvs_trax_item,'7'); ?>>Jewellery</option>
        				<option value="8" <?php selected($dvs_trax_item,'8'); ?>>Cosmetics</option>
        				<option value="9" <?php selected($dvs_trax_item,'9'); ?>>Stationery</option>
        				<option value="10" <?php selected($dvs_trax_item,'10'); ?>>Handicrafts</option>
        				<option value="11" <?php selected($dvs_trax_item,'11'); ?>>Home-made Items</option>
        				<option value="12" <?php selected($dvs_trax_item,'12'); ?>>Footwear</option>
        				<option value="13" <?php selected($dvs_trax_item,'13'); ?>>Watches</option>
        				<option value="14" <?php selected($dvs_trax_item,'14'); ?>>Leather Items</option>
        				<option value="15" <?php selected($dvs_trax_item,'15'); ?>>Organic and Health Products</option>
        				<option value="16" <?php selected($dvs_trax_item,'16'); ?>>Appliances and Consumer Electronics</option>
        				<option value="17" <?php selected($dvs_trax_item,'17'); ?>>Home Decor and Interior Items</option>
        				<option value="18" <?php selected($dvs_trax_item,'18'); ?>>Toys</option>
        				<option value="19" <?php selected($dvs_trax_item,'19'); ?>>Pet Supplies</option>
        				<option value="20" <?php selected($dvs_trax_item,'20'); ?>>Athletics and Fitness Items</option>
        				<option value="21" <?php selected($dvs_trax_item,'21'); ?>>Vouchers and Coupons</option>
        				<option value="22" <?php selected($dvs_trax_item,'22'); ?>>Marketplace</option>
        				<option value="23" <?php selected($dvs_trax_item,'23'); ?>>Documents and Letters</option>
        				<option value="24" <?php selected($dvs_trax_item,'24'); ?>>Other</option>
                    </select>
                <td>        
                </tr>                       

                <tr>
                <th scope="row">Shipment Handling</th>
                <td>
                    <select id="dvs_trax_handling" name="dvs_trax_handling" required>
                    	<option value="Yes" <?php selected($dvs_trax_handling,'Yes'); ?>>Fragile</option>
                    </select>
                <td>        
                </tr>        

                <tr>
                <th scope="row">Consginee Details</th>
                <td>
                    <select id="dvs_trax_consignee" name="dvs_trax_consignee" required>
                    <option value="Billing Details" <?php selected($dvs_trax_consignee,'Billing Details'); ?>>Billing Details</option>
                    <option value="Shipping Details" <?php selected($dvs_trax_consignee,'Shipping Details'); ?>>Shipping Details</option>
                    </select>
                <td>        
                </tr>

                <tr>
                <th scope="row">Default Remarks</th>
                <td><input class="regular-text" placeholder="" type="text" name="dvs_trax_remarks" value="<?php echo esc_attr( get_option('dvs_trax_remarks') ); ?>" required/></td>
                </tr>

                <tr>
                <th scope="row">Default Product</th>
                <td><input class="regular-text" placeholder="" type="text" name="dvs_trax_product" value="<?php echo esc_attr( get_option('dvs_trax_product') ); ?>" /></td>
                </tr>    

                <tr>
                <th scope="row">Print Item Name in Label</th>
                <td>
                <?php
                echo '<input type="checkbox" name="dvs_trax_product_check" value="1" ' . checked( 1, get_option( 'dvs_trax_product_check' ), false ) . ' />';?>
                </td>
                </tr>

                <tr>
                <th scope="row">Print SKU Name in Label</th>
                <td>
                <?php
                echo '<input type="checkbox" name="dvs_trax_sku_check" value="1" ' . checked( 1, get_option( 'dvs_trax_sku_check' ), false ) . ' />';?>
                </td>
                </tr>    

                <tr>
                <th scope="row">Print Order Notes in Remarks</th>
                <td>
                <?php
                echo '<input type="checkbox" name="dvs_trax_notes_check" value="1" ' . checked( 1, get_option( 'dvs_trax_notes_check' ), false ) . ' />';?>
                </td>
                </tr> 

                <tr>
                <th scope="row">Auto Calculate Weight</th>
                <td>
                <?php
                echo '<input type="checkbox" name="dvs_trax_weight_check" value="1" ' . checked( 1, get_option( 'dvs_trax_weight_check' ), false ) . ' />';?>
                </td>
                </tr>


                <tr>
                <th scope="row">Auto Calculate Pieces</th>
                <td>
                <?php
                echo '<input type="checkbox" name="dvs_trax_pieces_check" value="1" ' . checked( 1, get_option( 'dvs_trax_pieces_check' ), false ) . ' />';?>
                </td>
                </tr>           

                <tr>
                <th scope="row">Calculate Non-COD as Zero</th>
                <td>
                <?php
                echo '<input type="checkbox" name="dvs_trax_cod_check" value="1" ' . checked( 1, get_option( 'dvs_trax_cod_check' ), false ) . ' />';?>
                </td>
                </tr>

            <?php
            }
            else {
                echo '<div class="notice notice-error is-dismissible"><p>Error: Invalid API Key</p></div>';
            }
        }
        ?>                     

    </table>

    <?php 	
	submit_button('Submit'); 
	?>
</form>

<br>
<a href="https://www.youtube.com/watch?v=6PHVp51Q2GU" target="blank" class="woocommerce-Button button">Video: How to configure Trax Settings</a>
<br>
<br>
<a href="https://devsol.pk/contact/" target="blank" class="woocommerce-Button button">Get Support</a>
<br>
<br>
<a href="https://wa.me/9203234152099" target="blank" class="woocommerce-Button button">WhatsApp Support</a>

</div>

<?php 
}

function dvs_trax_orders_data($order_id) {

    $order = wc_get_order($order_id);

    foreach ($order->get_items() as $item_key => $item ) {
        $order_product = $item->get_product();
        $orders_items[] = array(
            'item_name' => $item['name'],
            'item_qty' => $item['qty'],
            'item_sku'    => $order_product ? $order_product->get_sku() : '',
            'item_weight' => $order_product ? $order_product->get_weight() : '',
            'item_status' => $order_product ? $order_product->get_status() : '',
        );
    }
    
    $orders_data = array(
        'status' => $order->get_meta('_dvs_courier_check'),
        'order_id' => $order->get_id(),
        'order_number' => $order->get_order_number(),
        'gateway' => $order->get_payment_method(),
        'amount' => $order->get_total(),
        'email' => $order->get_billing_email(),
        'notes' => $order->get_customer_note(),
        'billing_name' => $order->get_billing_first_name() . ' ' . $order->get_billing_last_name(),
        'billing_address' => $order->get_billing_address_1() . ' ' . $order->get_billing_address_2(),
        'billing_city' => $order->get_billing_city(),
        'billing_phone' => $order->get_billing_phone(),
        'shipping_name' => $order->get_shipping_first_name() . ' ' . $order->get_shipping_last_name(),
        'shipping_address' => $order->get_shipping_address_1() . ' ' . $order->get_shipping_address_2(),
        'shipping_city' => $order->get_shipping_city(),
        'shipping_phone' => get_post_meta($order->get_id(), '_shipping_phone', true),
        'orders_items' => $orders_items,
    );

    return $orders_data;
}



function dvs_trax_body_data($orders_data) {
    $response = [
        'orders' => $orders_data,
        'dvs_courier' => 'Trax',
        'dvs_slug' => 'trax',
        'dvs_type' => get_option( 'dvs_trax_type' ),
        'dvs_handling' => get_option( 'dvs_trax_handling' ),
        'dvs_consignee' => get_option( 'dvs_trax_consignee' ),
        'dvs_remarks' => get_option( 'dvs_trax_remarks' ),
        'dvs_product' => get_option( 'dvs_trax_product' ),
        'dvs_product_check' => get_option( 'dvs_trax_product_check' ),
        'dvs_sku_check' => get_option( 'dvs_trax_sku_check' ),
        'dvs_notes_check' => get_option( 'dvs_trax_notes_check' ),
        'dvs_weight_check' => get_option( 'dvs_trax_weight_check' ), 
        'dvs_pieces_check' => get_option( 'dvs_trax_pieces_check' ),
        'dvs_cod_check' => get_option( 'dvs_trax_cod_check' ),
    ];
    $body = json_encode($response, true);
    $url = get_option( 'dvs_url' ).'/woo/form.php';
    $output = wp_remote_post( $url, array('method'=> 'POST','sslverify' => false,'timeout'=> 300,'body'=> $body));
    if (is_wp_error($output)) {
        $error = $output->get_error_message();
        echo "Error: $error";
    }
    else {
        $json = $output['body'];
        echo $json;
    }
}


add_filter( 'bulk_actions-edit-shop_order', 'trax_bulk_actions',101 );
function trax_bulk_actions( $bulk_array ) {
    $dvs_trax_enable = get_option( 'dvs_trax_enable' );
    if ($dvs_trax_enable == 1 ) {
        $bulk_array['mark_trax_orders'] = 'Trax Bulk Booking';
    }
    return $bulk_array;
}


add_filter( 'handle_bulk_actions-edit-shop_order', 'dvs_trax_bulk_action_handler', 10, 4 );
function dvs_trax_bulk_action_handler( $redirect, $doaction, $object_ids ) {
    if ( $doaction !== 'mark_trax_orders' ) {
        return $redirect;
    }
    $orders_data = [];
    $orders_items = [];
    foreach( $object_ids as $order_id ) {
        $orders_data[] = dvs_trax_orders_data($order_id);

    }
    dvs_trax_body_data($orders_data);
}


add_action('woocommerce_order_actions', 'trax_single_order_action', 10, 1 );
function trax_single_order_action( $actions ) {
    $dvs_trax_enable = get_option( 'dvs_trax_enable' );
    if ($dvs_trax_enable == 1 ) {    
        if ( is_array( $actions ) ) {
            $actions['trax_action'] = __( 'Book at Trax' );
        }
    }
    return $actions;
}


add_action( 'woocommerce_order_action_trax_action', 'trax_single_order_booking' );
function trax_single_order_booking($order_id) {
    $orders_data = [];
    $orders_items = [];    
    $orders_data[] = dvs_trax_orders_data($order_id);
    dvs_trax_body_data($orders_data);
    die();
}


add_action( 'init', 'trax_submit_form' );
function trax_submit_form() {    
    if(!empty($_POST['dvs_courier']) && $_POST['dvs_courier'] == 'trax' ) {

        $orders = $_POST['order'];
        $trackings = [];
        $msgs = '';
        $count = 0;
        $uncount = 0;
        $actualcount = 0;       
        $allcount = 1;

        foreach($orders as $order) {

            if(!isset($order['check']))
            continue;

            $book_packet_array = array(
                'dvs_courier' => "TRAX",
                'dvs_trax_api' => get_option('dvs_trax_api'),               
                'dvs_trax_pickup'  =>  get_option('dvs_trax_pickup'),
                'dvs_trax_info'  =>  get_option('dvs_trax_info'),
                'dvs_trax_payment'  =>  get_option('dvs_trax_payment'),
                'dvs_trax_charges'  =>  get_option('dvs_trax_charges'),
                'dvs_trax_item'  =>  get_option('dvs_trax_item'),           
                'dvs_trax_box'  =>  get_option('dvs_trax_box'),
                'order' => $order,
            );

            $booking = json_encode($book_packet_array);

            $url = get_option( 'dvs_url' ).'/woo/upload.php';
            $output = wp_remote_post( $url, array('method'=> 'POST','sslverify' => false,'timeout'=> 300,'body'=> $booking));
            if ( is_wp_error( $output ) ) {
                $error = $output->get_error_message();
                echo "Error: $error";
            }
            else {
                $json = $output['body'];
                $response = json_decode($json,true);
            }

            $order_id = $order['order_id'];
            $order_number = $order['order_number'];  
            $current_order = $order;

            if($response['status'] == 0 && $response['message'] == "Shipment has been Booked!") {
                $order = new WC_Order($order_id);
                $trax_tracking = $response['tracking_number'];
                $msgs .= "<div style='background-color:#107f61; color:#ffffff; padding:5px 10px; border: 1px solid #107f61; border-radius: 5px; margin: 5px 0px';><strong>{$allcount}: </strong>Order # ".$order_number;
                $msgs .= "<span> [ Booked: ".$trax_tracking." ]</span></div>";
                $order->add_order_note("Order has been booked at Trax with Tracking # ".$trax_tracking);
                update_post_meta( $order->get_id(), '_dvs_courier_list', 'Trax');   
                update_post_meta( $order->get_id(), '_dvs_courier_tracking', $trax_tracking );
                update_post_meta( $order->get_id(), '_dvs_courier_check', 'Booked' );

                $dvs_courier_link = 'https://trax.pk/tracking/?tracking_number='.$tcs_tracking;
                update_post_meta( $order->get_id(), '_dvs_courier_link', $dvs_courier_link ); 

                $dvs_label_shipper_booked = get_option('dvs_label_shipper_booked');

                if($dvs_label_shipper_booked == 1) {
                    $order->update_status( 'wc-booked' );
                }

                // Add log to db
                dvs_ucp_logs($current_order, $trax_tracking, 'Trax');

                $trackings[] = $trax_tracking;
                $count++;
            }
            else {
                $msgs .= "<div style='background-color:#ff4e4e; color:#ffffff; padding:5px 10px; border: 1px solid #ff4e4e; border-radius: 5px; margin: 5px 0px';'><strong>{$allcount}: </strong>Order # ".$order_number;
                $msgs .= "<br><span> [ Error: ".$json." ]</span></div>";
                $uncount++;
            }
            $allcount++;
            $actualcount++;
        }   

        if($msgs!='') { ?>

        <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');

        h3 {
            text-align: center;
        }

        .dvs-booking-result {
            width: 600px;
            margin: 0 auto;
            font-family: 'Roboto', sans-serif;
            margin-top: 20px;
        }               

        .dvs-btn-back {
            float: right;
            margin: 10px 0px;
            border: 1px solid #107f61;
            border-radius: 5px;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            background-color: #ffffff;
            color: #107f61;
            font-size: 16px;        
        }

        .dvs-btn-print {
            float: left;
            margin: 10px 0px;
            border: 1px solid #107f61;
            border-radius: 5px;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            background-color: #107f61;
            color: #ffffff;
            font-size: 16px;        
        }   

        </style>

        <?php
            echo '<div class="dvs-booking-result">';?>
            <center>    
            <img src="<?php echo plugin_dir_url( __DIR__ ) . 'images/trax-label-logo.png'; ?>" height="50px">    
            <h3>Trax Booking Summary</h3>
            </center>
            <?php 
            echo "Booked Packets = {$count}";
            echo '<br/>';
            echo '<br/>';       
            echo "Un-Booked Packets = {$uncount}";
            echo '<br/>';
            echo '<br/>';
            echo $msgs;
            echo '<br/>';
            echo '<br/>';

            if($_SERVER['REQUEST_URI'] == '/wp-admin/post.php') {
                $btn_url = get_admin_url(null, 'post.php?post='.$order_id.'&action=edit');
            }
            else {
                $btn_url = get_admin_url(null, 'edit.php?post_type=shop_order');
            }
            $tracking_url = get_admin_url(null, 'edit.php?dvs_trackings=' . join(',', $trackings));

            $dvs_label_shipper_enable = get_option('dvs_label_shipper_enable');

            if ($dvs_label_shipper_enable == '1') {
                echo '<a href="'.$tracking_url.'" class="dvs-btn-print" target="blank">Print Label</a>';
            }

            echo '<a href="'.$btn_url.'" class="dvs-btn-back">Go Back</a>';
            echo '</div>';
        }

        $dvs_courier_total = get_option( 'dvs_courier_total' ) + $count;
        update_option('dvs_courier_total', $dvs_courier_total);

        $dvs_courier_trax = get_option( 'dvs_courier_trax' ) + $count ;
        update_option('dvs_courier_trax', $dvs_courier_trax);

        $url = get_option( 'dvs_url' )."/woo/count.php";
        $data_count = array(
            'dvs_courier' => 'TRAX',
            'count' => $actualcount,
            'booked' => $count,
            'unbooked' => $uncount,
        );
        $data_count = json_encode($data_count);
        $post = wp_remote_post( $url, array('method'=> 'POST','sslverify' => false,'timeout'=> 30, 'body'=> $data_count ));
        die();   
    }
}

