<?php include("../Header/Session.php"); ?>
<?php include("../Header/Connection.php"); ?>

<?php 
$redirectStr = ''; 
if(!empty($_GET['paymentID']) && !empty($_GET['token']) && !empty($_GET['payerID']) && !empty($_GET['pid']) ){ 
    // Include and initialize database class 
    include_once 'Paypal/DB.class.php'; 
    $db = new DB; 
 
    // Include and initialize paypal class 
    include_once 'Paypal/PaypalExpress.class.php'; 
    $paypal = new PaypalExpress; 
     
    // Get payment info from URL 
    $paymentID = $_GET['paymentID']; 
    $token = $_GET['token']; 
    $payerID = $_GET['payerID']; 
    $productID = $_GET['pid']; 
    $payment_code = $_GET['payment_code']; 
     
    // Validate transaction via PayPal API 
    $paymentCheck = $paypal->validate($paymentID, $token, $payerID, $productID); 
     
    // If the payment is valid and approved 
    if($paymentCheck && $paymentCheck->state == 'approved')
    { 					
		// Get the transaction data 
        $id = $paymentCheck->id; 
        $state = $paymentCheck->state; 
        $payerFirstName = $paymentCheck->payer->payer_info->first_name; 
        $payerLastName = $paymentCheck->payer->payer_info->last_name; 
        $payerName = $payerFirstName.' '.$payerLastName; 
        $payerEmail = $paymentCheck->payer->payer_info->email; 
        $payerID = $paymentCheck->payer->payer_info->payer_id; 
        $payerCountryCode = $paymentCheck->payer->payer_info->country_code; 
        $paidAmount = $paymentCheck->transactions[0]->amount->details->subtotal; 
        $currency = $paymentCheck->transactions[0]->amount->currency; 

		$sql_order_item = "SELECT *
							FROM package_payment
							WHERE payment_code = '$payment_code'
							LIMIT 1";
		$result_order_item = $mysqli-> query($sql_order_item);
		if ($result_order_item -> num_rows > 0)
		{
			$row_order_item = $result_order_item ->fetch_assoc();
			$order_id  = $row_order_item['order_id'];
			$trans_code  = $row_order_item['trans_code'];
			$amount  = $row_order_item['amount'];
		}
         
        // If payment price is valid 
        if($amount >= $paidAmount)
        { 
             
            // Insert transaction data in the database 
            $data = array( 
                'product_id' => $productID, 
                'txn_id' => $id, 
                'payment_gross' => $paidAmount, 
                'currency_code' => $currency, 
                'payer_id' => $payerID, 
                'payer_name' => $payerName, 
                'payer_email' => $payerEmail, 
                'payer_country' => $payerCountryCode, 
                'payment_status' => $state 
            ); 
            $insert = $db->insert('payments', $data); 
             
            // Add insert id to the URL 
            $redirectStr = '?id='.$insert;  

            $sql_payment = "SELECT * 
			FROM payment 
			WHERE payment_code='$payment_code' ";
			$result_payment = $mysqli-> query($sql_payment);
			if ($result_payment -> num_rows > 0)
			{
				$row_payment = $result_payment ->fetch_assoc();
				$user_ref_code = $row_payment['ref_code'];
				$payment_code = $row_payment['trans_code'];
				$Name = $row_payment['name'];
				$Email = $row_payment['email'];
				$Tel = $row_payment['phone_number'];
				$amount = $row_payment['amount'];
			}

			$AP_status_id = '1';

			//If success payment
			if($AP_status_id == '1') 
			{
				$status = 1;

				$sql_order_item = "SELECT *
						   FROM woocommerce_order_info
						   WHERE order_id  = '$order_id'
						   AND trans_code  = '$trans_code'
						   AND status='1'";
				$result_order_item = $mysqli-> query($sql_order_item);
				if ($result_order_item -> num_rows > 0)
				{
					$row_order_item = $result_order_item ->fetch_assoc();
					$order_items  = $row_order_item['order_items'];
					$order_full_total = $row_order_item['order_full_total'];
				}

				$data_total_payment = 
				"SELECT SUM(amount) As num 
				FROM package_payment
				WHERE order_id = '$order_id'
				AND trans_code = '$trans_code'
				AND ref_code = '$user_ref_code'
				AND status = '1'";    
				$result_total_payment = $mysqli->query($data_total_payment);
				if ($result_total_payment ->num_rows > 0)
				{
					$row_total_payment = $result_total_payment ->fetch_assoc();
					$full_total_payment = $row_total_payment['num'];
				}

				$order_balance = $order_full_total - $full_total_payment - $amount;

				//Update Payment Info
				$Update_payment_info = "UPDATE payment SET
				transaction_id='$AP_transaction_id',
				status='1',
				payment_status='1'
				WHERE payment_code = '$AP_billcode' ";
				$result_payment_info = $mysqli->query($Update_payment_info);
		
				//Update Package Info
				$Update_package_info = "UPDATE package_payment SET
				balance = '$order_balance',
				status='1'
				WHERE payment_code = '$payment_code' ";
				$result_package_info = $mysqli->query($Update_package_info);

				if ($result_payment_info && $result_package_info)
				{
					//echo "<script type='text/javascript'>alert('Succesfully Paid');</script>";
					echo "<script type='text/javascript'> document.location='pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
					exit();
				}
				else
				{
					//echo "<script type='text/javascript'>alert('Payment Fail');</script>";
					echo "<script type='text/javascript'> document.location='pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
					exit();
				}						
			}
			else // If not success
			{									
				//echo "<script type='text/javascript'>alert('Payment Fail');</script>";
				echo "<script type='text/javascript'> document.location='pay_package.php?order_id=$order_id&trans_code=$trans_code'; </script>";
				exit();
			}

        } 
    } 
     
    // Redirect to payment status page 
    header("Location:pay_package.php?order_id=$order_id&trans_code=$trans_code"); 
}
else
{ 
    // Redirect to the home page 
    header("Location:pay_package.php?order_id=$order_id&trans_code=$trans_code"); 
} 
?>