<?php

namespace Main\Controllers\Credit;

use Exception;
use Main\Libs\Payment\Order;
use Main\Libs\Payment\Product;
use Main\Core\Controller;
use Main\Services\PaymentGatewayService;
use Main\Services\SeoService;

class ChargeController extends Controller
{
		protected string $route_type = 'credits';
		
		public function __construct()
		{
			if (modules('credit')->settings('creditPackageStatus') == 1) {
				redirect(url('credits.packages.index'));
			}
		}
		
    public function index()
    {
	      SeoService::set('credits.charge.index');
				
        $emailStatus = auth()->user()->email() != "your@email.com" && auth()->user()->email() != "guncelle@gmail.com";
	    
		    $paymentGateways = db()->prepare("SELECT * FROM PaymentGateways WHERE status = ? ORDER BY `order` ASC, title ASC");
		    $paymentGateways->execute(array(1));
		    $paymentGateways = $paymentGateways->fetchAll();
	    
		    $logs = db()->prepare("SELECT CH.* FROM CreditHistory CH WHERE CH.accountID = ? AND CH.type = ? ORDER by CH.id DESC LIMIT 5");
		    $logs->execute(array(auth()->user()->id(), 1));
        $logs = $logs->fetchAll();

        return $this->view('credits.charge', compact('paymentGateways', 'emailStatus', 'logs'));
    }

    public function charge()
    {
				$min = modules('credit')->settings('minPay');
				$max = modules('credit')->settings('maxPay');
				
        validate([
            "amount" => "required|numeric|min:$min|max:$max",
	          "paymentGatewayID" => "required"
        ]);
				
				if (auth()->user()->email() == "your@email.com") {
					return back()->flash('error', t__('To buy credits, you need to update your email.'));
				}
				
				if (modules('credit')->settings('showTermsCheckbox') == 1 && !isset($_POST["terms"])) {
					return back()->flash('error', t__('You must accept the terms and conditions!'));
				}
	    
		    $paymentGateway = db()->prepare("SELECT * FROM PaymentGateways WHERE slug = ? AND status = ?");
		    $paymentGateway->execute([input("paymentGatewayID"), 1]);
		    $paymentGateway = $paymentGateway->fetch();
		    if (!$paymentGateway) return back();
		    
		    $subtotal = input("amount");
		    $tax = 0;
		    if (modules('store')->settings('tax') > 0 && modules('store')->settings('isCreditRequiredOnPurchase') == 1) {
			    $tax = ($subtotal) * (modules('store')->settings('tax') / 100);
		    }
				$total = $subtotal + $tax;
	    
		    $gatewayFee = 0;
		    if ($paymentGateway["feeStatus"] == 1) {
			    $gatewayFee = $total * ($paymentGateway["transactionFee"] / 100);
			    if ($paymentGateway["fixedFee"] > 0) {
				    $gatewayFee += $paymentGateway["fixedFee"];
			    }
					
			    $total += $gatewayFee;
		    }
	    
		    $credit = $subtotal;
		    $bonus = 0;
		    if (modules('credit')->settings('bonusCredit') != 0 && $subtotal >= modules('credit')->settings('bonusCreditMinAmount') && (modules('credit')->settings('bonusCreditExpiryDate') == '1000-01-01 00:00:00' || modules('credit')->settings('bonusCreditExpiryDate') > date("Y-m-d H:i:s"))) {
			    $credit = $subtotal * ((modules('credit')->settings('bonusCredit') + 100) / 100);
			    $bonus = $credit - $subtotal;
		    }
		   
		    $createOrder = db()->prepare("INSERT INTO Orders (accountID, coupon, total, discount, subtotal, tax, gatewayFee, paymentID, paymentAPI, status, type, credit, earnings, creationDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
		    $createOrder->execute(array(
			    auth()->user()->id(),
			    null,
			    $total,
			    0,
			    $subtotal,
					$tax,
					$gatewayFee,
			    "",
			    $paymentGateway["slug"],
			    0,
			    2,
			    0,
			    $total,
			    datetime()
		    ));
		    $orderID = db()->lastInsertId();
	    
		    $insertOrderCredits = db()->prepare("INSERT INTO OrderCredits (orderID, amount, bonus) VALUES (?, ?, ?)");
		    $insertOrderCredits->execute(array($orderID, $credit, $bonus));
	    
		    $customer = PaymentGatewayService::getCustomer();
		    
		    // Order object
		    $products = [
			    new Product(t__('%credit% credit(s)', ['%credit%' => $credit]), $total, 1)
		    ];
		    $order = new Order(
			    $orderID,
			    "credit",
			    $total,
			    $subtotal,
			    $tax,
			    $gatewayFee,
			    0,
			    0,
			    null,
			    $products
		    );
		    
		    try {
			    $payment = PaymentGatewayService::init($paymentGateway["slug"], $paymentGateway["currency"], $paymentGateway["config"]);
			    $payment->setCustomer($customer);
			    $payment->setOrder($order);
			    $payment->pay();
		    } catch (Exception $e) {
			    if (settings('debugModeStatus') == 1) {
				    return $e->getMessage();
			    } else {
				    return $this->view('payment.error');
			    }
		    }
    }
}