<?php

if (!defined('INCLUDED_AMEMBER_CONFIG')) 
    die("Direct access to this location is not allowed");

/*
*
*
*     Author: Alex Scott
*      Email: alex@cgi-central.net
*        Web: http://www.cgi-central.net
*    Details: google checkout payment plugin
*    FileName $RCSfile$
*    Release: 3.1.8PRO ($Revision: 3277 $)
*
* Please direct bug reports,suggestions or feedback to the cgi-central forums.
* http://www.cgi-central.net/forum/
*                                                                          
* aMember PRO is a commercial software. Any distribution is strictly prohibited.
*
*/

global $config;
//require_once($config['root_dir']."/plugins/payment/cc_core/cc_core.inc.php");

require_once('gCheckout.php');

class payment_google_checkout extends amember_payment {
    
    function do_payment($payment_id, $member_id, $product_id, $price, $begin_date, $expire_date, &$vars){
        
        global $config, $db;
        
        $checkout_xml_schema = 'http://checkout.google.com/schema/2';
        $gCheckout = new gCheckout($this->config["merchant_id"], $this->config["merchant_key"], $cart_expires = '', 
                                   $checkout_xml_schema, $this->config["currency"], $this->config["debug"]);
        
        // Specify an expiration date for the order and build <shopping-cart>
        $tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
        $cart_expiration = date("Y-m-d", $tomorrow) . "T" . date("H:i:s");
        $gCheckout->setCartExpirationDate($cart_expiration);

        if (!is_array($price))
            $price = array($product_id => $price);

        $payment = $db->get_payment($payment_id);
        if ($pr = $payment['data'][0]['BASKET_PRODUCTS'])
            $product_id = $pr;
        
        if ($prices = $payment['data'][0]['BASKET_PRICES'])
            $price = $prices;
        
        $taxes = $payment['data']['TAXES'];
        
        if (!is_array($product_id))
            $product_id = (array)$product_id;
            
        
        foreach ($product_id as $pid){
            ///////////////////////////////////////
            // Add product
            ///////////////////////////////////////
            // Specify item data and create an item to include in the order
            $product = $db->get_product($pid);
            $item_name = trim(strip_tags($product['title'])); 
            $item_description = trim(strip_tags($product['description']));
            $quantity = "1";
            
            //$unit_price = $product['price'];
            $unit_price = $price[$pid];
            
            $tax_table_selector = "";
            $merchant_private_item_data = "<product-id>$pid</product-id>";
            

            ///////////////////////////////////////
            // Add Taxes info
            ///////////////////////////////////////
            if (false && $config['use_tax']){
    
                $area_type = "country";
                $area_place = "ALL";
                $tax_area = $gCheckout->getTaxArea($area_type, $area_place);
                
                if ($product['use_tax']){
                    $rate = $taxes[$pid] / $product['price'];
                } else {
                    $rate = "0.00";
                }
                
                if (!$rate) $rate = "0.00";
                $gCheckout->addAlternateTaxRule($rate, $tax_area);
                
                $standalone = 'true';
                $name = $pid;
                $gCheckout->addAlternateTaxTable($standalone, $name);
                
                $tax_table_selector = $pid;
            }

            $gCheckout->addItem($item_name, $item_description, $quantity, $unit_price, $tax_table_selector, $merchant_private_item_data);
        }
        
        
        ///////////////////////////////////////
        // Add extra data
        ///////////////////////////////////////
        $merchant_private_data = "<payment-id>$payment_id</payment-id><member-id>$member_id</member-id>";
        $gCheckout->setMerchantPrivateData($merchant_private_data);
        
        ///////////////////////////////////////
        // Add Merchant Calculations data
        ///////////////////////////////////////
        //$merchant_calc_url = $config['root_surl']."/plugins/payment/google_checkout/ResponseHandler.php";
        //$gCheckout->setMerchantCalculations($merchant_calc_url, $accepts_coupons="", $accept_gift_certificates="");

        ///////////////////////////////////////
        // Add shipping info
        ///////////////////////////////////////
        // Create list of areas where a particular shipping option is available
        /*
        $allowed_country_area = "ALL";    // OR: "CONTINENTAL_48", "FULL_50_STATES"
        $allowed_state = array();        // Ex: array("CA", "NY", "DC", "NC")
        $allowed_zip = array();        // Ex: array("94043", "94086", "91801", "91362")
        $allowed_restrictions = $gCheckout->getAllowedAreas($allowed_country_area, $allowed_state, $allowed_zip);
        */
        /*
        $excluded_country_area = "TX";    // OR: "CONTINENTAL_48", "FULL_50_STATES"
        $excluded_state = array();        // Ex: array("CA", "NY", "DC", "NC")
        $excluded_zip = array();        // Ex: array("94043", "94086", "91801", "91362")
        $excluded_restrictions = $gCheckout->getExcludedAreas($excluded_country_area, $excluded_state, $excluded_zip);
        */

        /*
        $name = 'UPS Ground';
        $prc = '10.0';
        $gCheckout->setFlatRateShipping($name, $price, $allowed_restrictions, $excluded_restrictions);
        */
        
        /*
        $name = 'Merchant Shipping';
        $prc = '20.0';
        $gCheckout->setMerchantCalculatedShipping($name, $price, $allowed_restrictions, $excluded_restrictions);
        */
        
        // Create a <pickup> shipping option
        $name = "Pickup";
        $prc = "0.00";
        $gCheckout->setPickup($name, $prc);
        
        ///////////////////////////////////////
        // Add Taxes info
        ///////////////////////////////////////
        if (false && $config['use_tax']){

            if ($config['tax_type'] == '2'){ // TODO: MUST BE FIXED FOR NEW REGIONAL TAX STRUCTURE - alex@cgi-central.net
                foreach ($config['regional_taxes'] as $regional_tax){
                    
                    $area_type = "country";
                    $area_place = "ALL";
                    if ($regional_tax['country']) {
                        $area_type = "country";
                        $area_place = $regional_tax['country'];
                    } elseif ($regional_tax['state']) {
                        $area_type = "state";
                        $area_place = $regional_tax['state'];
                    }
                    $tax_area = $gCheckout->getTaxArea($area_type, $area_place);
                    
                    $rate = $regional_tax['tax_value'] / 100;
                    $shipping_taxed = 'true';
                    $gCheckout->addDefaultTaxRule($rate, $tax_area, $shipping_taxed);
                    
                }
            } else {
    
                $area_type = "country";
                $area_place = "ALL";
                $tax_area = $gCheckout->getTaxArea($area_type, $area_place);
                $rate = $config['tax_value'] / 100;
                $shipping_taxed = 'false';
                $gCheckout->addDefaultTaxRule($rate, $tax_area, $shipping_taxed);
    
            }

            $merchant_calculated = 'false';
            $gCheckout->CreateTaxTables($merchant_calculated);
            
            /*
            $area_type = "state";
            $area_place = "CA";
            $tax_area = $gCheckout->getTaxArea($area_type, $area_place);
            $rate = "0.0825"; //8.25% tax is represented as 0.0825
            $shipping_taxed = 'true';
            $gCheckout->addDefaultTaxRule($rate, $tax_area, $shipping_taxed);
            
            $area_type = "country";
            $area_place = "ALL";
            $tax_area = $gCheckout->getTaxArea($area_type, $area_place);
            $rate = "0.07";
            $shipping_taxed = 'false';
            $gCheckout->addDefaultTaxRule($rate, $tax_area, $shipping_taxed);
            
            $area_type = "zip";
            $area_place = "12345";
            $tax_area = $gCheckout->getTaxArea($area_type, $area_place);
            $rate = "0.1";
            $gCheckout->addAlternateTaxRule($rate, $tax_area);
            
            $area_type = "zip";
            $area_place = "333777";
            $tax_area = $gCheckout->getTaxArea($area_type, $area_place);
            $rate = "0.2";
            $gCheckout->addAlternateTaxRule($rate, $tax_area);
            
            $area_type = "state";
            $area_place = "TX";
            $tax_area = $gCheckout->getTaxArea($area_type, $area_place);
            $rate = "0.15";
            $gCheckout->addAlternateTaxRule($rate, $tax_area);
            
            $standalone = 'false';
            $name = "food";
            $gCheckout->addAlternateTaxTable($standalone, $name);
            
            $merchant_calculated = 'false';
            $gCheckout->CreateTaxTables($merchant_calculated);
            */

        }
        
        ///////////////////////////////////////
        // Information about shipping, taxes, and merchant calculations used at checkout time.
        ///////////////////////////////////////
        $gCheckout->setMerchantCheckoutFlowSupport($edit_cart_url ="", $continue_shopping_url = "", $request_buyer_phone_number = false);

        ///////////////////////////////////////
        // Create Checkout Shopping Cart
        ///////////////////////////////////////
        
        // Get <checkout-shopping-cart> XML
        $xml_cart   = $gCheckout->getCart();
        $response   = $gCheckout->SendRequest($xml_cart, 'request');
		$res        = $gCheckout->ProcessXmlData ($response);
		
        if ($res['error-message']){
            $gCheckout->LogMessage ($res['error-message'], $debug_only_msg = true);
            return array("Google Checkout payment error. Please contact site administrator: <a href=\"mailto:".$config['admin_email']."\">".$config['admin_email']."</a>");
        }

    }
    function get_cancel_link($payment_id){
        global $db;                            
        return cc_core_get_cancel_link('google_checkout', $payment_id);
    }
    function get_plugin_features(){
        return array(
            'title' => $config['payment']['google_checkout']['title'] ? $config['payment']['google_checkout']['title'] : _PLUG_PAY_GOOGLE_CHECKOUT_TITLE,
            'description' => $config['payment']['google_checkout']['description'] ? $config['payment']['google_checkout']['description'] : _PLUG_PAY_GOOGLE_CHECKOUT_DESC,
            'currency' => array('usd' => 'USD', 'eur' => 'EUR'),
            'phone' => 2,
            'code' => 1,
            'name' => 2
        );
    }

}
/*
function google_checkout_get_member_links($user){
    return cc_core_get_member_links('google_checkout', $user);
}

function google_checkout_rebill(){
    return cc_core_rebill('google_checkout');
}

cc_core_init('google_checkout');
*/

$pl = & instantiate_plugin('payment', 'google_checkout');

?>
