include "../includes/session.php";
include "../includes/functions.php";
//$ip=$_SERVER['REMOTE_ADDR'];
//echo "<b>IP Address= $ip</b>";
if (get_magic_quotes_gpc()) {
    $_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
}
if (isset($_SESSION["sess_adminname"]) and $_SESSION["sess_adminname"] != "") {
    $adminname = $_SESSION["sess_adminname"];
} else {
    header("Location:login.php");
    exit;
}
$adminCurrency = GetAdminCurrency();
$adminSymbol = $adminCurrency['currency_symbol'];
/*
 * Orders
*/
$sql = "SELECT o.order_id,o.order_date,\n                CONCAT(o.billing_first_name, ' ' ,o.billing_last_name) as user_name,\n                od.product_discount,\n                (o.order_total_price+o.taxrate) as total\n                FROM " . $tableprefix . "orders o \n                INNER JOIN " . $tableprefix . "order_details od ON o.order_id = od.order_id  WHERE o.vpayment_status='C'\n                GROUP BY o.order_id ORDER BY o.order_id DESC LIMIT 0,5";
$orderResult = mysql_query($sql) or die(mysql_error());
/*
 * Orders - End
*/
/*
 * Order Counts Start
*/
$totalOrders = 0;
$pendingOrders = 0;
$shippedOrders = 0;
function exportCSV($artistid)
{
    global $tableprefix;
    $adminCurrency = GetAdminCurrency();
    $currencycode = getSellerCurrencySybol($artistid);
    $currencySymbol = getCurrencySybol($currencycode);
    $csv = new CSV(array('Order #', 'Order Total', 'Commission (%)', 'Total Tax Amount', 'Total Shipping Amount', 'Product Total Amount', 'Amount Received [ Product Total Amount - Admin Commision  + Product Shipping + Tax ]', 'Date Paid(mm/dd/yyyy)', 'Payment Status'), ";");
    $qryopt = "";
    $qrybtw = "";
    $sql = " SELECT sp.*,s.artist_name FROM " . $tableprefix . "artist_payments sp\n\t\tINNER JOIN  " . $tableprefix . "artists s ON sp.artist_id = s.artist_id\n                INNER JOIN  " . $tableprefix . "orders o ON o.order_id = sp.order_id" . $qryopt . "\n\t\tWHERE sp.artist_id = '" . addslashes($artistid) . "' AND o.vpayment_status='C'" . $qrybtw . "order by sp.artist_payment_id DESC   ";
    $rs = mysql_query($sql) or die("qqqq" . mysql_error());
    $result = mysql_query($sql) or die("www" . mysql_error());
    if (mysql_num_rows($result) > 0) {
        $i = 1;
        $total = 0;
        while ($row = mysql_fetch_array($rs)) {
            $txtPaymentDate = isNotNull($row["payment_date"] and $row["payment_date"] != "0000-00-00") ? dateFormat($row["payment_date"], "Y-m-d", "m/d/Y") : " Not Yet Settled;";
            if ($row['payment_status'] == 'P') {
                $Paymentstatus = 'Pending';
            } else {
                $Paymentstatus = 'Paid';
            }
            $qryopt1 = " ";
            $taxtotal = 0;
            $sql1 = "SELECT o.*, u.user_name, u.email, od.product_discount,sum( (od.product_price-(od.product_price*product_discount/100)) * od.product_quantity) as total,sum(od.product_tax)as taxtotal\n\t\tFROM " . $tableprefix . "orders o\n\t\tINNER JOIN " . $tableprefix . "users u ON o.user_id = u.user_id\n\t\tINNER JOIN " . $tableprefix . "order_details od ON o.order_id = od.order_id\n\t\tWHERE od.artist_id = '" . $artistid . "'\n                AND o.order_id = " . $row['order_id'] . "\n\t\tAND o.vpayment_status != 'P'" . $qryopt1 . " GROUP BY o.order_id ORDER BY o.order_date,o.order_id DESC ";
            $sellerCurrency = getSellerCurrencySybol($artistid);
            $result1 = mysql_query($sql1);
            if (mysql_num_rows($result1) != 0) {
                $row1 = mysql_fetch_array($result1);
                $ordernumber = $row1["order_id"];
                $username = $row1["user_name"];
                if ($row1['vorder_currency'] != $sellerCurrency and $row1['vorder_currency'] != "USD") {
                    $get_conversion_price = getCurrencyrate($sellerCurrency);
                    $ordertotal = $row1["total"];
                } else {
                    $ordertotal = $row1["total"];
                }
                $taxtotal = $row1["taxtotal"];
            }
            $select_shipping_cost = "SELECT sd.vshipping_name, sd.nshipping_cost,od.product_name\n                           FROM " . $tableprefix . "shipping_details sd," . $tableprefix . "order_details  od\n                          WHERE od.product_id=sd.nshp_productid\n                            AND norder_id = " . $row['order_id'] . "\n                            AND nshp_status = 'C'\n                            AND od.artist_id = '" . $artistid . "'\n                       GROUP BY sd.nshp_productid order by  od.product_name";
            $result_shipping_cost = mysql_query($select_shipping_cost);
            if (mysql_num_rows($result_shipping_cost) > 0) {
                $totalshippingcost = 0;
                while ($shipping_row = mysql_fetch_array($result_shipping_cost)) {
                    $totalshippingcost += $shipping_row['nshipping_cost'];
                }
            }
            $csv->addRow(array($row["order_id"], html_entity_decode($adminCurrency['currency_symbol']) . " " . number_format($row["seller_order_total_amount"], 2, '.', ''), $row["commission_percentage"], html_entity_decode($adminCurrency['currency_symbol']) . " " . number_format($taxtotal, 2, '.', ''), html_entity_decode($adminCurrency['currency_symbol']) . " " . number_format($totalshippingcost, 2, '.', ''), html_entity_decode($adminCurrency['currency_symbol']) . " " . number_format($row["total_amount"], 2, '.', ''), html_entity_decode($adminCurrency['currency_symbol']) . " " . number_format($row["amount_paid"], 2, '.', ''), $txtPaymentDate, $Paymentstatus));
            $artistName = $row["artist_name"];
            $i++;
            $total += $row["amount_paid"];
        }
        if ($total > 0) {
            $csv->addRow(array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '));
            $csv->addRow(array(' ', ' ', ' ', ' ', ' ', ' ', 'Total Seller Amount Received', html_entity_decode($currencySymbol) . " " . number_format($total, 2, '.', ''), ' '));
        }
    }
    // export csv as a download
    $filename = 'order_payment_details_' . $artistName;
    //$filename = 'order_payment_details'.$artistid;
    $csv->export($filename);
    // *or* pass the csv data to a variable as a string
    //$string = $csv;
}
 public static function getShippingPriceProduct($productid = 0, $productOptionId = 0, $userId = "", $destination_country = "", $destination_state = "", $destination_zip = "")
 {
     global $tableprefix;
     $adminCurrency = GetAdminCurrency();
     if (isCartEmpty($userId)) {
         clsGenerateShippingControl::getNoShippingControl($product_option_id);
         return 0;
     }
     if (get_magic_quotes_gpc()) {
         $_POST = array_map('stripslashes_deep', $_POST);
         $_GET = array_map('stripslashes_deep', $_GET);
         $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
     }
     if ($destination_country == "" && $destination_state == "" && $destination_zip == "") {
         $userAddress = clsGenerateShippingControl::getuserAddress($userId);
         if (count($userAddress) > 0) {
             $destination_state = $userAddress['state'];
             $destination_country = $userAddress['country'];
             $destination_zip = $userAddress['zip'];
         }
     }
     $uspsRequired_Service = array("Express Mail", "Express Mail Hold For Pickup", "Express Mail Sunday/Holiday Delivery", "Priority Mail", "Parcel Post", "Priority Mail Large Flat Rate Box", "\nPriority Mail Medium Flat Rate Box", "Priority Mail Small Flat Rate Box", "Priority Mail Flat Rate Envelope", "Media Mail", "Library Mail");
     //===================Getting Currency Type=========================
     $currency_attributes = displayCurrencyType();
     $flatrateEnabled = getSettingsValue('enable_flatrate');
     /*display the active template*/
     //set shipping gateway and doing basic settings
     include_once 'fedex/fedex.php';
     $sql = "select * from " . $tableprefix . "fedexsettings ";
     $rs = mysql_query($sql) or die(mysql_error());
     if (mysql_num_rows($rs) > 0) {
         $serviceName = array();
         $row = mysql_fetch_array($rs);
         $fedexaccno = stripslashes($row['FedexAccno']);
         $fedexmeterno = stripslashes($row['FedexMeterno']);
         $weightunits = $row['FedexWeight'];
         $server = $row['FedexServer'];
         $dropoff = stripslashes($row['FedexDropOff']);
         $packageTypes = stripslashes($row['FedexPackage']);
         $sName = $row['FedexService'];
         $currency = $row['FedexCurrency'];
         if ($_SESSION["sessShippingMethod"] == "FDXE") {
             $sarry = $fedexService;
             $shippingTitle = "Fedex Express Shipping";
         } else {
             $sarry = $fedexGroundService;
             $shippingTitle = "Fedex Express Ground Shipping";
         }
     }
     // end num rows check
     switch ($server) {
         case "test":
             $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
             break;
         case "production":
             // change this to actual server when go on live
             $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
             break;
         default:
             $fedexserver = "https://gatewaybeta.fedex.com/GatewayDC";
             break;
     }
     //// check enabled shipping is usps or not
     include_once "usps/xmlparser.php";
     include_once 'usps/usps.php';
     $shippingTitle = "USPS";
     $sql = "select * from " . $tableprefix . "usps_settings ";
     $rs = mysql_query($sql) or die(mysql_error());
     if (mysql_num_rows($rs) > 0) {
         $row = mysql_fetch_array($rs);
         $uspsid = $row['username'];
         $server = $row['server'];
     }
     // end num rows check
     switch ($server) {
         case "test":
             $uspsserver = "http://testing.shippingapis.com/ShippingAPITest.dll";
             break;
         case "production":
             //change this line when usps is on live
             $uspsserver = "http://Production.ShippingAPIs.com/ShippingAPI.dll";
             break;
         default:
             $uspsserver = "http://testing.shippingapis.com/ShippingAPITest.dll";
             break;
     }
     // end switch
     require_once "ups.php";
     include_once "shipping.php";
     include_once 'http_client.php';
     $shippingTitle = "UPS";
     // Shipping setting for UPS Shipping
     $select_shipping_settings = "SELECT * FROM " . $tableprefix . "shipping_settings";
     $result_shipping_settings = mysql_query($select_shipping_settings);
     if (mysql_num_rows($result_shipping_settings) > 0) {
         $rs_ship = mysql_fetch_array($result_shipping_settings);
         $ups_weight = $rs_ship['nShippingweight'];
         $ups_rate = $rs_ship['ups_rate'];
         $ups_container = $rs_ship['container_type'];
         $ups_type = $rs_ship['address_quote_method'];
     }
     $upsrate = new Ups();
     // select product details
     $select_cart_details = "SELECT prd.product_id,prd.product_name,po.product_option_id,po.product_length,po.product_width,po.product_height,crt.quantity,\n                       po.product_shipping_weight,art.country AS origin_country,art.state AS origin_state,art.zip AS origin_zip,art.artist_id,\n                       art.defaultflatrate,art.additionalflatrate, prd.eUps, prd.eUsps , prd.eFedex , prd.fFlatRateShippingAmount, prd.fAdditionalItemCost\n                       FROM " . $tableprefix . "cart crt\n                       INNER JOIN " . $tableprefix . "product_options po ON crt.product_option_id = po.product_option_id\n                       INNER JOIN " . $tableprefix . "products prd ON prd.product_id = po.product_id\n                       INNER JOIN " . $tableprefix . "artists art ON art.artist_id = prd.product_artist_id\n                       WHERE crt.user_id = '" . mysql_real_escape_string($userId) . "' AND po.product_option_id = '" . mysql_real_escape_string($productOptionId) . "' ORDER BY crt.cart_id";
     $result_cart_details = mysql_query($select_cart_details) or die(mysql_error());
     $_SESSION["SHIPPING_DETAILS"] = array();
     $_SESSION["SHIPPING_TOTAL"] = 0;
     $productArray = array();
     $resultShippingArray = array();
     if (mysql_num_rows($result_cart_details) == 0) {
         //as no products there is no point in staying in shipping options
         clsGenerateShippingControl::getNoShippingControl($product_option_id);
         return 0;
     } else {
         //Now we need to take shipping rates a products
         $cart_details_row = mysql_fetch_array($result_cart_details);
         $shipping_weight = trim($cart_details_row['product_shipping_weight']);
         $origin_country = $cart_details_row['origin_country'];
         $origin_state = $cart_details_row['origin_state'];
         $origin_zip = $cart_details_row['origin_zip'];
         $product_name = $cart_details_row['product_name'];
         $artist_id = $cart_details_row['artist_id'];
         $product_id = $cart_details_row['product_id'];
         $product_option_id = $cart_details_row['product_option_id'];
         $optionsStr = "";
         $optionVal = getProductOptionsName($product_option_id);
         if ($optionVal != "") {
             $optionsStr = "<br>" . $optionVal;
         }
         $productArray[$product_option_id] = $product_name . $optionsStr;
         $quantity = trim($cart_details_row['quantity']);
         $product_length = $cart_details_row['product_length'];
         $product_height = $cart_details_row['product_height'];
         $product_width = $cart_details_row['product_width'];
         // Take product shippings
         $productShippingArray = array();
         if ($cart_details_row['eUps'] == 'Y') {
             $productShippingArray[] = 'UPS';
         }
         if ($cart_details_row['eFedex'] == 'Y') {
             $productShippingArray[] = 'FDXG';
         }
         if ($cart_details_row['eUsps'] == 'Y') {
             $productShippingArray[] = 'USPS';
         }
         if ($cart_details_row['fFlatRateShippingAmount'] > 0) {
             $productShippingArray[] = 'Flat Rate';
             $FlatRateShippingAmount = $cart_details_row['fFlatRateShippingAmount'];
             $AdditionalItemCost = $cart_details_row['fAdditionalItemCost'];
         }
         /*  echo '<br>' . $origin_state;
             echo '<br>' . $origin_country;
             echo '<br>' . $origin_zip;
             echo '<br>' . $destination_state;
             echo '<br>' . $destination_country;
             echo '<br>' . $destination_zip;*/
         //print_r($productShippingArray);
         foreach ($productShippingArray as $key => $shippingMethod) {
             //  $shippingMethod = $value; // set product shipping
             //set for ups only
             $shippingMethod = trim($shippingMethod);
             //======================Getting rates for each product from shipping gateways-Santhosh=================================
             switch ($shippingMethod) {
                 case "FDXE":
                 case "FDXG":
                     $shippingMode = $shippingMethod;
                     if (is_array($sarry)) {
                         // check service is an array or not
                         foreach ($sarry as $serviceNames) {
                             $fedex_shipping_weight = $shipping_weight * $quantity;
                             list($service, $serviceName) = split('-', $serviceNames);
                             $fedex = new Fedex();
                             $fedex->setServer($fedexserver);
                             $fedex->setAccountNumber($fedexaccno);
                             //Get your own - this will not work...
                             $fedex->setMeterNumber($fedexmeterno);
                             //Get your own - this will not work...
                             $fedex->setCarrierCode($shippingMode);
                             $fedex->setDropoffType($dropoff);
                             $fedex->setService($service, $serviceName);
                             $fedex->setPackaging($packageTypes);
                             $fedex->setWeightUnits($weightunits);
                             $fedex->setWeight($fedex_shipping_weight);
                             $fedex->setOriginStateOrProvinceCode($origin_state);
                             $fedex->setOriginPostalCode($origin_zip);
                             $fedex->setOriginCountryCode($origin_country);
                             $fedex->setDestStateOrProvinceCode($destination_state);
                             $fedex->setDestPostalCode($destination_zip);
                             $fedex->setDestCountryCode($destination_country);
                             $fedex->setPayorType("SENDER");
                             $fedexprice = $fedex->getPrice();
                             $fedexrate[] = $fedexprice->price->rate;
                             $fedexerror[] = $fedexprice->error->description;
                             if ($fedexprice->error->description == "" && $fedexprice->serviceName != "" && $fedexprice->price->rate != "") {
                                 $resultShippingArray[$product_option_id][] = array("service_name" => $fedexprice->serviceName, "rate" => $fedexprice->price->rate);
                             }
                         }
                         // end foreach
                     }
                     // end array check
                     break;
                 case "USPS":
                     $usps_shipping_weight = $shipping_weight * $quantity;
                     if ($usps_shipping_weight < 1) {
                         $usps_shipping_weight = 1;
                     }
                     $usps_shipping_weightSplit = explode(".", $usps_shipping_weight);
                     $shipping_pounds = $usps_shipping_weightSplit[0];
                     $ouncelength = count_digit($usps_shipping_weightSplit[1]);
                     if ($ouncelength == 0) {
                         $shipping_ounces = 0;
                     }
                     if ($ouncelength == 1) {
                         $shipping_ounces = $usps_shipping_weightSplit[1] / 10 * 16;
                     }
                     if ($ouncelength == 2) {
                         $shipping_ounces = $usps_shipping_weightSplit[1] / 100 * 16;
                     }
                     if ($ouncelength == 3) {
                         $shipping_ounces = $usps_shipping_weightSplit[1] / 1000 * 16;
                     }
                     if ($ouncelength == 4) {
                         $shipping_ounces = $usps_shipping_weightSplit[1] / 10000 * 16;
                     }
                     $usps = new USPS();
                     if ($server == "test") {
                         $usps->setWeight(10, 5);
                         $usps->setDestZip("20008");
                         $usps->setOrigZip("10022");
                     } else {
                         $usps->setDestZip($destination_zip);
                         $usps->setOrigZip($origin_zip);
                         $usps->setWeight($shipping_pounds, $shipping_ounces);
                     }
                     $usps->setServer($uspsserver);
                     $usps->setUserName($uspsid);
                     $uspspaswd = "";
                     $usps->setPass($uspspaswd);
                     $usps->setService("All");
                     //$usps->setContainer("Flat Rate Box");
                     $usps->setCountry("USA");
                     $usps->setMachinable("true");
                     $usps->setSize("REGULAR");
                     $uspsprice = array();
                     $uspsprice = $usps->getPrice();
                     $special_chars = "&lt;sup&gt;&amp;reg;&lt;/sup&gt;";
                     if ($uspsprice->error->description == "") {
                         foreach ($uspsprice->list as $eachItem) {
                             if ($eachItem->mailservice != "" && $eachItem->rate != "") {
                                 $eachItemServicename = str_replace($special_chars, "", $eachItem->mailservice);
                                 if (in_array($eachItemServicename, $uspsRequired_Service)) {
                                     $resultShippingArray[$product_option_id][] = array("service_name" => $eachItemServicename, "rate" => $eachItem->rate);
                                 }
                             }
                         }
                     }
                     break;
                 case "UPS":
                     $ups_types = clsGenerateShippingControl::getupsShippingTypes();
                     $ups_shipping_weight = $shipping_weight * $quantity;
                     $ups_shipping_weight = $ups_shipping_weight < 0.1 ? 0.1 : $ups_shipping_weight;
                     foreach ($ups_types as $types => $ups) {
                         $upsrate->upsProduct($types);
                         // See upsProduct() function for codes
                         $upsrate->origin($origin_zip, $origin_country);
                         // Use ISO country codes!
                         $upsrate->dest($destination_zip, $destination_country);
                         // Use ISO country codes!
                         $upsrate->rate($ups_rate);
                         // See the rate() function for codes
                         $upsrate->container($ups_container);
                         // See the container() function for codes
                         $upsrate->weight(number_format($ups_shipping_weight, 2, ".", ""));
                         $upsrate->rescom($ups_type);
                         // See the rescom() function for codes
                         $quote = $upsrate->getQuote();
                         if ($quote != "error" && $ups != "" && $quote != "") {
                             $resultShippingArray[$product_option_id][] = array("service_name" => $ups, "rate" => $quote);
                         }
                         // end price empty check
                     }
                     //end foreach
                     break;
                 case "Flat Rate":
                     $flat_rate_name = "Flat Rate";
                     $first_Item_charge = $FlatRateShippingAmount;
                     $additional_Item_charge = $AdditionalItemCost;
                     $rate = $first_Item_charge + $additional_Item_charge * ($quantity - 1);
                     $resultShippingArray[$product_option_id][] = array("service_name" => stripslashes($flat_rate_name), "rate" => $rate);
                 default:
             }
             // if the rate array is empty for other shipping Options check whether
             // admin has enabled the flat rate shipping so that customer can still
             // buy with the flat option.
             $Selected_Shipping_options = $shippingTitle;
             if (empty($selectedShippingOption)) {
                 $selectedShippingOption = $shippingTitle;
             }
             $shipping_options_availabe = count($resultShippingArray[$product_option_id]);
         }
         // end while loop
     }
     return $resultShippingArray;
 }
function GetCategory_productName($productid)
{
    global $tableprefix;
    $sql_meta_product = "SELECT p.product_name,c.category_name,c.category_id,p.product_description,p.product_price  from " . $tableprefix . "products p INNER JOIN " . $tableprefix . "categories c\n\t \t\t\t\t\t\t\t\tON c.category_id=p.product_category  where p.product_id='" . $productid . "'  ";
    $rs_meta_prodcuct = mysql_query($sql_meta_product) or die(mysql_error());
    if (mysql_num_rows($rs_meta_prodcuct) > 0) {
        $productObj = mysql_fetch_object($rs_meta_prodcuct);
        $product_name = stripslashes($productObj->product_name);
        $category_name = stripslashes($productObj->category_name);
        $category_id = $productObj->category_id;
        // Item Description
        if (strlen($productObj->product_description) > 200) {
            $description = substr($productObj->product_description, 0, 200);
        } else {
            $description = $productObj->product_description;
        }
        // End Item Description
        $price = $productObj->product_price;
        $adminCurrency = GetAdminCurrency();
        $description = htmlentities($description);
        $description .= "  Price :: " . $adminCurrency['currency_symbol'] . " " . number_format($price, 2, ".", "");
    }
    $keywordTag = $product_name . ", " . getCategorynames($category_id) . SITE_NAME;
    $titleTag = $product_name . ", " . getCategorynames($category_id) . SITE_NAME;
    $descriptionTag = $description;
    $product_description = array("product_title" => $titleTag, "product_keyword" => $keywordTag, "product_description" => $descriptionTag);
    return $product_description;
}