<?php

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

//register plugin field settings
add_action( 'admin_init', 'dvs_tranzo_plugin_settings' );
function dvs_tranzo_plugin_settings() {
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_enable' );	
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_token' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_storeid' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_pickup' );  
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_return' );    
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_type' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_handling' );        
	register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_consignee' );       
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_remarks' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_product' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_product_check' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_pieces_check' );     
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_sku_check' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_notes_check' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_weight_check' );
    register_setting( 'dvs-tranzo-settings-group', 'dvs_tranzo_cod_check' );                             
}

//Courier settings input fields
function dvs_tranzo_api_page() { ?>
<div class="wrap">
<form method="post" action="options.php">
    <?php 
	settings_fields( 'dvs-tranzo-settings-group' );
	do_settings_sections( 'dvs-tranzo-settings-group' ); 
	$dvs_tranzo_type = get_option('dvs_tranzo_type');
	$dvs_tranzo_handling = get_option('dvs_tranzo_handling');
	$dvs_tranzo_consignee = get_option('dvs_tranzo_consignee');
    $dvs_tranzo_token = get_option('dvs_tranzo_token');
    $dvs_tranzo_pickup = get_option('dvs_tranzo_pickup');
    $dvs_tranzo_return = get_option('dvs_tranzo_return');
    $dvs_tranzo_storeid = get_option('dvs_tranzo_storeid');
 	?>
    <img src="<?php echo plugin_dir_url( __DIR__ ) . 'images/tranzo-label-logo.png'; ?>" height="50px">
    <h2>Tranzo Settings</h2>
    <table class="form-table">

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

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

    <?php

    if (!empty($dvs_tranzo_token)) {

       $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://api-integration.tranzo.pk/api/custom/v1/get-locations/',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_HTTPHEADER => array('api-token: '.$dvs_tranzo_token),
        ));
        $pickup_response = curl_exec($curl);
        curl_close($curl);
        $pickup_result = json_decode($pickup_response, true);
        
        if(isset($pickup_result[0]['id'])) {

            // Fetch Stores
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api-integration.tranzo.pk/api/custom/v1/get-stores/',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('api-token: '.$dvs_tranzo_token),
            ));
            $tranzo_stores = curl_exec($curl);
            curl_close($curl);
            $tranzo_stores = json_decode($tranzo_stores, true);

            // Fetch Shipment Types
            $curl = curl_init();
            curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://api-integration.tranzo.pk/api/custom/v1/get-shipment-types/',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => array('api-token: '.$dvs_tranzo_token),
            ));
            $tranzo_types = curl_exec($curl);
            curl_close($curl);
            $tranzo_types = json_decode($tranzo_types, true);
        ?> 
        <tr>
        <th scope="row">Pickup Address</th>
        <td>
            <select id="dvs_tranzo_pickup" name="dvs_tranzo_pickup" >
                <option value="">Select Pickup Address</option>
                <?php foreach ($pickup_result as $pickup): ?>
                <?php if ($pickup['is_active'] && $pickup['is_pickup']): ?>
                    <option value="<?= $pickup['location_code'] ?>" <?= ($pickup['location_code'] == $dvs_tranzo_pickup) ? 'selected' : '' ?>>
                    <?= $pickup['location_address'] . ' ' . $pickup['city'] ?>
                    </option>
                <?php endif; ?>
                <?php endforeach; ?>
            </select>    
        </td>
        </tr>

        <tr>
        <th scope="row">Return Address</th>
        <td>
            <select id="dvs_tranzo_return" name="dvs_tranzo_return" >
                <option value="">Select Return Address</option>
                <?php foreach ($pickup_result as $pickup): ?>
                <?php if ($pickup['is_active'] && $pickup['is_return']): ?>
                    <option value="<?= $pickup['location_code'] ?>" <?= ($pickup['location_code'] == $dvs_tranzo_return) ? 'selected' : '' ?>>
                    <?= $pickup['location_address'] . ' ' . $pickup['city'] ?>
                    </option>
                <?php endif; ?>
                <?php endforeach; ?>
            </select>    
        </td>
        </tr>

        <tr>
        <th scope="row">Store ID</th>
        <td>
            <select id="dvs_tranzo_storeid" name="dvs_tranzo_storeid" >
                <option value="">Select Store ID</option>
                <?php foreach ($tranzo_stores as $store): ?>
                <option value="<?= $store['store_id'] ?>" <?= ($store['store_id'] == $dvs_tranzo_storeid) ? 'selected' : '' ?>>
                    <?= $store['store_name'] . ' ' . $store['city'] ?>
                </option>
                <?php endforeach; ?>
            </select>    
        </td>
        </tr>


        <tr>
        <th scope="row">Shipment Type</th>
        <td>
            <select id="dvs_tranzo_type" name="dvs_tranzo_type" >
                <option value="">Select Shipment Type</option>
                <?php foreach ($tranzo_types as $type): ?>
                <option value="<?= $type['id'] ?>" <?= ($type['id'] == $dvs_tranzo_type) ? 'selected' : '' ?>>
                    <?= $type['ds_shipment_type'] ?>
                </option>
                <?php endforeach; ?>
            </select>
        <td>        
        </tr>

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

            <tr>
            <th scope="row">Consginee Details</th>
            <td>
                <select id="dvs_tranzo_consignee" name="dvs_tranzo_consignee" required>
                <option value="Billing Details" <?php selected($dvs_tranzo_consignee,'Billing Details'); ?>>Billing Details</option>
                <option value="Shipping Details" <?php selected($dvs_tranzo_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_tranzo_remarks" value="<?php echo esc_attr( get_option('dvs_tranzo_remarks') ); ?>" required /></td>
            </tr>

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

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

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

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

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

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

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

            <?php
                }
                else {
                    echo '<div class="notice notice-error is-dismissible"><p>Error: Invalid API Token. Please contact support: support@tranzo.pk</p><hr>'.$pickup_response.'</div>';
                }
            }
            ?>
    </table>

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

<br>
<a href="https://www.loom.com/share/d7111ed6d2a14eba880af91f588954e0" target="blank" class="woocommerce-Button button">Video: How to configure Tranzo 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/923234152099" target="blank" class="woocommerce-Button button">WhatsApp Support</a>

</div>

<?php 
}


function dvs_tranzo_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_tranzo_body_data($orders_data) {
    $response = [
        'orders' => $orders_data,
        'dvs_courier' => 'Tranzo',
        'dvs_slug' => 'tranzo',
		'dvs_tranzo_token' => get_option('dvs_tranzo_token'),
        'dvs_type' => get_option( 'dvs_tranzo_type' ),
        'dvs_handling' => get_option( 'dvs_tranzo_handling' ),
        'dvs_consignee' => get_option( 'dvs_tranzo_consignee' ),
        'dvs_remarks' => get_option( 'dvs_tranzo_remarks' ),
        'dvs_product' => get_option( 'dvs_tranzo_product' ),
        'dvs_product_check' => get_option( 'dvs_tranzo_product_check' ),
        'dvs_sku_check' => get_option( 'dvs_tranzo_sku_check' ),
        'dvs_notes_check' => get_option( 'dvs_tranzo_notes_check' ),
        'dvs_weight_check' => get_option( 'dvs_tranzo_weight_check' ), 
        'dvs_pieces_check' => get_option( 'dvs_tranzo_pieces_check' ),
        'dvs_cod_check' => get_option( 'dvs_tranzo_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', 'tranzo_bulk_actions',101 );
function tranzo_bulk_actions( $bulk_array ) {
    $dvs_tranzo_enable = get_option( 'dvs_tranzo_enable' );
    if ($dvs_tranzo_enable == 1 ) {
        $bulk_array['mark_tranzo_orders'] = 'Tranzo Bulk Booking';
    }
    return $bulk_array;
}


add_filter( 'handle_bulk_actions-edit-shop_order', 'dvs_tranzo_bulk_action_handler', 9999, 4 );
function dvs_tranzo_bulk_action_handler( $redirect, $doaction, $object_ids ) {
	if ( $doaction !== 'mark_tranzo_orders' ) {
	    return $redirect;
	}
    $orders_data = [];
    $orders_items = [];
	foreach( $object_ids as $order_id ) {
        $orders_data[] = dvs_tranzo_orders_data($order_id);

    }
    dvs_tranzo_body_data($orders_data);
}


add_action('woocommerce_order_actions', 'tranzo_single_order_action', 10, 1 );
function tranzo_single_order_action( $actions ) {
    $dvs_tranzo_enable = get_option( 'dvs_tranzo_enable' );
    if ($dvs_tranzo_enable == 1 ) {    
        if ( is_array( $actions ) ) {
            $actions['tranzo_action'] = __( 'Book at Tranzo' );
        }
    }
    return $actions;
}


add_action( 'woocommerce_order_action_tranzo_action', 'tranzo_single_order_booking' );
function tranzo_single_order_booking($order_id) {
    $orders_data = [];
    $orders_items = [];    
    $orders_data[] = dvs_tranzo_orders_data($order_id);
    dvs_tranzo_body_data($orders_data);
    die();
}


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

        $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' => "TRANZO",
                'dvs_tranzo_token' => get_option('dvs_tranzo_token'),
                'dvs_tranzo_pickup' => get_option('dvs_tranzo_pickup'),
                'dvs_tranzo_return' => get_option('dvs_tranzo_return'),
                'dvs_tranzo_storeid' => get_option('dvs_tranzo_storeid'),
                '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(isset($response['tracking_number'])) {
                $order = new WC_Order($order_id);
                $tranzo_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: ".$tranzo_tracking." ]</span></div>";
                $order->add_order_note("Order has been booked at Tranzo with Tracking # ".$tranzo_tracking);
                update_post_meta( $order->get_id(), '_dvs_courier_list', 'Tranzo');   
                update_post_meta( $order->get_id(), '_dvs_courier_tracking', $tranzo_tracking );
                update_post_meta( $order->get_id(), '_dvs_courier_check', 'Booked' );

                $dvs_courier_link = 'https://tranzo.pk/track-order?tn='.$tranzo_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, $tranzo_tracking, 'Tranzo');

                $trackings[] = $tranzo_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/tranzo-label-logo.png'; ?>" height="50px">    
            <h3>Tranzo 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_tranzo = get_option( 'dvs_courier_tranzo' ) + $count ;
        update_option('dvs_courier_tranzo', $dvs_courier_tranzo);

        $url = get_option( 'dvs_url' )."/woo/count.php";
        $data_count = array(
            'dvs_courier' => 'POSTEX',
            '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();   
    }
}

