<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

function fernweh_remarks_modal_callback($js = FALSE) {
    if ($js) {

        ctools_include('modal');
        ctools_include('ajax');
        ctools_add_js('ajax-responder');

        $form_state = array(
            'title' => t('View Remark'),
            'ajax' => TRUE,
        );


        $output = ctools_modal_form_wrapper('ferhweh_remark_view_form', $form_state);

        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }

        print ajax_render($output);
        drupal_exit();
    } else {
        return drupal_get_form('ferhweh_remark_view_form');
    }
}

function ferhweh_remark_view_form($form, $form_state) {
    $type = arg(3) ? arg(3) : 0;
    $id = arg(4) ? arg(4) : 0;
    $node = node_load($id);
    if ($type == "payment") {
        $remark = isset($node->field_payment_detail[LANGUAGE_NONE][0]['value']) ? $node->field_payment_detail[LANGUAGE_NONE][0]['value'] : "";
    } else {
        $remark = isset($node->field_transaction_remarks[LANGUAGE_NONE][0]['value']) ? $node->field_transaction_remarks[LANGUAGE_NONE][0]['value'] : "";
    }

    if (empty($remark)) {
        $remark = '<div class="alert alert-warning text-center"> No remarks available</div>';
    }
    $form = array();
    $form['view_message']['#markup'] = '<p>' . $remark . '</p>';

//    $form['actions']['cancel'] = array(
//        '#prefix' => '<div class="popup-footer-wrapper">',
//        '#markup' => l(t('Close'), '#', array(
//                'attributes' => array(
//                    'class' => 'ctools-close-modal modal-cancel-btn'
//                ),
//                'external' => TRUE
//            )
//        )
//    );

    return $form;
}

function fernweh_order_delete_modal_callback($js = FALSE) {
    if ($js) {

        ctools_include('modal');
        ctools_include('ajax');
        ctools_add_js('ajax-responder');

        $form_state = array(
            'title' => t('Delete order'),
            'ajax' => TRUE,
        );


        $output = ctools_modal_form_wrapper('order_delete_form', $form_state);

        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }

        print ajax_render($output);
        drupal_exit();
    } else {
        return drupal_get_form('order_delete_form');
    }
}

function order_delete_form($form, $form_state) {
    $form = array();
    $order = commerce_order_load(arg(3));
    if(isset($order->status) and $order->status == 'canceled'){
        $form['delete_message']['#markup'] = '<h2>You cannot delete a cancelled order</h2>';
        $form['actions']['cancel'] = array(
            '#prefix' => '<div class="popup-footer-wrapper">',
            '#markup' => l(t('Close'), '#', array(
                'attributes' => array(
                    'class' => 'ctools-close-modal modal-cancel-btn'
                ),
                'external' => TRUE
                    )
            )
        );
    }else{
        $form['delete_message']['#markup'] = '<h2>Are you sure you want to Delete?</h2>';
        $form['id'] = array(
            '#type' => 'hidden',
            '#value' => arg(3),
        );

        $form['actions']['cancel'] = array(
            '#prefix' => '<div class="popup-footer-wrapper">',
            '#markup' => l(t('Cancel'), '#', array(
                'attributes' => array(
                    'class' => 'ctools-close-modal modal-cancel-btn'
                ),
                'external' => TRUE
                    )
            )
        );
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('Delete'),
            '#suffix' => '</div>'
        );
    }

    return $form;
}

function order_delete_form_submit(&$form, &$form_state) {

    $order = commerce_order_load($form_state['values']['id']);
    if (is_object($order)) {
        //logical delete
        $order->field_order_logical_delete[LANGUAGE_NONE][0]['value'] = 0;
        commerce_order_save($order);
        //JOSEPH
        // Step 1: Get node of type transaction with transaction type "Internal Cost" and unpublish that
        $transaction_internal_query = db_select('node', 'n');
        $transaction_internal_query->join('field_data_field_transaction_order_entity_r', 'oer', 'n.nid = oer.entity_id');
        $transaction_internal_query->join('field_data_field_transaction_types', 'tt', 'n.nid = tt.entity_id');
        $transaction_internal_query->join('field_data_field_transaction_flag', 'tf', 'n.nid = tf.entity_id');
        $transaction_internal_query->fields('n', array('nid'))
                ->condition('n.type', 'service_transaction', '=')
                ->condition('tt.field_transaction_types_value', array(2,5), 'IN')
                ->condition('tf.field_transaction_flag_value', 0, '=')
                ->condition('oer.field_transaction_order_entity_r_target_id', $form_state['values']['id'], '=');

        $transaction_internal_result = $transaction_internal_query->execute();
        while ($transaction_internal_record = $transaction_internal_result->fetchAssoc()) {
            if (isset($transaction_internal_record['nid'])) {
                $internalNode = node_load($transaction_internal_record['nid']);
                $internalNode->status = 0;
                node_save($internalNode);
                // Step 2: Find out if there is any reference to transaction card? If yes, then deduct the same amount from the card balance
                if (isset($internalNode->field_transaction_card_reference[LANGUAGE_NONE][0]['tid'])) {
                    $ccTermObj = taxonomy_term_load($internalNode->field_transaction_card_reference[LANGUAGE_NONE][0]['tid']);
                    if ($ccTermObj) {
                        $transactionCharge = $internalNode->field_transaction_charge[LANGUAGE_NONE][0]['value'];
                        $existingCCAmount = $ccTermObj->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'];
                        $ccTermObj->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'] = $existingCCAmount - $transactionCharge;
                        taxonomy_term_save($ccTermObj);
                    }
                }
            }
        }
        // Step 3: Get node of type transaction with transaction type "Service Cost" and un-publish that
        $transaction_service_query = db_select('node', 'n');
        $transaction_service_query->join('field_data_field_transaction_order_entity_r', 'oer', 'n.nid = oer.entity_id');
        $transaction_service_query->join('field_data_field_transaction_types', 'tt', 'n.nid = tt.entity_id');
        $transaction_service_query->join('field_data_field_transaction_flag', 'tf', 'n.nid = tf.entity_id');
        $transaction_service_query->fields('n', array('nid'))
                ->condition('n.type', 'service_transaction', '=')
                ->condition('tt.field_transaction_types_value', array(1,2), 'IN') //@TODO: CHECK FOR OTHER TYPES
                ->condition('tf.field_transaction_flag_value', 1, '=')
                ->condition('oer.field_transaction_order_entity_r_target_id', $form_state['values']['id'], '=');

        $transaction_service_result = $transaction_service_query->execute();

        $orderAccountNid = 0;
        while ($transaction_service_record = $transaction_service_result->fetchAssoc()) {
            if (isset($transaction_service_record['nid'])) {
                $serviceNode = node_load($transaction_service_record['nid']);
                $serviceNode->status = 0;
                node_save($serviceNode);
                
                // Step 4: Reduce the same amount from associated account outstanding balance
                if (isset($serviceNode->field_transaction_account_entity[LANGUAGE_NONE][0]['target_id'])) {
                    
                    $accountNodeObj = node_load($serviceNode->field_transaction_account_entity[LANGUAGE_NONE][0]['target_id']);
                    if ($accountNodeObj) {
                        $orderAccountNid = $accountNodeObj->nid;
                        $transactionCharge = $serviceNode->field_transaction_charge[LANGUAGE_NONE][0]['value'];
                        $existingOutstandingBalance = $accountNodeObj->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'];
                        $accountNodeObj->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] = $existingOutstandingBalance - $transactionCharge;
                        // JOSEPH
                        db_update('node')->fields(array('changed' => time()))->condition('nid', $accountNodeObj->nid, '=')->execute();
                        // JOSEPH
                        node_save($accountNodeObj);
                    }
                }
            }
        }
        
        // Step 5: Get node of type payment which is created against an order
        $order_payment_query = db_select('node', 'n');
        $order_payment_query->join('field_data_field_payment_entity_reference', 'per', 'n.nid = per.entity_id');
        $order_payment_query->join('field_data_field_payment_account_entity_ref', 'aer', 'n.nid = aer.entity_id');
        $order_payment_query->fields('n', array('nid'))
                ->condition('n.type', 'payment', '=')
                ->condition('aer.field_payment_account_entity_ref_target_id', $orderAccountNid , '=')
                ->condition('per.field_payment_entity_reference_target_id', $form_state['values']['id'], '=');

        $order_payment_result = $order_payment_query->execute();
        
        while ($order_payment_record = $order_payment_result->fetchAssoc()) {
            
            if(isset($order_payment_record['nid'])) {
                $paymentNodeObj = node_load($order_payment_record['nid']);    
                
                if($paymentNodeObj) {
                    $paymentNodeObj->status = 0;
                    node_save($paymentNodeObj);
                }
            }
        }
        
        
        $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
        drupal_set_message(t('Order information deleted successfully.'));
    } else {
        drupal_set_message(t('Some error occurred while deleting order.', 'error'));
    }
    $form_state['ajax_commands'][] = ctools_ajax_command_redirect('orders', 1000);
}

function fernweh_order_modify_modal_callback($js = FALSE) {
    if ($js) {

        ctools_include('modal');
        ctools_include('ajax');
        ctools_add_js('ajax-responder');

        $form_state = array(
            'title' => t('Modify order'),
            'ajax' => TRUE,
        );


        $output = ctools_modal_form_wrapper('order_modify_form', $form_state);

        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }

        print ajax_render($output);
        drupal_exit();
    } else {
        return drupal_get_form('order_modify_form');
    }
}

function order_modify_form($form, $form_state) { 
    module_load_include('module', 'fernweh_alter', 'fernweh_alter');
    $product_id = fernweh_get_account_id(arg(3), true);
    $product = commerce_product_load($product_id);
    //var_dump(drupal_get_form('commerce_product_ui_product_form'));exit;
    //drupal_set_message('<pre>' . print_r($form_state, 1) . '</pre>', 'error');
    $service_type = $product->field_lead_service_type[LANGUAGE_NONE][0]['value'];
    if ($service_type == "airport_transfer") {
        $service_type_label = "Tour / Transfer";
    } else {
        $service_type_label = ucwords($service_type);
    }
    $form = array();
    $form['product_id'] = array(
        '#type' => 'hidden',
        '#value' => is_numeric($product_id) ? $product_id : $form_state['input']['product_id'],
    );
    if (!in_array($service_type, array('airport_transfer', 'miscellaneous'))) {

        $from_title = "From";
        if ($service_type == "hotel") {
            $from_title = "Hotel Name";
        } elseif ($service_type == "insurance") {
            $from_title = "Sector";
        }

        $form['service'] ['sector_from'] = array(
            '#title' => $from_title,
            '#type' => 'textfield',
            '#default_value' => isset($product->field_lead_service_flight_from[LANGUAGE_NONE][0]['value']) ? $product->field_lead_service_flight_from[LANGUAGE_NONE][0]['value'] : '',
            '#prefix' => '<div class="order-lead-service-form"><div class="service_heading"><h3>' . t('Services-' . $service_type_label) . '</h3></div><div class="order_service_inner_wrapper">',
        );

        if ($service_type != "hotel" && $service_type != "insurance") {
            $form['service'] ['sector_to'] = array(
                '#title' => t('To'),
                '#type' => 'textfield',
                '#default_value' => isset($product->field_lead_service_flight_to[LANGUAGE_NONE][0]['value']) ? $product->field_lead_service_flight_to[LANGUAGE_NONE][0]['value'] : '',
            );
        }
        $form['service'] ['travel_date'] = array(
            '#title' => ($service_type == "hotel") ? t('Checkin Date') : t('Travel Date'),
            '#date_format' => 'd M Y',
            '#type' => 'date_popup',
            '#default_value' => isset($product->field_lead_ser_flight_traveldate[LANGUAGE_NONE][0]['value']) ? $product->field_lead_ser_flight_traveldate[LANGUAGE_NONE][0]['value'] : '',
        );
        if ($service_type == "hotel") {
            $form['service'] ['checkout_date'] = array(
                '#title' => t('Checkout Date'),
                '#date_format' => 'd M Y',
                '#type' => 'date_popup',
                '#default_value' => isset($product->field_lead_service_checkout_date[LANGUAGE_NONE][0]['value']) ? $product->field_lead_service_checkout_date[LANGUAGE_NONE][0]['value'] : '',
            );
        }
    } else {
        $form['service'] ['travel_date'] = array(
            '#title' => t('Travel Date'),
            '#date_format' => 'd M Y',
            '#type' => 'date_popup',
            '#default_value' => isset($product->field_lead_ser_flight_traveldate[LANGUAGE_NONE][0]['value']) ? $product->field_lead_ser_flight_traveldate[LANGUAGE_NONE][0]['value'] : '',
            '#prefix' => '<div class="order-lead-service-form"><div class="service_heading"><h3>' . t('Services-' . $service_type_label) . '</h3></div><div class="order_service_inner_wrapper">',
        );

        $form['service'] ['free_text'] = array(
            '#title' => t('Free Text'),
            '#type' => 'textarea',
            '#default_value' => isset($product->field_lead_free_text[LANGUAGE_NONE][0]['value']) ? $product->field_lead_free_text[LANGUAGE_NONE][0]['value'] : '',
            '#resizable' => false,
            '#attributes' => array('style' => 'resize: none;border: 1px solid #ddd;width: 316px;'),
        );
    }
    if ($service_type != "insurance") {
        $form['service'] ['pnr'] = array(
            '#title' => ($service_type != "hotel") ? t('PNR') : t("Bill NO"),
            '#type' => 'textfield',
            '#default_value' => isset($product->field_lead_service_flight_pnr[LANGUAGE_NONE][0]['value']) ? $product->field_lead_service_flight_pnr[LANGUAGE_NONE][0]['value'] : '',
        );
    }

    $form['service'] ['modify_charge'] = array(
        '#title' => t('Service Modify Charge <br> (Additional charge)'),
        '#type' => 'textfield',
        '#attributes' => array('class' => array('cost-inr')),
        '#required' => TRUE,
    );
    $form['service'] ['modify_internal_charge'] = array(
        '#title' => t('Internal Modify Cost <br> (Additional Cost)'),
        '#type' => 'textfield',
        '#attributes' => array('class' => array('cost-inr')),
        '#required' => TRUE,
    );


    // ==== Code to display existing attachment ====
    $existingAttachments = '<ul>';
    foreach ($product->field_lead_service_flight_attche[LANGUAGE_NONE] as $key => $value) {
        $existingAttachments .= '<li data-fid="' . $value['fid'] . '">';
        $existingAttachments .= theme_file_link(array('file' => (object) $value));
        $existingAttachments .= l(t('Remove'), '#', array('attributes' => array('class' => array('order-remove-attachment'))));
        $existingAttachments .= '</li>';
    }
    $existingAttachments .= '</ul>';

    if (count($product->field_lead_service_flight_attche[LANGUAGE_NONE]) > 0) {
        $form['lead_service']['existing_attachments'] = array(
            '#type' => 'item',
            '#title' => t('Attachments'),
            '#markup' => $existingAttachments,
        );
    }

    $form['lead_service']['todelete_attachments'] = array('#type' => 'hidden', '#value' => '');

    // ==== Code to display existing attachment ====
    // ==== Code to add new attachment ==== (For now make it to 10)
    for ($i = 0; $i < 10; $i ++) {
        $form['lead_service']['add_attachment_' . $i] = array(
            '#title' => t('Add new attachment'),
            '#title_display' => 'invisible',
            '#type' => 'managed_file',
            '#upload_location' => 'public://leads',
            '#upload_validators' => array(
                'file_validate_extensions' => array('gif png jpg jpeg txt doc docx xls odt ods pdf'),
            ),
            '#attributes' => array('class' => array('order-attachment-' . $i))
        );
        if ($i > 0) {
            $form['lead_service']['add_attachment_' . $i]['#attributes'] = array('class' => array('element-hidden', 'order-attachment-' . $i));
            $form['lead_service']['add_more_attachment_' . $i] = array(
                '#markup' => l(t('Add More'), '#', array('attributes' => array('data-next' => ($i + 1), 'class' => array('attachment-addmore-btn', 'element-hidden')))),
            );
        } else {
            $form['lead_service']['add_more_attachment_' . $i] = array(
                '#markup' => l(t('Add More'), '#', array('attributes' => array('data-next' => ($i + 1), 'class' => array('attachment-addmore-btn')))),
            );
        }

        // ==== Code to add new attachment ==== (For now make it to 10)
    }


    $form['service'] ['transaction_remarks'] = array(
        '#title' => t('Remarks'),
        '#type' => 'textarea',
        '#suffix' => '</div></div>',
    );

    $form['actions']['cancel'] = array(
        '#prefix' => '<div class="popup-footer-wrapper">',
        '#markup' => l(t('Cancel'), '#', array(
            'attributes' => array(
                'class' => 'ctools-close-modal modal-cancel-btn'
            ),
            'external' => TRUE
                )
        )
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
        '#suffix' => '</div>'
    );
    return $form;
}

function order_modify_form_submit(&$form, &$form_state) {
    $product_id = $form_state['values']['product_id'];

    if ($product_id) {

        // ===================== Modification in Lead Entity ====================//
        $product = commerce_product_load($product_id);

        // Handle delete case
        $todeleteAttachment = explode(',', $form_state['input']['todelete_attachments']);

        $refinedAttachment = array();
        // Remove the delete file asociation from Lead
        foreach ($product->field_lead_service_flight_attche[LANGUAGE_NONE] as $key => $value) {
            if (!in_array($value['fid'], $todeleteAttachment)) { // Means we have to retain attachment
                $refinedAttachment[] = $value;
            }
        }
        $product->field_lead_service_flight_attche[LANGUAGE_NONE] = $refinedAttachment;

        // Now add the new attachment (if Any)
        for ($i = 0; $i < 10; $i++) {
            $fid = $form_state['values']['add_attachment_' . $i];
            if ($fid > 0) {
                $fileObj = file_load($fid);
                $fileArray = array(
                    'fid' => $fileObj->fid,
                    'uid' => $fileObj->uid,
                    'filename' => $fileObj->filename,
                    'uri' => $fileObj->uri,
                    'filemime' => $fileObj->filemime,
                    'filesize' => $fileObj->filesize,
                    'status' => $fileObj->status,
                    'timestamp' => $fileObj->timestamp,
                    'display' => 1,
                    'rdf_mapping' => array(),
                );
                $product->field_lead_service_flight_attche[LANGUAGE_NONE][] = $fileArray;
            }
        }

        $cost = $product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value'] + $form_state['values']['modify_charge'];

        $product->field_lead_service_flight_from[LANGUAGE_NONE][0]['value'] = $form_state['values']['sector_from'];
        $product->field_lead_service_flight_to[LANGUAGE_NONE][0]['value'] = $form_state['values']['sector_to'];
        $product->field_lead_ser_flight_traveldate[LANGUAGE_NONE][0]['value'] = $form_state['values']['travel_date']; // change to travel date

        if (isset($form_state['values']['checkout_date'])) {
            $product->field_lead_service_checkout_date[LANGUAGE_NONE][0]['value'] = $form_state['values']['checkout_date']; // Set Checkout Date
        }

        $product->field_lead_service_flight_pnr[LANGUAGE_NONE][0]['value'] = $form_state['values']['pnr'];
        $product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value'] = $cost;

        commerce_product_save($product);

        // Update Outstanding balance
        $account_id = $product->field_lead_account[LANGUAGE_NONE][0]['target_id'];
        $account = node_load($account_id);
        $credit_amount = $form_state['values']['modify_charge'];
        if (!empty($credit_amount) && is_numeric($credit_amount)) {
            // If amount is making from account page
            $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] = $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] + $credit_amount;
            // JOSEPH
            db_update('node')->fields(array('changed' => time()))->condition('nid', $account->nid, '=')->execute();
// JOSEPH            
// update node with new values
            field_attach_update('node', $account);
        }
        // Finally delete the not associated files
        if (count($todeleteAttachment) > 0) {
            foreach ($todeleteAttachment as $fileIndex => $fileId) {
                $fileObj = file_load($fileId);
                if (is_object($fileObj)) {
                    file_delete($fileObj);
                }
            }
        }



        // ===================== Modification in Order Entity ====================//
        $id = arg(3);
        $order = commerce_order_load($id);
        //internal purchase cost
        $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] = $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] + $form_state['values']['modify_internal_charge'];
        //service cost
        $order->field_order_service_cost[LANGUAGE_NONE][0]["value"] = $cost;
        $card_id = $order->field_order_select_card[LANGUAGE_NONE][0]['tid'];
        $order->status = "pending";
        commerce_order_save($order);
        drupal_set_message('Order is modified.');
        //-------------------------------------service transaction node creation---------------------------------------------------
         if ($form_state['values']['modify_charge'] >= 0 && $form_state['values']['modify_internal_charge'] >= 0) {
//        if (!empty($form_state['values']['modify_charge']) && !empty($form_state['values']['modify_internal_charge'])) {
            for ($i = 0; $i < 2; $i++) {
                $title = ($i == 0) ? 'Service' : 'Internal';
                $modify_charge = ($i == 0) ? $form_state['values']['modify_charge'] : $form_state['values']['modify_internal_charge'];
                $flag = ($i == 0) ? 1 : 0; //0 is internal and 1 is service flag
                $node = new stdClass();
                $node->type = 'service_transaction';
                node_object_prepare($node);
                $node->title = $title . ' modified transaction for order id ' . arg(3);
                $node->status = 1;
                $node->promote = 0;
                $node->comment = 0;
                $node->language = LANGUAGE_NONE;
                
                $node->field_transaction_types[$node->language][0]['value'] = 2; // 2 is for modification charge id               
                $node->field_transaction_charge[$node->language][0]['value'] = $modify_charge;
                $node->field_transaction_remarks[$node->language][0]['value'] = $form_state['values']['transaction_remarks'];
                $node->field_transaction_order_entity_r[$node->language][0]['target_id'] = arg(3);
                $node->field_transaction_account_entity[$node->language][0]['target_id'] = fernweh_get_account_id($id);
                $node->field_transaction_flag[$node->language][0]['value'] = $flag;
                if ($flag == 0 && is_numeric($card_id)) { // Internal card reference
                    //$node->field_transaction_card_reference[$node->language][0]['tid'] = !empty($card_id) ? $card_id : NULL;
                    $node->field_transaction_card_reference[$node->language][0]['tid'] = $card_id;
                }
                $node = node_submit($node);
                node_save($node);
            }
            //drupal_set_message('New Transaction node created');
            //-----------------------------------service transaction node creation----------------------------------------------------------
            if ($flag == 0) {
                // Update Card Outstanding balance
                $card_id = !empty($card_id) ? $card_id : NULL;
                if (!empty($card_id)) {
                    $card = taxonomy_term_load($card_id);
                    $credit_amount = $modify_charge;
                    if (!empty($credit_amount) && is_numeric($credit_amount)) {
                        // If amount is making from account page
                        $card->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'] = $card->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'] + $credit_amount;
                        // update node with new values
                        field_attach_update('taxonomy_term', $card);
                    }
                }
            }
        } else {
            drupal_set_message(t('Some error occurred while deleting order.', 'error'));
        }
        $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
        $form_state['ajax_commands'][] = ctools_ajax_command_redirect('order/' . arg(3) . '/details', 1000);
    }
}

function fernweh_order_cancel_modal_callback($js = FALSE) {
    if ($js) {

        ctools_include('modal');
        ctools_include('ajax');
        ctools_add_js('ajax-responder');

        $form_state = array(
            'title' => t('Cancel Order'),
            'ajax' => TRUE,
        );


        $output = ctools_modal_form_wrapper('order_cancel_form', $form_state);

        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }

        print ajax_render($output);
        drupal_exit();
    } else {
        return drupal_get_form('order_cancel_form');
    }
}

/**
 * Cancel Order Popup Form
 * @param type $form
 * @param type $form_state
 * @return type
 */
function order_cancel_form($form, $form_state) { 
    $order = commerce_order_load(arg(3));
    $card_id = null;
    if (is_object($order) && isset($order->field_order_select_card[LANGUAGE_NONE][0]['tid'])) {
        $card_id = $order->field_order_select_card[LANGUAGE_NONE][0]['tid'];
    }

    $form = array();
    $form['service'] ['cancel_charge'] = array(
        '#title' => t('Enter Applicable Cancel Charges To Client'),
        '#type' => 'textfield',
        '#prefix' => '<div class= cancel-order> ',
        '#required' => TRUE
    );
    $form['service'] ['cancel_internal_charge'] = array(
        '#title' => t('Enter Internal Refund Amount'),
        '#type' => 'textfield',
        '#required' => TRUE
    );
    if ($card_id != null) {
        $form['service'] ['card_refund_status'] = array(
            '#title' => t('Credit Card Refund Status'),
            '#type' => 'select',
            '#options' => array(
                'pending' => t('Pending'),
                'complete' => t('Complete'),
            ),
            '#required' => TRUE,
            '#suffix' => '<br/>',
        );
    }
    $form['service'] ['transaction_remarks'] = array(
        '#title' => t('Remarks'),
        '#type' => 'textarea',
        '#suffix' => '</div></div>',
    );

    $form['actions']['cancel'] = array(
        '#prefix' => '<div class="popup-footer-wrapper">',
        '#markup' => l(t('Cancel'), '#', array(
            'attributes' => array(
                'class' => 'ctools-close-modal modal-cancel-btn'
            ),
            'external' => TRUE
                )
        )
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Save'),
        '#suffix' => '</div> </div>'
    );
    return $form;
}

function order_cancel_form_submit(&$form, &$form_state) {
    $product_id = fernweh_get_account_id(arg(3), true);

    $cost = $form_state['values']['cancel_charge'];
    //order update
    $id = arg(3);
    $order_id = $id;
    $order = commerce_order_load($id);

    // Update Outstanding balance
    $account_id = fernweh_get_account_id($id);
    $account = node_load($account_id);
    $card_id = $order->field_order_select_card[LANGUAGE_NONE][0]['tid'];
    //   $credit_amount = $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] - $form_state['values']['cancel_internal_charge'];
//    if(!empty($credit_amount) && is_numeric($credit_amount)){
//        // If amount is making from account page
//        $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] = $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] + $credit_amount;
//        // update node with new values
//        field_attach_update('node', $account);
//    }
    //internal field for purchase
    $original_service_cost = $order->field_order_service_cost[LANGUAGE_NONE][0]['value']; 
    $internal_refund_amount = $form_state['values']['cancel_internal_charge']; 
    $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] = $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] - $internal_refund_amount;
    $order->field_order_service_cost[LANGUAGE_NONE][0]['value'] = $cost;

    commerce_order_status_update($order, $name = 'canceled');
    commerce_order_save($order);
    $product = commerce_product_load($product_id);
    $original_service_flight_cost = $product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value'];
    $product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value'] = $cost;
    commerce_product_save($product);

    //-------------------------------------service transaction node creation---------------------------------------------------
    if (isset($form_state['values']['cancel_charge']) && is_numeric($form_state['values']['cancel_charge'])) {
        //for ($i = 1; $i < 3; $i++) {
        for ($i = 1; $i <= 4; $i++) { // 1,2 - Service Tx, 3,4 - Internal Tx 
            $node = new stdClass();
            $node->type = 'service_transaction';
            node_object_prepare($node);
            $node->status = 1;
            $node->promote = 0;
            $node->comment = 0;
            $node->language = LANGUAGE_NONE;
            if ($i == 1 || $i == 2) {
                $title = ($i == 1) ? 'Service order canceled for order id ' . arg(3) : 'Service order Refund for order id ' . arg(3);
                $type = ($i == 1) ? 4 : 3;
                $flag = 1;
                $charge = $cost;

                $service_ob = $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'];
                $credit_amount = $charge;
                if (!empty($credit_amount) && is_numeric($credit_amount)) {
                    if ($i == 1) { // Service cancel 
                        $service_ob = (float) $service_ob + (float) $credit_amount;
                    } elseif ($i == 2) {
                        //$credit_amount = (float)$original_service_cost - $cost;
                        $service_ob = (float) $service_ob - (float) $original_service_cost;                   
                        //$charge = (float) $original_service_cost;
                        $charge = (float) $original_service_cost - $cost; //ADDED BY JOSEPH
                        // ---- Generate Payment type transaction for refund + payment already done ----/
                        $already_paid_amount = fernweh_get_order_paid_amount($order_id);
                        if ($already_paid_amount > $cost) { 
                            $payment_node = new stdClass();
                            $payment_node->type = 'payment';
                            node_object_prepare($payment_node);
                            $payment_node->title = 'Payment Refund from Order ID ' . $order_id;
                            $payment_node->status = 1;
                            $payment_node->promote = 0;
                            $payment_node->comment = 0;
                            $payment_node->language = LANGUAGE_NONE;
                            $payment_node->field_payment_date[LANGUAGE_NONE][0] = array(
                                'value' => date('Y-m-d H:i:s', strtotime('now')),
                                'timezone' => 'UTC',
                                'timezone_db' => 'UTC',
                            );
                            $payment_node->field_payment_type[LANGUAGE_NONE][0]['value'] = 2;
                            $payment_node->field_payment_mode[LANGUAGE_NONE][0]['value'] = NULL;
                            $payment_node->field_payment_amount_paid[LANGUAGE_NONE][0]['value'] = $already_paid_amount - (float) $cost;
                            $payment_node->field_payment_entity_reference[LANGUAGE_NONE][0]['target_id'] = $order_id;
                            $payment_node->field_payment_account_entity_ref[LANGUAGE_NONE][0]['target_id'] = $account_id;
                            $payment_node->field_payment_status[LANGUAGE_NONE][0]['value'] = "complete";
                            $payment_node = node_submit($payment_node);
                            node_save($payment_node);
                        }

                        // ------- Payment type end -----------------/
                        $account->field_account_available_amount[LANGUAGE_NONE][0]['value'] = $account->field_account_available_amount[LANGUAGE_NONE][0]['value'] + $already_paid_amount;
                    }
                    $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] = $service_ob;
                    // JOSEPH
                    db_update('node')->fields(array('changed' => time()))->condition('nid', $account->nid, '=')->execute();
                    // JOSEPH
                    field_attach_update('node', $account);
                }
                $node->field_transaction_account_entity[$node->language][0]['target_id'] = $account_id;
            } else {
                $title = ($i == 3) ? 'Internal order canceled for order id ' . arg(3) : 'Internal order Refund for order id ' . arg(3);
                $type = ($i == 3) ? 4 : 3;
                $flag = 0;
                $cancel_charge = $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'];
                $charge = ($i == 3) ? $cancel_charge : $internal_refund_amount;
                if (!empty($card_id)) {
                    $node->field_transaction_card_reference[$node->language][0]['tid'] = $card_id;
                    // Type: 3- Refund, 4 - Cancel
                    $card = taxonomy_term_load($card_id);
                    $card_ob = $card->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'];
                    $tx_credit_amount = (float) $card_ob;
                    if ($type == 4) { // Cancel
                        $tx_credit_amount = $tx_credit_amount; // + (float)$charge;
                    } elseif ($type == 3) { // Refund
                        $tx_credit_amount = $tx_credit_amount - (float) $charge;
                    }
                    if ($form_state['values']['card_refund_status'] == 'complete') {
                        $card->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'] = $tx_credit_amount;
                        field_attach_update('taxonomy_term', $card);
                    }
                }
            }
            //var_dump($form_state['values']['cancel_internal_charge']);
            $node->title = $title;
            $node->field_transaction_types[$node->language][0]['value'] = $type;
            $node->field_transaction_charge[$node->language][0]['value'] = $charge; 
            $node->field_transaction_order_entity_r[$node->language][0]['target_id'] = arg(3);
            $node->field_transaction_remarks[$node->language][0]['value'] = $form_state['values']['transaction_remarks'];
            $node->field_transaction_flag[$node->language][0]['value'] = $flag;
            if (isset($form_state['values']['card_refund_status'])) {
                $node->field_transaction_status[$node->language][0]['value'] = $form_state['values']['card_refund_status'];
            }
            $node = node_submit($node);
            node_save($node);
            //drupal_set_message('New Transaction node created');
        } 
    }
    //-----------------------------------service transaction node creation----------------------------------------------------------
    else {
        drupal_set_message('Some error occurred while deleting order.', 'error');
    }
    $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
    $form_state['ajax_commands'][] = ctools_ajax_command_redirect('order/' . arg(3) . '/details', 1000);
}

/**
 * //================== ORDER - SERVICE TRANSACTION =================/
 * Delete and edit service transaction modal
 */
function fernweh_transaction_edit_modal_callback($js = FALSE, $nodeId) {
    if ($js) {
        ctools_include('node.pages', 'node', '');
        ctools_include('modal');
        ctools_include('ajax');

        // Create a blank node object here. You can also set values for your custom fields here as well.
        $node = node_load($nodeId);

        $form_state = array(
            'title' => t('Edit Transaction'),
            'ajax' => TRUE,
        );

        $form_state['build_info']['args'] = array($node);

        $output = ctools_modal_form_wrapper('transaction_edit_node_form', $form_state);

        if (!empty($form_state['executed'])) {
            $output = array();
            // Close the modal
            $output[] = ctools_modal_command_dismiss();
            $output[] = ctools_ajax_command_reload();
        }

        print ajax_render($output);
        drupal_exit();
    } else {
        return drupal_get_form('transaction_edit_node_form');
    }
}

// Generate transaction edit node form with single field
function transaction_edit_node_form() {
    $form = array();
    $tx_id = is_numeric(arg(3)) ? arg(3) : NULL;
    $order_id = is_numeric(arg(6)) ? arg(6) : NULL;

    $order = commerce_order_load($order_id);
    if (is_object($order) && $order->status === "canceled") { // If order is not canceled then only allow modification
        $form['tx_modify_message']['#markup'] = '<div class="alert alert-warning"><strong>Sorry!</strong> Order is cancelled, so you can not modify this transaction.</div>';
        return $form;
    }

    // Processing edit form
    $transaction = node_load($tx_id);
    if (is_object($transaction)) {
        $tx_original_amount = isset($transaction->field_transaction_charge[LANGUAGE_NONE][0]['value']) ? $transaction->field_transaction_charge[LANGUAGE_NONE][0]['value'] : 0;
        $form['transaction_amount'] = array(
            '#title' => t('Amount'),
            '#type' => 'textfield',
            '#prefix' => '<div class="tx-form-wapper">',
            '#default_value' => $tx_original_amount
        );
        $form['field_tx_order_id'] = array(// Create order id field to retain order id
            '#type' => 'hidden',
            '#title' => t(''),
            '#value' => $order_id
        );
        $form['field_tx_original_amount'] = array(// Create order id field to retain order id
            '#type' => 'hidden',
            '#title' => t(''),
            '#value' => $tx_original_amount
        );
        $form['actions']['cancel'] = array(
            '#prefix' => '<div class="popup-footer-wrapper">',
            '#markup' => l(t('Cancel'), '#', array(
                'attributes' => array(
                    'class' => 'ctools-close-modal modal-cancel-btn'
                ),
                'external' => TRUE
                    )
            )
        );
        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => t('save'),
            '#suffix' => '</div></div>'
        );
    }

    return $form;
}

// Custom transaction edit from submit
function transaction_edit_node_form_submit(&$form, &$form_state, $form_id) {
    $tx_id = is_numeric(arg(3)) ? arg(3) : NULL;
    if ($tx_id && isset($form['transaction_amount']['#value']) && is_numeric($form['transaction_amount']['#value'])) {

        // Form values
        $tx_new_amount = $form['transaction_amount']['#value'];
        $tx_org_amount = isset($form['field_tx_original_amount']['#value']) ? $form['field_tx_original_amount']['#value'] : 0;
        $order_id = isset($form['field_tx_order_id']['#value']) ? $form['field_tx_order_id']['#value'] : 0;
        $order = commerce_order_load($order_id);
        if (is_object($order) && $order->status !== "canceled") { // If order is not canceled then only allow modification
            // Amount change
            $amount_change = $tx_new_amount - $tx_org_amount; //(+ve = Increased amount, -ve = Reduce)
            // Update transaction
            $transaction = node_load($tx_id);
            if (is_object($transaction)) {
                $tx_amount = isset($transaction->field_transaction_charge[LANGUAGE_NONE][0]['value']) ? $transaction->field_transaction_charge[LANGUAGE_NONE][0]['value'] : 0;
                $transaction->field_transaction_charge[LANGUAGE_NONE][0]['value'] = $tx_amount + $amount_change;
                field_attach_update('node', $transaction);

                // If service transaction type is refund then don't update service cost or lead flight cost
                $tx_type = ($transaction->field_transaction_types[LANGUAGE_NONE][0]['value']) ? $transaction->field_transaction_types[LANGUAGE_NONE][0]['value'] : NULL;
                // Transaction parent is service or internal
                // 0 - internal, 1 - service
                $tx_flag = ($transaction->field_transaction_flag[LANGUAGE_NONE][0]['value']) ? $transaction->field_transaction_flag[LANGUAGE_NONE][0]['value'] : NULL;

                if ($tx_type != 3) { // 3 - transaction type refund
                    if ($tx_flag == 1) { // 1 - Service
                        // Update order service cost
                        if (is_object($order) && isset($order->field_order_service_cost)) {
                            //service field for purchase
                            $service_cost = ($order->field_order_service_cost[LANGUAGE_NONE][0]['value']) ? $order->field_order_service_cost[LANGUAGE_NONE][0]['value'] : 0;
                            $order->field_order_service_cost[LANGUAGE_NONE][0]['value'] = $service_cost + $amount_change;
                            if (function_exists(_change_order_status)) {
                                $order = _change_order_status($order);
                            }
                            commerce_order_save($order);

                            // Update Outstanding balance
                            $account_id = fernweh_get_account_id($order_id);
                            $account = node_load($account_id);
                            $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] = $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] + $amount_change;
                            // JOSEPH
                            db_update('node')->fields(array('changed' => time()))->condition('nid', $account->nid, '=')->execute();
// JOSEPH                            
// update node with new values
                            field_attach_update('node', $account);
                        }

                        // Update lead service flight cost
                        $product_id = fernweh_get_account_id($order_id, true);
                        $product = commerce_product_load($product_id);
                        if (is_object($product) && isset($product->field_lead_service_flight_cost)) {
                            $service_flight_cost = ($product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value']) ? $product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value'] : 0;
                            $product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value'] = $service_flight_cost + $amount_change;
                            commerce_product_save($product);
                        }
                    } elseif ($tx_flag == 0) { // 0 - Internal
                        if (is_object($order) && isset($order->field_order_purchase_cost)) {
                            //internal field for purchase
                            $purchase_cost = ($order->field_order_purchase_cost[LANGUAGE_NONE][0]['value']) ? $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] : 0;
                            //print_r($purchase_cost); exit;
                            $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] = $purchase_cost + $amount_change;
                            //changing the order status
                            commerce_order_save($order);


                            // Update Card Outstanding balance
                            $card_id = $order->field_order_select_card[LANGUAGE_NONE][0]['tid'];
                            if (!empty($card_id)) {
                                $card = taxonomy_term_load($card_id);
                                $credit_amount = $amount_change;
                                if (!empty($credit_amount) && is_numeric($credit_amount)) {
                                    // If amount is making from account page
                                    $card->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'] = $card->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'] + $credit_amount;
                                    // update node with new values
                                    field_attach_update('taxonomy_term', $card);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

// Custom transaction delete model
function fernweh_transaction_delete_modal_callback($js = FALSE, $nodeId) {

    if ($js) {
        ctools_include('ajax');
        ctools_include('modal');
        ctools_add_js('ajax-responder');

        $form_state = array(
            'ajax' => TRUE,
            'title' => t('Delete Transaction'),
        );

        $output = ctools_modal_form_wrapper('transaction_delete_form', $form_state);

        if (!empty($form_state['ajax_commands'])) {
            $output = $form_state['ajax_commands'];
        }

        print ajax_render($output);
        drupal_exit();
    } else {
        return drupal_get_form('transaction_delete_form');
    }
}

// Custom transaction delete form
function transaction_delete_form($form, $form_state) {

    $form = array();
    $tx_id = is_numeric(arg(3)) ? arg(3) : 0;
    $transaction = node_load($tx_id);
    $order_id = ($transaction->field_transaction_order_entity_r[LANGUAGE_NONE][0]['target_id']) ? $transaction->field_transaction_order_entity_r[LANGUAGE_NONE][0]['target_id'] : 0;

    $order = commerce_order_load($order_id);
    if (is_object($order) && $order->status === "canceled") { // If order is not canceled then only allow modification
        $form['tx_modify_message']['#markup'] = '<div class="alert alert-warning"><strong>Sorry!</strong> Order is cancelled, so you can not delete this transaction.</div>';
        return $form;
    }


    // Process delete form
    $form['delete_message']['#markup'] = '<h2>Are you sure you want to Delete?</h2>';
    $form['id'] = array(
        '#type' => 'hidden',
        '#value' => $tx_id,
    );

    $form['actions']['cancel'] = array(
        '#prefix' => '<div class="popup-footer-wrapper">',
        '#markup' => l(t('Cancel'), '#', array(
            'attributes' => array(
                'class' => 'ctools-close-modal modal-cancel-btn'
            ),
            'external' => TRUE
                )
        )
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Delete'),
        '#suffix' => '</div>'
    );
    return $form;
}

// Custom transaction delete form submit
function transaction_delete_form_submit(&$form, &$form_state) {
    $transaction = node_load($form_state['values']['id']);
    if (is_object($transaction)) {
        $tx_type = ($transaction->field_transaction_types[LANGUAGE_NONE][0]['value']) ? $transaction->field_transaction_types[LANGUAGE_NONE][0]['value'] : 0;
        $tx_amount = ($transaction->field_transaction_charge[LANGUAGE_NONE][0]['value']) ? $transaction->field_transaction_charge[LANGUAGE_NONE][0]['value'] : 0;

        if ($tx_type == 2) { // 2- transaction type is modified
            $order_id = ($transaction->field_transaction_order_entity_r[LANGUAGE_NONE][0]['target_id']) ? $transaction->field_transaction_order_entity_r[LANGUAGE_NONE][0]['target_id'] : 0;
            // Handle internal transactions delete action
            $order = commerce_order_load($order_id);
            // 0 - internal, 1 - service
            $tx_flag = ($transaction->field_transaction_flag[LANGUAGE_NONE][0]['value']) ? $transaction->field_transaction_flag[LANGUAGE_NONE][0]['value'] : NULL;

            if ($tx_flag == 1) { // 1 - Service
                // Update order service cost
                if (is_object($order) && isset($order->field_order_service_cost)) {
                    //internal field for purchase
                    $service_cost = ($order->field_order_service_cost[LANGUAGE_NONE][0]['value']) ? $order->field_order_service_cost[LANGUAGE_NONE][0]['value'] : 0;
                    $order->field_order_service_cost[LANGUAGE_NONE][0]['value'] = $service_cost - $tx_amount;

                    //changing the order status
                    commerce_order_save($order);
                    // Update Outstanding balance
                    $account_id = fernweh_get_account_id($order_id);
                    $account = node_load($account_id);
                    $credit_amount = $tx_amount;
                    if (!empty($credit_amount) && is_numeric($credit_amount)) {
                        // If amount is making from account page
                        $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] = $account->field_account_outstanding_bal[LANGUAGE_NONE][0]['value'] - $credit_amount;
                        // JOSEPH
                        db_update('node')->fields(array('changed' => time()))->condition('nid', $account->nid, '=')->execute();
// JOSEPH                        
// update node with new values
                        field_attach_update('node', $account);
                    }
                }

                // Update lead service flight cost
                $product_id = fernweh_get_account_id($order_id, true);
                $product = commerce_product_load($product_id);
                if (is_object($product) && isset($product->field_lead_service_flight_cost)) {
                    $service_flight_cost = ($product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value']) ? $product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value'] : 0;
                    $product->field_lead_service_flight_cost[LANGUAGE_NONE][0]['value'] = $service_flight_cost - $tx_amount;
                    commerce_product_save($product);
                }
            } elseif ($tx_flag == 0) { // 0 - Internal
                if (is_object($order) && isset($order->field_order_purchase_cost)) {
                    //internal field for purchase
                    $purchase_cost = ($order->field_order_purchase_cost[LANGUAGE_NONE][0]['value']) ? $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] : 0;
                    $order->field_order_purchase_cost[LANGUAGE_NONE][0]['value'] = $purchase_cost - $tx_amount;
                    //changing the order status
                    commerce_order_save($order);
                }
            }
            // Delete transaction
            node_delete($transaction->nid);
            $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
            drupal_set_message(t('Transaction deleted successfully.'));
        } elseif ($tx_type == 5) { // Internal cost
            $order_id = ($transaction->field_transaction_order_entity_r[LANGUAGE_NONE][0]['target_id']) ? $transaction->field_transaction_order_entity_r[LANGUAGE_NONE][0]['target_id'] : 0;
            // Handle internal transactions delete action
            $order = commerce_order_load($order_id);

            // Update Card Outstanding balance
            $card_id = $order->field_order_select_card[LANGUAGE_NONE][0]['tid'];

            if (!empty($card_id)) {
                $card = taxonomy_term_load($card_id);
                $credit_amount = $tx_amount;
                if (!empty($credit_amount) && is_numeric($credit_amount)) {
                    // If amount is making from account page
                    $card->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'] = $card->field_card_outstanding_balance[LANGUAGE_NONE][0]['value'] - $credit_amount;
                    // update node with new values
                    field_attach_update('taxonomy_term', $card);
                }
            }
            // Delete transaction
            node_delete($transaction->nid);
            $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
            drupal_set_message(t('Transaction deleted successfully.'));
        }
    } else {
        drupal_set_message(t('Some error occurred while deleting transaction.', 'error'));
    }
    $form_state['ajax_commands'][] = ctools_ajax_command_reload();
}

?>
