<?php

namespace engine\eventSubscribers\payment;

use Subscribers\AbstractEventSubscriber;

class SuccessPaymentSubscriber extends AbstractEventSubscriber
{

    public function balance($data, $meta)
    {

    }

    public function donate($eventData, $meta)
    {
        $isSuccessParam = true;
        $defaultRedirect = "";

        $data = $eventData["data"];
        $widget = $eventData["widget"];
        $user_id = $eventData["user_id"];
        $settings = $eventData["settings"];
        $emailTemplate = $eventData["emailTemplate"];

        $dollarSum = convertAmount($data["sum"],  $data["currency"], "USD");
        $dollarSumTop = convertAmount($widget["super_donater_sum"], $this->config["payment_info"]["default_currency"], "USD");

        if ($dollarSum >= $dollarSumTop) {
            sendEmail($_SESSION["user_email"] ?? $_SESSION["payment_email"], "donate-category", "Sertificate", $emailTemplate);
            $this->db->insert("top_donaters", [
                "user_id" => $user_id,
                "transaction_id" => $data["id"],
            ]);
        }

        if (empty($user_id)) {
            $isSuccessParam = false;
            if ($settings["redirect_to_registration"]) {
                $defaultRedirect = "/registration?status=success#{$settings["group_field"]}";
            }
        }

        return [
            "isSuccessParam" => $isSuccessParam,
            "defaultRedirect" => $defaultRedirect,
        ];
    }

    public function sale($eventData, $meta)
    {
        $isSuccessParam = true;
        $defaultRedirect = "";

        $user_id = $eventData["user_id"];
        $settings = $eventData["settings"];
        $emailTemplate = $eventData["emailTemplate"];

        $this->db->update("user_applications", [
            "payed_status" => "paid",
            "json_data" => json_encode([
                "transaction_id" => $_GET["session_id"]
            ])
        ], ["user_id" => $user_id]);

        $user = $this->db->get("users", "*", ["id" => $user_id]) ?? [];

        sendEmail($_SESSION["user_email"] ?? $_SESSION["payment_email"], "subscription-category", "Successfully payed subscription", [
            "user" => $user,
            "email" => $_SESSION["user_email"] ?? $_SESSION["payment_email"]
        ], $emailTemplate);

        if (empty($user_id)) {
            $isSuccessParam = false;
            if ($settings["redirect_to_registration"]) {
                $defaultRedirect = "/registration?status=success#{$settings["group_field"]}";
            }
        }

        return [
            "isSuccessParam" => $isSuccessParam,
            "defaultRedirect" => $defaultRedirect,
        ];
    }

    public function subscription($eventData, $meta)
    {
        $isSuccessParam = true;

        $data = $eventData["data"];
        $widget = $eventData["widget"];
        $user_id = $eventData["user_id"];
        $settings = $eventData["settings"];
        $emailTemplate = $eventData["emailTemplate"];
        $defaultRedirect = $settings["success_url"];

        $subscription = $this->db->get("subscriptions", "*", ["widget_id" => $widget["id"]]);

        $userSubscription = $this->db->get("user_subscriptions", "*", [
            "transaction_id" => $data["transaction_id"]
        ]);

        if (empty($user_id)) {
            $this->db->update("user_subscriptions", [
                "status" => "active"
            ], ["id" => $userSubscription["id"]]);

            $domain = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'mds-cms';
            $uniqueLink = "$domain/registration?subs_uniq_id={$userSubscription['uniq_id']}#{$settings["group_field"]}";

            if ($settings["redirect_to_registration"]) {
                $defaultRedirect = "/registration?subs_uniq_id={$userSubscription['uniq_id']}#{$settings["group_field"]}";
            }

            $isSuccessParam = false;

            sendEmail($userSubscription["email"], "subscription-buy-category", "Successfully payed subscription", [
                "subscriptionName" => $subscription["name"],
                "subscriptionPrice" => $widget["price"],
                "currency" => $data["currency"],
                "registrationUniqueLink" => $uniqueLink,
            ], $emailTemplate);

        } else {
            $existsSubscription = $this->db->get("user_subscriptions", "*", ["user_id" => $user_id, "status" => "active"]);
            if ($existsSubscription) {
                $this->db->delete("user_subscriptions", ["user_id" => $user_id]);
            }
            $this->db->update("user_subscriptions", [
                "status" => "active",
                "user_id" => $user_id
            ], ["id" => $userSubscription["id"]]);
        }

        return [
            "isSuccessParam" => $isSuccessParam,
            "defaultRedirect" => $defaultRedirect,
        ];

    }

    public function successPrePayment($eventData, $meta)
    {
        global $user_id;

        $amount = $eventData["amount"];
        $currency = $eventData["currency"];
        $status = $eventData["status"];
        $pdfUrl = $eventData["pdfUrl"];

        updateTransactionStatus($_GET["session_id"], $status);

        $this->db->update("transactions", [
            "pdf_url" => $pdfUrl,
            "sum" => $amount,
        ], ["transaction_id" => $_GET["session_id"]]);

        $transactionId = $this->db->get("transactions", "id", ["transaction_id" => $_GET["session_id"]]);

        $transaction = $this->db->get("transactions", "*", ["id" => $transactionId]);

        $reward_percentage = $this->config["referral_reward_percentage"] == "" ? 0 : $this->config["referral_reward_percentage"];
        $referralFixSum = convertAmount($this->config["referral_fix_sum"], $this->config["payment_info"]["default_currency"], $currency);

        $referrer = $this->db->get("users", "*", ["id" => $user_id]);
        if (!empty($referrer)) {
            $refSettings = $this->db->get("referral_settings", "*", ["object_type" => "groups", "object_id" => $this->db->get("users", "group", ["id" => $referrer["referrer_id"]])]);
            if ($refSettings["discount_sum"] != "0.00") {
                $referralFixSum = convertAmount($refSettings["discount_sum"], $this->config["payment_info"]["default_currency"], $currency);
            } else if ($refSettings["discount_percent"] != "0.00") {
                $reward_percentage = $refSettings["discount_percent"];
            }
        }

        $reward_amount = 0;
        if (!empty($reward_percentage)) {
            $reward_amount = (int)$amount * ($reward_percentage / 100);
        } else if (!empty($referralFixSum)) {
            $reward_amount = convertAmount($referralFixSum, strtoupper($currency), $this->config["payment_info"]["default_currency"]);
        }

        if (!empty($referrer["referrer_id"])) {
            $this->db->insert("referral_rewards", [
                "referrer_id" => $referrer["referrer_id"],
                "referred_user_id" => $user_id,
                "transaction_id" => $transactionId,
                "reward_amount" => (string)convertAmount($reward_amount, strtoupper($currency), $this->config["payment_info"]["default_currency"]) ?? 0,
                "reward_percentage" => $reward_percentage,
            ]);

            deposit(strtoupper($currency), $reward_amount, $referrer["referrer_id"]);
        }

        return [
          "transaction" => $transaction,
        ];

    }

}