<?php
$raw_post_data = file_get_contents('php://input');
$raw_post_array = explode('&', $raw_post_data);
$myPost = ['payment_status' => ''];
foreach ($raw_post_array as $keyval)
{
    $keyval = explode('=', $keyval);
    if (count($keyval) == 2)
    {
        $myPost[$keyval[0]] = urldecode($keyval[1]);
    }
}
$req = 'cmd=_notify-validate';
if (function_exists('get_magic_quotes_gpc'))
{
    $get_magic_quotes_exists = true;}
foreach ($myPost as $key => $value)
{
    if ($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1)
    {
        $value = urlencode(stripslashes($value));}
    else
    {
        $value = urlencode($value);}
    $req .= "&$key=$value";
}
$ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Connection: Close']);
$res = trim(curl_exec($ch));
curl_close($ch);
$payment_verified = false;
if (strcmp($res, "VERIFIED") == 0)
{
    $payment_verified = true;
}
//make sure status is completed
if ($myPost['payment_status'] != 'Completed')
{
    $payment_verified = false;
}
//check transactions status
if ($payment_verified == false && !isset($_GET['forceAdmin']))
{
    die('Unauthorised access 1');exit;}
if (empty($_GET['order']))
{
    die('Unauthorised access 2');exit;}
include_once '../../class/mysql.php';
require_once '../../functions.php';
require_once fileInclude('class/site.php');
//check for order
$owner = addslashes($_GET['order']);
$subtotal = 0;
$query = $mysql->query("(price*qty) as price", "fs_shop_cart", "owner = '$owner' AND temp = 'y'");
if ($mysql->num_rows($query) == 0)
{
    die('Unauthorised access');exit;}
while ($data = $mysql->get_array($query))
{
    $subtotal += $data['price'];
}
$orderTotal = $mysql->get_array($mysql->query("shipping,sales_tax,discount_value,discount_code", "fs_shop_orderdata", "owner = '$owner' AND temp = 'y' LIMIT 1"));
$total = number_format($subtotal + $orderTotal['shipping'] - $orderTotal['sales_tax'] - $orderTotal['discount_value'], 2);
if ($_GET['pickuplater'] == 'y')
{
    $total = number_format($subtotal - $orderTotal['sales_tax'] - $orderTotal['discount_value'], 2);
}
//order contsnt for the email
$orderContents = '';
$cartQuery = $mysql->query("item_name,qty,virtual,pid", "fs_shop_cart", "owner = '$owner'");
while ($cartContents = $mysql->get_array($cartQuery))
{
    $orderContents .= stripslashes($cartContents['qty']." X ".$cartContents['item_name'])."\n";
//vr download link
    if ($cartContents['virtual'] == 'y')
    {
        $i = $mysql->get_array($mysql->query("virtual_product_file", "fs_shop_products", "ID = {$cartContents['pid']} LIMIT 1"));
        $orderContents .= "Download: http://".str_replace("www.", "", $_SERVER['SERVER_NAME'])."/inc/shop/images/".$i['virtual_product_file']."\n\n";
    }
//
}
//make and send email to customer
$order = $mysql->get_array($mysql->query("first_name,email_address,discount_code", "fs_shop_orderdata", "owner = '$owner' AND temp = 'y' LIMIT 1"));
$msg = "Hi ".$order['first_name'].",

Thank you for placing your order with ".$_SERVER['SERVER_NAME']."!

Once your order has been processed, we will send you an email to notify you.

Your order number: $owner

----Order contents----
".$orderContents."
If you would like more details for this order, please download the invoice from below URL.
http://".str_replace("www.", "", $_SERVER['SERVER_NAME'])."/inc/shop/invoice/?order=".$owner."

If you have any questions regarding your order please do not hesitate to contact us via our site.

Thank you
http://".str_replace("http://", "", $_SERVER['SERVER_NAME']);
if ($_GET['pickuplater'] == 'y')
{
    $address = $site->shop_settings('shop_address');
    $msg = "Hi ".$order['first_name'].",

Thank you for placing your order with ".$_SERVER['SERVER_NAME']."!

** Please remember that you have selected to pay now and pick up this order at our store using PAY NOW PICK UP LATER method. **

Our store address:
".stripslashes($address['shop_address'])."

Once your order has been processed, we will send you an email to notify you.

Your order number: $owner

----Order contents----
".$orderContents."
If you have any questions regarding your order please do not hesitate to contact us via our site.

Thank you
http://".str_replace("http://", "", $_SERVER['SERVER_NAME']);
    $mysql->update("shipping", "0", "fs_shop_orderdata", "owner = '$owner' AND temp = 'y' LIMIT 1");
}
//email customer
$admin = $site->shop_settings('admin_email');
emailWithPhpMailer($order['email_address'], 'Your Order @ '.$_SERVER['SERVER_NAME'], $msg, $admin['admin_email'], false);
//email the admin
$msg = "Hello,

A new shop order from {$order['first_name']} for $".$total." was placed at ".$_SERVER['SERVER_NAME'].", please process it ASAP.

----Order contents----
".$orderContents."
If you would like more details for this order, please download the invoice from below URL or view the order in your account.
http://".str_replace("www.", "", $_SERVER['SERVER_NAME'])."/inc/shop/invoice/?order=".$owner."

Thank you
http://".str_replace("http://", "", $_SERVER['SERVER_NAME']);
emailWithPhpMailer($admin['admin_email'], 'New Order @ '.$_SERVER['SERVER_NAME'], $msg, $admin['admin_email'], false);
//mark order as paid
$method = ($_GET['pickuplater'] == 'y') ? 'pay now pickup later' : 'paypal';
$mysql->update("temp,payment_method", "n,$method", "fs_shop_orderdata", "owner = '$owner' AND temp = 'y' LIMIT 1");
$mysql->update("temp", "n", "fs_shop_cart", "owner = '$owner' AND temp = 'y'");
//update stock
$query = $mysql->query("pid,`option`,qty", "fs_shop_cart", "owner = '$owner' AND temp = 'n'");
while ($cart = $mysql->get_array($query))
{
    $site->update_stock($cart['pid'], $cart['option'], $cart['qty'], false);
}
//delete one_use discount code
$mysql->Delete("fs_shop_discountcodes", "code = '{$order['discount_code']}' AND one_use = 'y' LIMIT 1");
//end
die();
exit;
