$versions{'order_paypal_api.pl'} = '06.6.00.0000';

#######################################################################
#
# AgoraCart and all associated files, except where noted, are
# Copyright 2001 to Present jointly by K-Factor Technologies, Inc.
# and by C E Mayo (aka Mister Ed) at AgoraCart.com & K-Factor.net
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This copyright notice may not be removed or altered in any way.
#
#######################################################################

#
#
# Contains the order form and processing subroutines/functions for
# the paypal express API.
#
#

########################################################################
#                  api_cart_table_info Subroutine
########################################################################
#
# Needed a way to get the information without printing out results to the screen
#
# The job of api_cart_table_info is to replace display_cart_table for those processes
# that do not need to dispaly cart tables but still need the information, such as an API call.
#The subroutine takes one argument (or none), the reason that the cart is being
# totaled for an API call, and is called with the following syntax:
#
# api_cart_table_info("reason");
#
# There are really only five values that
# $reason_to_get_api_cart_info should be equal to:
#
# 1. "" ()
# 2. "" ()
# 3. "" ()
# 4. "" ()
# 5. "" ()
#
# $reason_to_get_api_cart_info blank for future needs
#
#######################################################################

sub api_cart_table_info {

    # Working variables are initialized and defined as local
    # to this subroutine.  Don't mess with these definitions.

    local ( $reason_to_get_api_cart_info ) = @_;
    local ( $cart_id_number, $cart_line_id )= q{};
    local ( $unformatted_subtotal, $subtotal ) = q{};
    local ( $unformatted_grand_total, $grand_total ) = q{};
    local ( $stevo_shipping_thing ) = q{};
    local ( $total_quantity, $total_measured_quantity ) = 0;
    local ( $found_it ) = q{};
    local ( $product_id, @db_row );
    local $api_call_status = 1;

    # taxable or non-table. added by Mister Ed Sept 13, 2005
    local ($isTaxable) = q{};
    local ($unformatted_taxable_grand_total) = 0;
    local ($taxable_grand_total) = 0;

    codehook( 'api_cart_table_info_top' );

    if ( $sc_global_bot_tracker ne '1' ) {    # run only if not a bot

        # Next, the client's cart is read line by line (file open
        # errors handled by file_open_error as usual).

        #&read_verify_file;
        if ( !( -f "$sc_cart_path" ) ) {    #doesn't exist, create a null file
            open( CART, ">$sc_cart_path" )
              || file_open_error( "$sc_cart_path", 'api_cart_table_info create null file',__FILE__,__LINE__
              );
            close(CART);
        }

        # If it cannot be read, then there is a problem
        open( CART, "$sc_cart_path" )
          || file_open_error( "$sc_cart_path", "api_cart_table_info",__FILE__, __LINE__ );

          if ( !( $sc_db_lib_was_loaded =~ /yes/i ) ) { require_supporting_libraries( __FILE__, __LINE__, "$sc_db_lib_path" ); }

        while (<CART>) {
            chomp;

            local @cart_fields     = split( /\|/, $_ );
            local $cart_row_number = pop(@cart_fields);
            push( @cart_fields, $cart_row_number );

            codehook( 'api_cart_table_info_row_read' );

            my $quantity   = $cart_fields[ $cart{'quantity'} ];
            my $product_id = $cart_fields[ $cart{'product_id'} ];

            # taxable or non-table. added by Mister Ed Sept 13, 2005
            $isTaxable = $cart_fields[ $cart{'user4'} ];

            # Then, we call the check_db_with_product_id
            # in the database library. If it returns
            # false, then we output a footer
            # complaining about the problem and
            # exit the program.

            # load the row for use with virtual fields ...
            undef(@db_row);
            $found_it = check_db_with_product_id( $product_id, *db_row );

            codehook( 'api_cart_table_info_db_row_read' );

            if (  ( $sc_order_check_db =~ /yes/i ) )   {
                if ( !($found_it) ) {
                    $api_error_string .= qq~
<div align="center"><p class="ac_error">$agora_error_message07$product_id $agora_error_message08</p></div>
~;
                    &api_error_header_print;
                    call_exit();
                }

                # Otherwise, we check the returned row
                # with the price of the product in the
                # cart. If the prices do not match
                # then another complaint message is printed
                # and we exit the program.

                else {

  # if ($db_row[$sc_db_index_of_price] ne $cart_fields[$sc_cart_index_of_price])
                    my $test_price = vf_get_data( 'PRODUCT', $sc_db_price_field_name, $db_row[$sc_db_index_of_product_id], @db_row );
                    if ( $test_price ne $cart_fields[$sc_cart_index_of_price] ) {
                        $api_error_string .= qq~
<div align="center"><p class="ac_error">$agora_error_message10$product_id $agora_error_message10</p></div>
~;
                        &api_error_header_print;
                        call_exit();
                    }
                    # End of Else
                }
            }

            $total_quantity += $quantity;


            # create the shipping info for SBW module and totals
            $total_measured_quantity = $total_measured_quantity + $quantity * $cart_fields[6];
            $shipping_total = $total_measured_quantity;

# alt origin postal code adds postal code to stevo for shipping by Mister Ed Feb 9, 2005
# added alt origin state/prov by Mister Ed May 22, 2007
            if ( $sc_alt_origin_enabled =~ /yes/i ) {
                my ( $zip, $stateprov, $junk ) =
                  split( /\,/, $cart_fields[11], 3 );
                $stevo_shipping_thing .= '|'
                  . $quantity . '*'
                  . $cart_fields[6] . '*'
                  . $cart_fields[$sc_cart_index_of_price_after_options] . '*'
                  . $zip . '*'
                  . $stateprov . '*';
            }
            else {
                $stevo_shipping_thing .= '|'
                  . $quantity . '*'
                  . $cart_fields[6] . '*'
                  . $cart_fields[$sc_cart_index_of_price_after_options] . '*'
                  . '*' . '*';
            }

# dimensional shipping data added to stevo for shipping by Mister Ed May 17, 2007
            if ( $sc_dimensional_shipping_enabled =~ /yes/i ) {
                $stevo_shipping_thing .= $cart_fields[13];
            }

            $unformatted_subtotal =  ( $cart_fields[$sc_cart_index_of_price_after_options] );
            $subtotal = format_price( $quantity * $unformatted_subtotal );
            $unformatted_grand_total = $grand_total + $subtotal;
            $grand_total   = format_price($unformatted_grand_total);

            # taxable or non-table. added by Mister Ed Sept 13, 2005
            if ( $isTaxable !~ /yes/i ) {
                $unformatted_taxable_grand_total = $taxable_grand_total + $subtotal;
                $taxable_grand_total =  format_price($unformatted_taxable_grand_total);
            }

            $price = format_price($subtotal);

            # End of while (<CART>)
        }

        close(CART);

        # For now, assume this value is correct.  If SBW or others change it
        # then they need to set this variable independently
        $sc_shipping_thing = $shipping_total . $stevo_shipping_thing;

        $price = format_price($grand_total);

        $shipping_total = format_price($shipping_total);

        (
        $final_shipping,   $final_discount,   $final_sales_tax,
        $final_extra_tax1, $final_extra_tax2, $final_extra_tax3,
        $grand_total, $final_buySafe, $final_PST_tax
      ) = get_api_calculations( $taxable_grand_total, $grand_total, 'at', $total_measured_quantity, $api_call_status );

        codehook( 'api_cart_table_info_bottom' );

        return (
        $final_shipping,   $final_discount,   $final_sales_tax,
        $final_extra_tax1, $final_extra_tax2, $final_extra_tax3,
        $grand_total, $final_buySafe, $final_PST_tax
      )
        # old returns
        #( $taxable_grand_total, $grand_total, $total_quantity, $total_measured_quantity, $stevo_shipping_thing );

    }    # end of "run only if not a bot"

    #End of api_cart_table_info
}

########################################################################
#                  get_api_calculations Subroutine
########################################################################
# Added by Mister Ed -- August 8, 2013
#
# Need a way to get the information without printing out results to the screen
#
sub get_api_calculations {

    local ( $taxable_grand_total, $subtotal, $are_we_before_or_at_process_form,
        $total_measured_quantity, $api_call_status )
      = @_;

    local (
        $final_shipping,   $final_discount,   $final_sales_tax,
        $final_extra_tax1, $final_extra_tax2, $final_extra_tax3,
        $grand_total, $final_buySafe, $final_PST_tax
    );

    (
        $final_shipping,   $final_discount,   $final_sales_tax,
        $final_extra_tax1, $final_extra_tax2, $final_extra_tax3,
        $grand_total, $final_buySafe, $final_PST_tax
      )
      = calculate_final_values( $taxable_grand_total, $subtotal,
        $total_quantity, $total_measured_quantity,
        $are_we_before_or_at_process_form, $api_call_status );

    # set these as global variables for possible use later
    $zsubtotal         = $subtotal;
    $zfinal_shipping   = $final_shipping;
    $zfinal_discount   = $final_discount;
    $zfinal_sales_tax  = $final_sales_tax;
    $zfinal_extra_tax1 = $final_extra_tax1;
    $zfinal_extra_tax2 = $final_extra_tax2;
    $zfinal_extra_tax3 = $final_extra_tax3;
    $zfinal_PSTsales_tax  = $final_PST_tax;
    $zfinal_buySafe    = $final_buySafe;
    if ( $subtotal < .000000001 ) {
        $zfinal_buySafe = q{};
    }
    $zgrand_total = $grand_total;

    if ( $final_shipping > 0 ) {
        $final_shipping = format_price($final_shipping);
    }

    if ( $final_discount > 0 ) {
        $final_discount      = format_price($final_discount);
    }

    if ( $final_sales_tax > 0 ) {
        $final_sales_tax      = format_price($final_sales_tax);
    }

    if ( $final_PST_tax > 0 ) {
        $final_PST_tax      = format_price($final_PST_tax);
    }

    if ( ( $final_buySafe > 0 ) && ( $subtotal > 0 ) ) {
        $final_buySafe      = format_price($final_buySafe);
    }
    else {
        $final_buySafe = q{};
    }

    $grand_total = format_price($grand_total);

    codehook( 'get_api_calculations_bottom' );

    return (
        $final_shipping,   $final_discount,   $final_sales_tax,
        $final_extra_tax1, $final_extra_tax2, $final_extra_tax3,
        $grand_total, $final_buySafe, $final_PST_tax
      );

}

########################################################################
#                  process_api_order_form Subroutine
########################################################################
#
# subroutine: process_api_order_form
#   Usage:
#     process_api_order_form();
#
#   Parameters:
#     None. This takes input from the form
#     variables of the previously displayed
#     order form
#
#   Output:
#     calculates totals, saves verified information, routes to API
#
########################################################################

sub process_api_order_form {

    local ( $subtotal, $total_quantity, $total_measured_quantity,
        $required_fields_filled_in, $taxable_grand_total, $api_error_string ) = q{};
    local ($continue)   = 1;
    local $we_need_to_exit = 0;

    codehook( 'process_order_form_top' );

    if ( $continue == 0 ) { return; }

     # We display the cart table.

    #api_cart_table_info('verify');

    # Now that we have the text of the cart
    # all together. We check the required
    # form fields from the previous form
    # to see if they were filled in by the user
    #
    # $required_fields_filled_in is set to "yes"
    # and remains this way until any ONE
    # required field is missing -- at which
    # point it is set to no.

    $required_fields_filled_in = 'yes';

    if ( $form_data{'gateway'} eq '' ) {

        # set default value, backwards compatable!
        $form_data{'gateway'} = $sc_gateway_name;
    }

    codehook( 'set_form_required_fields' );
    codehook('printSubmitPage');


# checks for prevent of Zero sub total orders.  Set in main settings manager
    # Added by Mister Ed (K-Factor Technologies, Inc) 10/17/2003
    if ( $sc_prevent_zero_total_orders =~ /yes/i ) {
        my $mustbegreaterthanthis = .0001;
        if ( $zsubtotal < $mustbegreaterthanthis ) {
            $we_need_to_exit++;
            if ( $we_need_to_exit eq 1 ) {
                $api_error_string .=  '<div align="center">';
            }
            $api_error_string .= <<ENDOFTEXT;
<p class="ac_missing_field">$agora_empty_orders</p>
ENDOFTEXT

        }
    }

    # checks for minimum order amount.  Set in main settings manager
    # Added by Mister Ed (K-Factor Technologies, Inc) 10/17/2003
    if ( $zsubtotal < $sc_minimum_order_amount ) {
        $we_need_to_exit++;

        if ( $we_need_to_exit eq 1 ) {
            $api_error_string .=  '<div align="center">';
        }
        $api_error_string .= <<ENDOFTEXT;
<p class="ac_missing_field">$agora_minimum_order $sc_minimum_order_amount $sc_minimum_order_text.</p>
ENDOFTEXT

    }

    foreach $required_field (@sc_order_form_required_fields) {
        if ( $form_data{$required_field} eq '' ) {
            $required_fields_filled_in = 'no';

            $we_need_to_exit++;
            if ( $we_need_to_exit eq 1 ) {
                $api_error_string .=  '<div align="center">';
            }
            $api_error_string .=  <<ENDOFTEXT;
<p class="ac_missing_field">$agora_missing_field $sc_order_form_array{$required_field}.</p>
ENDOFTEXT
        }

    }

    # End of checking required fields

    if ( $we_need_to_exit > 0 ) {
        &api_error_header_print;
        call_exit();
    }

}

########################################################################
#                  api_error_header_print Subroutine
########################################################################

sub api_error_header_print {
    # First, we output the header of the processing of the order
    print $sc_browser_header;
    print qq~$sc_doctype
<html>
<head>
<title>$agora_checkout_two</title>
$sc_standard_head_info
$sc_noindex_robot_meta_tags
</head>
<body>
~;

    # We display the cart table.
    (
        $taxable_grand_total, $subtotal, $total_quantity,
        $total_measured_quantity, $stevo_shipping_thing
    ) = display_cart_table('verify');

    print $api_error_string;

    print qq~<form method="post" action="$sc_stepone_order_script_url">
  <p class="ac_missing_field">
    <input type="hidden" name="order_form_button" value="1">
    $hidden_fields
    <input type="hidden" name="HCODE" value="$sc_pass_used_to_scramble">
    <input type="hidden" name="gateway" value="$form_data{'gateway'}">
    <input type="hidden" name="ofn" value="$form_data{'gateway'}">
    <input type="image" name="Make Changes" value="Make Changes" src="picserve.cgi?buttonserve=make_changes.gif" alt="Make Changes">
  </p>
</form>
</div>~;

    CheckoutStoreFooter();

}

########################################################################

1;
