<?php

namespace Market\ZodacoBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Market\ZodacoBundle\Paypal;
use Market\ZodacoBundle\Entity\PaypalPayment;
use Market\ZodacoBundle\VNGate;

class PaymentController extends BaseController {

    public function depositAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $error = 0;
        $username = $session->get('username', "");
        $password = $session->get('password', "");

        $check = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if (!$check) {
            $session->clear();
            return $this->redirect($this->generateUrl("login"));
        }

        if ($request->getMethod() == 'POST') {
            $a = new \DateTime();
            $paymentAmount = (int) $request->request->get("deposit", 0);
            $paymentOption = $request->request->get("paymentOption", "paypal");
            $rateMoney = (int) $this->container->getParameter('rateMoney');

            $url = "http://" . $request->getHost();
            switch ($paymentOption) {
                case "baokim":
                    try {
                        $em->getConnection()->beginTransaction();
                        $newPayment = new PaypalPayment();

                        $token = md5($check->getId() . "_" . $newPayment->getId() . "_" . time());

                        $newPayment->setUserId($check->getId());
                        $newPayment->setAmount($paymentAmount * $rateMoney);
                        $newPayment->setToken($token);
                        $newPayment->setPayerId('');
                        $newPayment->setStatus(0);
                        $newPayment->setCreatedAt($a);
                        $newPayment->setUpdatedAt($a);
                        $em->persist($newPayment);
                        $em->flush();

                        $returnURL = $url . $this->generateUrl("_depositBK");

                        $transaction_info = $this->get('translator')->trans('Zodaco Market') . " : " . $check->getUsername() . " " . $this->get('translator')->trans('Make a deposit') . " " . number_format($paymentAmount * $rateMoney);

                        $em->getConnection()->commit();

                        $tax_fee = ($paymentAmount * $rateMoney * 3) / 100;
                        $shipping_fee = 0;

                        VNGate::createRequestUrl($token, $paymentAmount * $rateMoney, $shipping_fee, $tax_fee, $transaction_info, $returnURL, $returnURL, $returnURL);

                        die;
                    } catch (Exception $ex) {
                        $em->getConnection()->rollback();
                        $error = 1;
                    }
                    break;

                case "nganluong":
                    try {
                        $em->getConnection()->beginTransaction();
                        $newPayment = new PaypalPayment();

                        $token = md5($check->getId() . "_" . $newPayment->getId() . "_" . time());
                        $tax_fee = ($paymentAmount * $rateMoney * 3) / 100 + 1000;

                        $newPayment->setUserId($check->getId());
                        $newPayment->setAmount($paymentAmount * $rateMoney);
                        $newPayment->setToken($token);
                        $newPayment->setPayerId('');
                        $newPayment->setStatus(0);
                        $newPayment->setCreatedAt($a);
                        $newPayment->setUpdatedAt($a);
                        $em->persist($newPayment);
                        $em->flush();

                        $returnURL = $url . $this->generateUrl("_depositNL");

                        $transaction_info = $this->get('translator')->trans('Zodaco Market') . " : " . $check->getUsername() . " " . $this->get('translator')->trans('Make a deposit') . " " . number_format($paymentAmount * $rateMoney);

                        $em->getConnection()->commit();

                        VNGate::buildCheckoutUrl($returnURL, $transaction_info, $token, $paymentAmount * $rateMoney + $tax_fee);
                        die;
                    } catch (Exception $ex) {
                        $em->getConnection()->rollback();
                        $error = 1;
                    }
                    break;

                default:
                    $returnURL = $url . $this->generateUrl("_depositSuccess");
                    $cancelURL = $returnURL;
                    $resArray = Paypal::CallShortcutExpressCheckout($paymentAmount, $returnURL, $cancelURL);

                    $ack = strtoupper($resArray["ACK"]);
                    if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
                        $newPayment = new PaypalPayment();
                        $newPayment->setUserId($check->getId());
                        $newPayment->setAmount($paymentAmount);
                        $newPayment->setToken($resArray["TOKEN"]);
                        $newPayment->setPayerId('');
                        $newPayment->setStatus(0);
                        $newPayment->setCreatedAt($a);
                        $newPayment->setUpdatedAt($a);
                        $em->persist($newPayment);
                        $em->flush();
                        Paypal::RedirectToPayPal($resArray["TOKEN"]);
                        die;
                    } else {
                        $error = 1;
                    }
                    break;
            }
        }
        $arrReturn = array('check' => $check, "error" => $error);
        return $this->render('MarketZodacoBundle:Payment:deposit.html.php', $arrReturn);
    }

    public function successNLAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");

        $checkUser = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));

        $transaction_info = $_REQUEST["transaction_info"];
        $order_code = $_REQUEST["order_code"];
        $price = $_REQUEST["price"];
        $payment_id = $_REQUEST["payment_id"];
        $payment_type = $_REQUEST["payment_type"];
        $error_text = $_REQUEST["error_text"];
        $secure_code = $_REQUEST["secure_code"];

        $rateMoney = (int) $this->container->getParameter('rateMoney');
        $error = 0;
        $check1 = VNGate::verifyPaymentUrl($transaction_info, $order_code, $price, $payment_id, $payment_type, $error_text, $secure_code);
        if ($check1) {
            $check = $em->getRepository('MarketZodacoBundle:PaypalPayment')->findOneByToken($order_code);
            if (!$check || $check->getStatus() != 0 || $check->getPayerId() != "") {
                return $this->redirect($this->generateUrl("deposit"));
            }
            if ($payment_type == 1) {
                try {
                    $checkUser = $em->getRepository('MarketZodacoBundle:Users')->findOneById($check->getUserId());
                    if (!$checkUser) {
                        return $this->redirect($this->generateUrl("_homepage"));
                    }
                    $check->setStatus(1);
                    $check->setPayerId($checkUser->getId());
                    $tmp = $checkUser->getMoney() + number_format($check->getAmount() / $rateMoney, 2);
                    $checkUser->setMoney($tmp);
                    $em->persist($checkUser);
                    $em->persist($check);
                    $em->flush();
                } catch (Exception $ex) {
                    $error = 1;
                }
            } else {
                $error = 1;
            }
        } else {
            $error = 1;
        }

        $arrReturn = array(
            'check' => $checkUser, "error" => $error
        );

        return $this->render('MarketZodacoBundle:Payment:success.html.php', $arrReturn);
    }

    public function successBKAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");

        $checkUser = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));

        $arrReturn = array('check' => $checkUser, "error" => 0);

        return $this->render('MarketZodacoBundle:Payment:success.html.php', $arrReturn);
    }

    public function ipnAction(Request $request) {
        $em = $this->getDoctrine()->getManager();

        if ($request->getMethod() == 'POST') {
            $created_on = $_REQUEST["created_on"];
            $customer_address = $_REQUEST["customer_address"];
            $customer_email = $_REQUEST["customer_email"];
            $customer_name = $_REQUEST["customer_name"];
            $customer_phone = $_REQUEST["customer_phone"];
            $fee_amount = $_REQUEST["fee_amount"];
            $merchant_address = $_REQUEST["merchant_address"];
            $merchant_email = $_REQUEST["merchant_email"];
            $merchant_id = $_REQUEST["merchant_id"];
            $merchant_name = $_REQUEST["merchant_name"];
            $merchant_phone = $_REQUEST["merchant_phone"];
            $net_amount = $_REQUEST["net_amount"];
            $order_id = $_REQUEST["order_id"];
            $payment_type = $_REQUEST["payment_type"];
            $total_amount = $_REQUEST["total_amount"];
            $transaction_id = $_REQUEST["transaction_id"];
            $transaction_status = $_REQUEST["transaction_status"];
            $resend = $_REQUEST["resend"];
            $verify_sign = $_REQUEST["verify_sign"];

            $checkData = "created_on=$created_on&customer_address=$customer_address&customer_email=$customer_email&customer_name=$customer_name&customer_phone=$customer_phone&fee_amount=$fee_amount&merchant_address=$merchant_address&merchant_email=$merchant_email&merchant_id=$merchant_id&merchant_name=$merchant_name&merchant_phone=$merchant_phone&net_amount=$net_amount&order_id=$order_id&payment_type=$payment_type&total_amount=$total_amount&transaction_id=$transaction_id&transaction_status=$transaction_status&resend=$resend&verify_sign=$verify_sign";

            $urlIpn = 'https://www.baokim.vn/bpn/verify';
//            $urlIpn = 'http://sandbox.baokim.vn/bpn/verify';
            $getData = trim(VNGate::sendPostRequest($urlIpn, $checkData));
            $rateMoney = (int) $this->container->getParameter('rateMoney');
            if ($getData == 'VERIFIED') {
                $check = $em->getRepository('MarketZodacoBundle:PaypalPayment')->findOneByToken($order_id);
                if ($check && $check->getStatus() != 1) {
                    if ($payment_type == 1 && $transaction_status == 4) {
                        try {
                            $checkUser = $em->getRepository('MarketZodacoBundle:Users')->findOneById($check->getUserId());
                            if ($checkUser) {
                                $check->setStatus(1);
                                $check->setPayerId($checkUser->getId());
                                $tmp = $checkUser->getMoney() + number_format($check->getAmount() * $rateMoney, 2);
                                $checkUser->setMoney($tmp);
                                $em->persist($checkUser);
                                $em->persist($check);
                                $em->flush();
                                echo 1;
                            }
                        } catch (Exception $ex) {
                            
                        }
                    }
                }
            }
        }
        die;
    }

    public function successAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");

        $checkUser = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if (!$checkUser) {
            $session->clear();
            return $this->redirect($this->generateUrl("login"));
        }

        $error = 0;
        $token = isset($_REQUEST["token"]) ? trim($_REQUEST["token"]) : "";
        $PayerID = isset($_REQUEST["PayerID"]) ? trim($_REQUEST["PayerID"]) : "";
        if (!$token || !$PayerID) {
            return $this->redirect($this->generateUrl("deposit"));
        }
        $check = $em->getRepository('MarketZodacoBundle:PaypalPayment')->findOneByToken($token);
        if (!$check || $check->getStatus() != 0 || $check->getPayerId() != "") {
            $error = 1;
        } else {
            $resArray = Paypal::GetShippingDetails($token);
            $ack = strtoupper($resArray["ACK"]);
            if ($ack == "SUCCESS" || $ack == "SUCESSWITHWARNING") {
                $resArray = Paypal::ConfirmPayment($token, $PayerID, $check->getAmount());
                $ack = strtoupper($resArray["ACK"]);
                if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
                    try {
                        $check->setStatus(1);
                        $check->setPayerId($PayerID);

                        $tmp = $checkUser->getMoney();
                        $rate = 1; //(int) $this->container->getParameter('rateMoney');
                        $tmp = $tmp + $rate * $check->getAmount();
                        $checkUser->setMoney($tmp);

                        $em->persist($checkUser);
                        $em->persist($check);
                        $em->flush();
                    } catch (Exception $ex) {
                        $error = 1;
                    }
                } else {
                    $error = 1;
                }
            } else {
                $error = 1;
            }
        }

        $arrReturn = array(
            'check' => $checkUser, "error" => $error
        );
        return $this->render('MarketZodacoBundle:Payment:success.html.php', $arrReturn);
    }

    public function withdrawalAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $session = $request->getSession();
        $username = $session->get('username', "");
        $password = $session->get('password', "");

        $checkUser = $em->getRepository('MarketZodacoBundle:Users')->findOneBy(array("email" => $username, "password" => $password));
        if (!$checkUser) {
            $session->clear();
            return $this->redirect($this->generateUrl("login"));
        }

        $status = 0;
        $error = 0;
        $checkPayout = $em->getRepository('MarketZodacoBundle:Withdrawal')->findOneBy(array('user_id' => $checkUser->getId(), 'status' => 0));
        if ($checkPayout) {
            $status = 1;
        }
        $fee = floatval($this->container->getParameter('feeCashout'));
        $min = floatval($this->container->getParameter('minCashout'));

        if ($request->getMethod() == 'POST') {
            $cash = floatval($request->request->get("amount", 0));
            $email = $request->request->get("email", "");
            $paymentOption = $request->request->get("paymentOption", "paypal");
            if (!in_array($paymentOption, array("paypal", "nganluong", "baokim"))) {
                $paymentOption = "paypal";
            }
            if ($checkUser->getMoney() > 0 && $cash > 0 && $cash >= $min && filter_var($email, FILTER_VALIDATE_EMAIL) && $cash <= $checkUser->getMoney()) {
                if ($checkPayout) {
                    $status = 1;
                } else {
                    try {
                        $net = $cash - round($cash * $fee / 100, 2);
                        $datas = array("email" => $email, "amount" => $cash, "net" => $net, 'method' => $paymentOption);
                        $a = new \DateTime();
                        $new_user = new \Market\ZodacoBundle\Entity\Withdrawal();
                        $new_user->setUsers($checkUser);
                        $new_user->setAmount($net);
                        $new_user->setDatas(json_encode($datas));
                        $new_user->setDateProcess($a);
                        $new_user->setDateRequest($a);
                        $new_user->setStatus(0);
                        $new_user->setCreatedAt($a);
                        $new_user->setUpdatedAt($a);

                        $checkUser->setMoney($checkUser->getMoney() - $cash);
                        $checkUser->setEmailPayment($email);

                        $em->persist($new_user);
                        $em->persist($checkUser);

                        $em->flush();
                        $error = 0;
                        $status = 1;
                    } catch (Exception $ex) {
                        $error = 1;
                    }
                }
            } else {
                $error = 1;
            }
        }

        $list = $em->getRepository('MarketZodacoBundle:Withdrawal')->_getlist($checkUser->getId());
        $arrReturn = array('check' => $checkUser, 'status' => $status, 'error' => $error, 'list' => $list, 'min' => $min, 'fee' => $fee);
        return $this->render('MarketZodacoBundle:Payment:withdrawal.html.php', $arrReturn);
    }

}
