$versions{'PayPalBasic-order_lib.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.
#
#######################################################################
#                    Order Form Definition Variables
#######################################################################
$sc_order_response_vars{'PayPalBasic'} = 'PayPalBasic';
$PayPalBasic_form_prep = 0;
add_codehook( 'printSubmitPage', 'print_PayPalBasic_SubmitPage' );
add_codehook( 'set_form_required_fields', 'PayPalBasic_fields' );
add_codehook( 'special_navigation', 'PayPalBasic_pre_header_nav' );
add_codehook( 'gateway_response', 'check_for_PayPalBasic_response' );

#best to leave this option as it is, as PayPal return is NOT guaranteed!
# set to "no" if email upon return
$PayPalBasic_email_before = 'yes';
#######################################################################
sub PayPalBasic_URL_logic {
    local ( $bn, $url, $return, $mylogic, $err_code );
    if ( $sc_use_custom_PayPalBasic_url_logic =~ /yes/i ) {
        $mylogic = "$sc_custom_PayPalBasic_url_logic";
        eval($mylogic);
        $err_code = $@;
        if ( $err_code ne '' ) {    #script died, error of some kind
            update_error_log( "custom-paypal-url-logic $err_code ", '', '' );
        }
    }
    else {
        $return = $sc_store_url;
        $return =~ s/\:/\%3A/;
        $bn = $PayPalBasic_gateway_username;
        $bn =~ s/\@/\%40/;
        $url =
            $PayPalBasic_order_script_url . '='
          . $bn
          . '&item_name='
          . my_PayPalBasic_order_name()
          . my_PayPalBasic_order_number()
          . '&item_number='
          . my_PayPalBasic_order_number()
          . '&amount='
          . format_price($authPrice)
          . "&currency_code=$PayPalBasic_currency_id"
          . '&no_shipping=1'
          . "&address_override=$PayPalBasic_address_override"
          . "&first_name=$eform_Ecom_ShipTo_Postal_Name_First"
          . "&last_name=$eform_Ecom_ShipTo_Postal_Name_Last"
          . "&address1=$eform_Ecom_ShipTo_Postal_Street_Line1"
          . "&city=$eform_Ecom_ShipTo_Postal_City"
          . "&state=$eform_Ecom_ShipTo_Postal_StateProv"
          . "&zip=$eform_Ecom_ShipTo_Postal_PostalCode"
          . "&return=$return"
          . '&bn=AgoraCart'
          . "%3Fppret%3D$cart_id";
        $url =~ s/\ /+/g;
        $url =~ s/\#/\%23/g;
    }

    # use this to change $url
    codehook('PayPalBasic_URL_logic_bottom');

    return $url;

}

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

sub PayPalBasic_check_and_load {
    local ($myname) = 'PayPalBasic';
    if ( $mc_mgr_gateways_enabled =~ /$myname/ ) {
        require_supporting_libraries( __FILE__, __LINE__, "$sc_userpay_conf_dir/$myname-user_lib.pl" );
    }
}

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

sub check_for_PayPalBasic_response {
    PayPalBasic_check_and_load();
    if ( $form_data{'ppret'} ) {
        $cart_id = $form_data{'ppret'};
        set_sc_cart_path();
        load_order_libs();
        load_cart_libs();
        codehook( 'PayPalBasic_order' );
        process_PayPalBasic_Order();
        call_exit();
    }
}

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

sub PayPalBasic_pre_header_nav {
    local ($myname) = 'PayPalBasic';
    $PayPalBasic_form_prep = 0;
    if ( $form_data{'ppsnd'} ) {
        PayPalBasic_check_and_load();
        $form_data{'cart_id'} =~ /^([\w\-\=\+\/]+)\.(\w+)/;
        $cart_id = "$1.$2";
        set_sc_cart_path();
        load_order_libs();
        load_cart_libs();
        codehook('PayPalBasic_order_send');
        process_PayPalBasic_Order('send');
        call_exit();
    }
}

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

sub PayPalBasic_fields {
    local ($myname) = 'PayPalBasic';

    if ( ( $mc_mgr_gateways_enabled !~ /$myname/ ) && ( $form_data{'gateway'} ne $myname ) ) {
        return;
    }

    set_order_form_array();

    @sc_order_form_required_fields = (
        'Ecom_BillTo_Online_Email',      'Ecom_ShipTo_Postal_Name_First',
        'Ecom_ShipTo_Postal_Name_Last',  'Ecom_ShipTo_Postal_Street_Line1',
        'Ecom_ShipTo_Postal_City',       'Ecom_ShipTo_Postal_StateProv',
        'Ecom_ShipTo_Postal_PostalCode', 'Ecom_ShipTo_Postal_CountryCode'
    );

    if ( $PayPalBasic_display_checkout_tos =~ /yes/i ) {
        push( @sc_order_form_required_fields, 'Ecom_tos' );
    }

    # use this codehook to change the above arrays for required fields and such
    codehook('PayPalBasic_fields_bottom');

}

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

sub PayPalBasic_order_form_prep {    # load the customer info ...
    PayPalBasic_check_and_load();
    if ( $PayPalBasic_form_prep == 0 ) {
        if ( -f "$sc_verify_order_path" ) {
            read_verify_file();
        }
        else {
            codehook('load_customer_info');
        }
        $PayPalBasic_form_prep = 1;
    }
    return '';
}

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

sub PayPalBasic_table_setup {

    #
    # To use this, put this in the email_text in the manager for HTML:
    #
    #	<!--agorascript-pre
    #	  return $PayPalBasic_cart_table;
    #	-->
    #
    # or for text in an email:
    #
    #	<!--agorascript-pre
    #	  return $PayPalBasic_prod_in_cart;
    #	-->
    #

    local ( @my_cart_fields, $my_cart_row_number, $result );
    local ( $count, $price, $product_id, $quantity, $total_cost, $total_qty ) = 0;
    local ( $name, $cost );

    $PayPalBasic_prod_in_cart = q{};
    $PayPalBasic_cart_table   = q{};
    $result                = q{};
    open( CART, "$sc_cart_path" ) || file_open_error(
        "$sc_cart_path", 'display_cart_contents_in_header',__FILE__, __LINE__ );
    while (<CART>) {
        $count++;
        chop;
        @my_cart_fields = split( /\|/, $_ );
        $my_cart_row_number = pop(@my_cart_fields);
        push( @my_cart_fields, $my_cart_row_number );
        $quantity   = $my_cart_fields[0];
        $product_id = $my_cart_fields[1];
        $price      = $my_cart_fields[$sc_cart_index_of_price_after_options];
        $name       = $my_cart_fields[ $cart{'name'} ];
        $name       = substr( $name, 0, 35 );
        $cost       = format_price( $quantity * $price );
        $total_cost = $total_cost + $quantity * $price;
        $total_qty  = $total_qty + $quantity;
        $options    = $my_cart_fields[ $cart{'options'} ];
        $options =~ s/<br>/ /g;

        if ( $result eq '' ) {
            $result .= '<table cellpadding=0 cellspacing=0 border=0 width=425>';
            $result .= "<tr><td>Items Ordered:</td></tr><tr><td>\n";
            $result .=
              "<table cellpadding=3 cellspacing=0 border=1 width=100%>\n";
            $result .= "<tr><th>QTY</th><th>ID #</th><th>Description</th>";
            $result .= "<th>Cost</th></tr>\n";
            $PayPalBasic_prod_in_cart .= "  --PRODUCT INFORMATION--\n\n";
        }
        $result .= "<tr><td>$quantity</td><td>$product_id</td>\n";
        $result .= "<td>$name</td><td>$cost</td>";
        $result .= '</tr>\n';
        $PayPalBasic_prod_in_cart .= cart_textinfo(*my_cart_fields);
    }    # End of while (<CART>)
    close(CART);
    if ( $result ne '' ) {
        $result .= '</table></td></tr></table>\n';
    }

    # use this to change $result
    codehook('PayPalBasic_table_setup_bottom');

    $PayPalBasic_cart_table = $result;

}

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

sub my_PayPalBasic_order_name {
    local ($temp);
    eval( '$temp = "' . $PayPalBasic_order_name . '";' );
    return $temp;
}

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

sub my_PayPalBasic_order_number {
    local ($temp);
    eval( '$temp = "' . $PayPalBasic_order_number . '";' );
    return $temp;
}

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

sub print_PayPalBasic_SubmitPage {

    local ( $invoice_number, $customer_number, $url, $return, $img, $bn );
    local ($myname) = 'PayPalBasic';
    local ( $my_change, $my_message, $my_desc );

    if ( ( $mc_mgr_gateways_enabled !~ /$myname/ ) || ( $form_data{'gateway'} ne $myname ) ) { return; }

    $invoice_number  = $current_verify_inv_no;
    $customer_number = $cart_id;
    $customer_number =~ s/_/./g;

    if ( ( $PayPalBasic_email_before =~ /yes/i ) && ( $authPrice > 0 ) ) {
        $url = $sc_store_url . "?ppsnd=$cart_id&cart_id=$cart_id";
    }
    else {
        read_verify_file();
        $url = PayPalBasic_URL_logic();

    }

    $my_desc = script_and_substitute($PayPalBasic_order_desc);
    $my_message = script_and_substitute($PayPalBasic_verify_message);

    if ( $PayPalBasic_verifytable eq '' ) {
        $PayPalBasic_verifytable = 'verifyTable_PayPalBasic.inc';
    }

    require_supporting_libraries( __FILE__, __LINE__, "$sc_cartverifyplates_dir/$PayPalBasic_verifytable" );


    print $PayPalBasic_verifytable_at_checkout;
    print <<ENDOFTEXT;

ENDOFTEXT

}

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

sub process_PayPalBasic_Order {

    local ($mode) = @_;
    local ( $subtotal, $total_quantity, $total_measured_quantity, $text_of_cart,
        $required_fields_filled_in, $product, $quantity, $options );
    local ($stevo_shipping_thing) = q{};
    local ($stevo_shipping_names) = q{};
    local ( $ship_thing_too, $ship_instructions, $href, $return, $bn, $url );

    codehook('process-order-routine-top');

    if ( $mode eq 'send' ) {
        read_verify_file();
        $authPrice = $sc_verify_grand_total;
        $url = PayPal_URL_logic();
    }

    if (
        ( ( $PayPalBasic_email_before =~ /yes/i ) && ( $mode eq "send" ) )
        || ( ( !( $PayPalBasic_email_before =~ /yes/i ) ) && ( !( $mode eq 'send' ) ) )
      )
    {
        send_PayPalBasic_Email();
    }

    if ( $mode eq 'send' ) {    # Need to send them to PayPal
        #undef(%agora);
        #undef(%form_data);
        #set_agora('AGORA_ORDER_COMPLETED', 'yes');
        #agora_cookie_save();
        print "Location: $url\n\n";
        call_exit();
    }

codehook('process-order-display-thankyou-page');

    if ( $PayPalBasic_thankstable eq '' ) {
        $PayPalBasic_thankstable = 'thanksTable_basic1.inc';
    }
    require_supporting_libraries( __FILE__, __LINE__,"$sc_templates_dir/$PayPalBasic_thankstable" );

    print $sc_thankstable_after_checkout;

    CheckoutStoreFooter();

    empty_cart();
    undef(%form_data);

}

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

sub send_PayPalBasic_Email {
    local ( $subtotal, $total_quantity, $total_measured_quantity, $text_of_cart,
        $html_of_cart, $html_of_cart_header, $weight, $required_fields_filled_in,
        $product, $quantity, $options, $myoptions, $weight );
    local ($stevo_shipping_thing) = q{};
    local ($stevo_shipping_names) = q{};
    local ( $ship_thing_too, $ship_instructions, $xcomments_html );
    local (%orderLoggingHash);
    local ($verification) = q{};
    local (%zip_list);
    local (%zip_names_list);
    my $temp_admin_email_template = $PayPalBasic_admin_email_template;
    my $temp_email_template = $PayPalBasic_email_template;

    if ( $temp_admin_email_template eq '' ) {
        $temp_admin_email_template = 'admin_emailPlate_text_default01.inc';
    }
    if ( $temp_email_template eq '' ) {
        $temp_email_template = 'emailPlate_text_default01.inc';
    }

    load_verify_file();

    $orderDate = get_date();

    # default data entered at cart order  form logged here, if exists.
    populate_orderlogging_hash();

    $orderLoggingHash{'orderDate'}   = "$orderDate";
    $orderLoggingHash{'GatewayUsed'} = 'PayPalBasic';

    if ( $sc_use_html_customer_emails =~ /yes/i )  {
        $html_of_cart_header = cart_html_headerinfo();
    }

    open( CART, "$sc_cart_path" )
      || file_open_error( "$sc_cart_path", 'display_cart_contents', __FILE__,__LINE__ );

        if ( $sc_opt_sep_marker eq '' ) {
            $sc_opt_sep_marker = '<br>';
        }
        while (<CART>) {
            $cartData++;
            @cart_fields   = split( /\|/, $_ );
            $quantity      = $cart_fields[0];
            $product_price = $cart_fields[3];
            $product       = $cart_fields[4];
            $weight        = $cart_fields[6];
            $options       = $cart_fields[ $cart{"options"} ];
            $options =~ s/${sc_opt_sep_marker}$//i;
            $myoptions = $options;
            $options =~ s/$sc_opt_sep_marker/,/gi;
            $text_of_cart         .= cart_textinfo(*cart_fields);
            if ($sc_use_html_customer_emails =~ /yes/i)  {
                $html_of_cart .= cart_html_textinfo(*cart_fields);
            }
            $myoptions =~ s/<br>/,\n         /g;
            if ( $myoptions ne '' ) { $myoptions = "\n        \($myoptions\)"; }
            $stevo_shipping_thing .= "|$quantity\*$weight";
            $stevo_shipping_names .= "|$product$myoptions";
            codehook('process-cart-item');
        }
        close(CART);


    $sc_orderlib_use_SBW_for_ship_ins = $sc_use_SBW;

    codehook('orderlib-ship-instructions');

    if ( $sc_orderlib_use_SBW_for_ship_ins =~ /yes/i ) {
        ( $ship_thing_too, $ship_instructions ) = ship_put_in_boxes(
            $stevo_shipping_thing, $stevo_shipping_names,
            $sc_verify_Origin_ZIP, $sc_verify_boxes_max_wt
        );
    }

    $orderLoggingHash{'shippingMessages'} = "$ship_instructions";
    $orderLoggingHash{'shippingMessages'} =~ s/\n/<br>/g;
    $orderLoggingHash{'cart_and_order_id'} = "$cart_id";
    $orderLoggingHash{'cart_invoiceNumber'}  = "$sc_verify_inv_no";


    codehook('process-order-pre-xcomments');

    $orderLoggingHash{'adminMessages'} =
      "$verification<br><br>$XCOMMENTS_ADMIN";
    $orderLoggingHash{'adminMessages'} .=
        qq|\nPAYMENT INFORMATION --------------\nTRANSACTION STATUS: PayPal Standard - PENDING\n\nDOUBLE CHECK TO MAKE SURE PAYMENT WAS RECEIVED AT PAYPAL\n--------------------------------------------\n|;
    $orderLoggingHash{'xcomments'} = "$XCOMMENTS";

    $x_description = my_PayPalBasic_order_name() . my_PayPalBasic_order_number();

    if ( $sc_send_order_to_email =~ /yes/i ) {
        local $text_of_cart_to_send = replace_email_template_tokens($temp_admin_email_template);
        codehook('admin_mailtosend');
        send_mail(
            $sc_admin_email,  $sc_order_email,
            $x_description, $text_of_cart_to_send
        );
    }

    if ( $cartData && $eform_Ecom_BillTo_Online_Email ) {
        if ($sc_use_html_customer_emails =~ /yes/i)  {
            $sc_email_content_type = "text/html";
        }
        $xcomments_html = $orderLoggingHash{'xcomments'};
        $xcomments_html =~ s/\n/<br>/g;
        my $text_of_cart_to_send = replace_email_template_tokens($temp_email_template);
        send_mail(
            $sc_admin_email,   $orderLoggingHash{'emailAddress'},
            $messages{'ordcnf_08'}, "$text_of_cart_to_send"
        );
    }

    $orderLoggingHash{'adminMessages'} =~ s/\n/<br>/g;
    $orderLoggingHash{'adminMessages'} =~ s/\t/ /g;
    $orderLoggingHash{'xcomments'}     =~ s/\n/<br>/g;
    $orderLoggingHash{'adminMessages'} =~ s/\t/ /g;

    log_order( $sc_verify_inv_no, $cart_id );

    if ( $sc_buySafe_is_enabled =~ /yes/ ) {
        set_agora( 'BUYSAFE_ORDER_COMPLETED', 'yes' );
    }

    undef(%form_data);
    undef(%orderLoggingHash);

    set_agora('AGORA_ORDER_COMPLETED', 'yes');
    agora_cookie_save();
    empty_cart();

}

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

1;
