<?php

include("GameEngine/Protection.php");
include("GameEngine/Village.php");
include("Templates/Plus/price.tpl");
include("GameEngine/config.php");
require_once("GameEngine/paypal.class.php");
define('EMAIL_ADD', 'xbox360ps2game@gmail.com'); // define any notification email

require_once("GameEngine/Mailer.php"); // مسیر Mailer.php رو درست بذار
$mailer = new Mailer;




$p 				= new paypal_class(); // paypal class
$p->admin_mail 	= EMAIL_ADD; // set notification email
$action 		= $_REQUEST["action"];

switch ($action) {
	case "process": // case process insert the form data in DB and process to the paypal



		// چک کردن ورودی‌های لازم
		$invoice = uniqid("INV-");
		$product_id      = $_POST["product_id"] ?? '';
		$product_name    = $_POST["product_name"] ?? '';
		$product_quantity = $_POST["product_quantity"] ?? '';
		$product_amount  = $_POST["product_amount"] ?? '';
		$payer_fname     = $_POST["payer_fname"] ?? '';
		$payer_email     = $_POST["payer_email"] ?? '';
		$payer_address   = $_POST["payer_address"] ?? '';
		$currency_code   = $_POST["currency_code"] ?? '';
		$cmd             = $_POST["cmd"] ?? '_cart';


		// انتخاب ایمیل پی‌پال بر اساس مبلغ
		if ($product_amount > 1 && $product_amount <= 6) {
			define('PAYPAL_EMAIL_ADD', 'amirjahesh51@gmail.com');
		} elseif ($product_amount > 6 && $product_amount <= 11) {
			define('PAYPAL_EMAIL_ADD', 'amirjahesh51@gmail.com');
		} elseif ($product_amount > 11 && $product_amount <= 31) {
			define('PAYPAL_EMAIL_ADD', 'servergame603@gmail.com');
		} elseif ($product_amount > 31) {
			define('PAYPAL_EMAIL_ADD', 'sup.warian@gmail.com');
		} else {
			//die("Invalid product amount.");
		}


		$database->query("INSERT INTO `" . TB_PREFIX . "purchases` (invoice, product_id, product_name, product_quantity, product_amount, payer_fname, payer_address,payer_email, payment_status, posted_date) VALUES ('" . $invoice . "', '" . $_POST["product_id"] . "', '" . $_POST["product_name"] . "', '" . $_POST["product_quantity"] . "', '" . $_POST["product_amount"] . "', '" . $_POST["payer_fname"] . "','" . $_POST["payer_address"] . "','" . $_POST["payer_email"] . "', 'pending', NOW())");

		$this_script = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];

		$p->add_field('business', PAYPAL_EMAIL_ADD); // Call the facilitator eaccount
		$p->add_field('cmd', $_POST["cmd"]); // cmd should be _cart for cart checkout
		$p->add_field('upload', '1');
		$p->add_field('return', $this_script . '?action=success'); // return URL after the transaction got over
		$p->add_field('cancel_return', $this_script . '?action=cancel'); // cancel URL if the trasaction was cancelled during half of the transaction
		$p->add_field('notify_url', $this_script . '?action=ipn'); // Notify URL which received IPN (Instant Payment Notification)
		$p->add_field('currency_code', $_POST["currency_code"]);
		$p->add_field('invoice', $invoice);
		$p->add_field('item_name_1', $_POST["product_name"]);
		$p->add_field('item_number_1', $_POST["product_name"]);
		$p->add_field('quantity_1', $_POST["product_quantity"]);
		$p->add_field('amount_1', $_POST["product_amount"]);
		$p->add_field('first_name', $_POST["payer_fname"]);
		$p->add_field('address1', $_POST["payer_address"]);
		$p->add_field('email', $_POST["payer_email"]);


		//$p->dump_fields(); // Show the posted values for a reference, comment this line before app goes live	

		$p->submit_paypal_post(); // POST it to paypal


		break;

	case "success":

		$itemTransaction = $_REQUEST['tx']; // Paypal transaction ID
		$itemPrice       = $_REQUEST['amt']; // Paypal received amount
		$itemCurrency    = $_REQUEST['cc']; // Paypal received currency type
		$invoice         = $_REQUEST['invoice'] ?? ''; // PayPal Custom Field (we can send invoice as cm if needed)

		foreach ($AppConfig['plus']['packages'] as $package) {
			if ($itemPrice == $package['dollar']) {
				$gold = $package['gold'];
			}
		}


		if (!$database->check_purchases($itemTransaction)) {

			if (!empty($itemTransaction) && !empty($itemPrice) && !empty($itemCurrency)) {
				// واکشی اطلاعات خرید با استفاده از invoice یا transaction ID
				$purchase = mysqli_fetch_assoc($database->query("SELECT * FROM `" . TB_PREFIX . "purchases` WHERE invoice = '$invoice' AND payment_status = 'pending' LIMIT 1"));

				if ($purchase) {
					$payer_email   = $purchase['payer_email'];
					$payer_address = $purchase['payer_address'];

					$database->query("UPDATE `" . TB_PREFIX . "users` SET gold = gold + $gold, boughtgold = boughtgold + $gold WHERE `id` = '" . $session->uid . "'");
					$database->query("UPDATE `" . TB_PREFIX . "purchases` SET trasaction_id = '$itemTransaction', payment_status = 'success' WHERE invoice = '$invoice'");

					$purchaseDetails = "
							<strong>💳 Gold Purchase Receipt</strong><br><br>
							👤 Username: {$session->username}<br>
							📧 Email: {$payer_email}<br>
							💰 Gold Purchased: {$gold}<br>
							💵 Amount Paid: {$itemPrice} {$itemCurrency}<br>
							🧾 Transaction ID: {$itemTransaction}<br>
							🏠 Address: {$payer_address}<br>
							🕒 Date: " . date("Y-m-d H:i:s") . "
						";
					$topic = $gold . "-" . LANG_151;
					$database->sendMessage($session->uid, 4, $topic, $purchaseDetails, 0);

					// ارسال ایمیل
					$mailer->sendNotification(
						$payer_email,
						$session->username,
						"✅ Your Gold Purchase Was Successful",
						"Hi {$session->username},<br><br>Thank you for your purchase. Your gold has been successfully added to your account.<br><br>{$purchaseDetails}<br><br>Regards,<br>TravianSpeed Team"
					);

					$mailer->sendNotification(
						'saeed.zeraati@gmail.com',
						'Admin',
						"🛒 New Gold Purchase by {$session->username}",
						"A new gold purchase was made:<br><br>{$purchaseDetails}"
					);

					//  جمع کل خریدها (اختیاری)
					if (method_exists($database, 'Asz_addbuy')) {
						$database->Asz_addbuy('sumbuy', $itemPrice);
					}

					header("Location: nachrichten.php");
					exit;
				}
			}
		} else {
			header("Location: dorf1.php");
			exit;
		}

		break;

	case "cancel": // case cancel to show user the transaction was cancelled
		echo "<h1>Transaction Cancelled ";
		header("Location: nachrichten.php"); /* Redirect browser */
		exit;
		break;

	case "ipn": // IPN case to receive payment information. this case will not displayed in browser. This is server to server communication. PayPal will send the transactions each and every details to this case in secured POST menthod by server to server. 
		$trasaction_id  = $_POST["txn_id"];
		$payment_status = strtolower($_POST["payment_status"]);
		$invoice		= $_POST["invoice"];

		if ($p->validate_ipn()) { // validate the IPN, do the others stuffs here as per your app logic

			$database->query("UPDATE purchases SET trasaction_id = '$trasaction_id ', log_id = '$paypal_log_id', payment_status = '$payment_status' WHERE invoice = '$invoice'");
			$subject = 'Instant Payment Notification - Recieved Payment';
			$p->send_report($subject); // Send the notification about the transaction


		} else {
			$subject = 'Instant Payment Notification - Payment Fail';
			$p->send_report($subject); // failed notification
		}
		break;
}
