using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using PayPal.PayPalAPIInterfaceService;
using PayPal.PayPalAPIInterfaceService.Model;
using PaypalDirectPayment.Models;

namespace PaypalDirectPayment.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Index(PaypalModel pModel)
        {
            if (ModelState.IsValid)
            {
                pModel.Credentials = "USER=" + pModel.USER + "&PWD=" + pModel.PWD + "&SIGNATURE=" + pModel.SIGNATURE;

                if (pModel.IslemTipi == "Sandbox")
                {
                    pModel.PostAdres = "https://api-3t.sandbox.paypal.com/nvp";
                }
                else if (pModel.IslemTipi == "Live")
                {
                    pModel.PostAdres = "https://api-3t.paypal.com/nvp";
                }

                pModel.ApiVersiyon = "58.0";
                //pModel.IpAdress = Request.ServerVariables["REMOTE_ADDR"];
                pModel.IpAdress = "192.168.2.1";

                pModel.KartBitisTarihi = pModel.ExpDateAy + pModel.ExpDateYil;

                string strNVP = pModel.Credentials + "&METHOD=DoDirectPayment" +
                "&CREDITCARDTYPE=" + pModel.KrediKartTipi +
                "&ACCT=" + pModel.KartNumarasi +
                "&EXPDATE=" + pModel.KartBitisTarihi +
                "&CVV2=" + pModel.Cvv2 +
                "&AMT=" + pModel.Fiyat.Replace(",", ".") +
                "&PAYMENTACTION=Authorization" +
                "&CURRENCYCODE=" + pModel.ParaBirimi +
                "&FIRSTNAME=" + pModel.Isim +
                "&LASTNAME=" + pModel.Soyisim +
                "&IPADDRESS=" + pModel.IpAdress +
                "&STREET=" + pModel.Adres +
                "&CITY=" + pModel.Sehir +
                "&STATE=" + pModel.Sehir +
                "&COUNTRY=" + pModel.Ulke +
                "&ZIP=" + pModel.PostaKodu +
                "&COUNTRYCODE=" + pModel.Ulke +
                "&PAYMENTACTION=Sale" +
                "&VERSION=" + pModel.ApiVersiyon;

                try
                {
                    //Create web request and web response objects, make sure you using the correct server (sandbox/live)
                    HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(pModel.PostAdres);
                    wrWebRequest.Method = "POST";
                    StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
                    requestWriter.Write(strNVP);
                    requestWriter.Close();

                    // Get the response.
                    HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
                    StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());

                    //and read the response
                    string responseData = responseReader.ReadToEnd();
                    responseReader.Close();

                    string result = Server.UrlDecode(responseData);

                    string[] arrResult = result.Split('&');
                    Hashtable htResponse = new Hashtable();
                    string[] responseItemArray;
                    foreach (string responseItem in arrResult)
                    {
                        responseItemArray = responseItem.Split('=');
                        htResponse.Add(responseItemArray[0], responseItemArray[1]);
                    }

                    string strAck = htResponse["ACK"].ToString();

                    if (strAck == "Success" || strAck == "SuccessWithWarning")
                    {
                        string strAmt = htResponse["AMT"].ToString();
                        string strCcy = htResponse["CURRENCYCODE"].ToString();
                        string strTransactionID = htResponse["TRANSACTIONID"].ToString();
                        //ordersDataSource.InsertParameters["TransactionID"].DefaultValue = strTransactionID;

                        string strSuccess = "Çekim İşlemi Başarılı.Çekilen Tutar #" + strAmt + " " + strCcy + "#";
                        ViewBag.successLabel = strSuccess;
                    }
                    else
                    {
                        string strErr = "Hata: " + htResponse["L_LONGMESSAGE0"].ToString();
                        string strErrcode = "Hata Kodu : " + htResponse["L_ERRORCODE0"].ToString();
                        ViewBag.ErrLabel = strErr;
                        ViewBag.errcodeLabel = strErrcode;

                    }
                }
                catch (Exception ex)
                {
                    ViewBag.errcodeLabel = "Hata Oluştu.Hata Kodu : " + ex.Message;
                }

                ViewBag.Success = true;
            }

            return View();
        }

        public ActionResult PaypalExpressCheckout()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult PaypalExpressCheckout(PaypalModel pModel)
        {
            pModel.ApiVersiyon = "109.0";
            pModel.LogoImg = "http://mibilisim.com/Content/themes/Frut/img/logo.png";
            pModel.RETURNURL = "http://localhost:1525/Home/Cevap?success=true";
            pModel.CANCELURL = "http://localhost:1525/Home/Cevap?success=false";

            for (int i = 0; i < 2; i++)
            {
                pModel.UrunDuzenlemeleri += "&L_PAYMENTREQUEST_0_NAME" + i + "=" + pModel.UrunAdi;
                pModel.UrunDuzenlemeleri += "&L_PAYMENTREQUEST_0_NUMBER" + i + "=" + pModel.UrunNumarasi;
                pModel.UrunDuzenlemeleri += "&L_PAYMENTREQUEST_0_DESC" + i + "=" + pModel.UrunAciklama;
                pModel.UrunDuzenlemeleri += "&L_PAYMENTREQUEST_0_AMT" + i + "=" + pModel.Fiyat.Replace(',', '.');
                pModel.UrunDuzenlemeleri += "&L_PAYMENTREQUEST_0_QTY" + i + "=" + pModel.Adet;

                pModel.UrunToplami += Convert.ToDecimal(pModel.Fiyat.Replace('.', ',')) * pModel.Adet;
            }
            pModel.Toplam = pModel.UrunToplami.ToString().Replace(',', '.');

            string gonderilecekVeri = "METHOD=SetExpressCheckout" +
                                      "&VERSION=" + pModel.ApiVersiyon +
                                      "&USER=" + pModel.USER +
                                      "&PWD=" + pModel.PWD +
                                      "&SIGNATURE=" + pModel.SIGNATURE +
                                      "&LOCALECODE=tr_TR" +
                                      "&PAYMENTREQUEST_0_PAYMENTACTION=Sale" +
                                       pModel.UrunDuzenlemeleri +
                                      "&PAYMENTREQUEST_0_ITEMAMT=" + pModel.Toplam +  //Ürün Toplamı
                //"&PAYMENTREQUEST_0_TAXAMT=2.58" + //Vergi
                //"&PAYMENTREQUEST_0_SHIPPINGAMT=3.00" +    //Gönderim 
                //"&PAYMENTREQUEST_0_HANDLINGAMT=2.99" +    //Paketleme
                //"&PAYMENTREQUEST_0_SHIPDISCAMT=-3.00" +   //Gönderim İndirimi
                //"&PAYMENTREQUEST_0_INSURANCEAMT=1.00" +   //Sigorta
                                      "&PAYMENTREQUEST_0_AMT=" + pModel.Toplam +          //Toplam
                                      "&PAYMENTREQUEST_0_CURRENCYCODE=" + pModel.ParaBirimi +
                                      "&ALLOWNOTE=0" +
                                      "&LOGOIMG=" + pModel.LogoImg +
                                      "&CARTBORDERCOLOR=0000CD" +
                                      "&RETURNURL=" + pModel.RETURNURL +
                                      "&CANCELURL=" + pModel.CANCELURL;

            Session["IslemTipi"] = pModel.IslemTipi;
            Session["ParaBirimi"] = pModel.ParaBirimi;
            Session["ToplamTutar"] = pModel.Toplam;

            if (pModel.IslemTipi == "Sandbox")
            {
                pModel.PostAdres = "https://api-3t.sandbox.paypal.com/nvp";
            }
            else if (pModel.IslemTipi == "Live")
            {
                pModel.PostAdres = "https://api-3t.paypal.com/nvp";
            }

            HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(pModel.PostAdres);
            wrWebRequest.Method = "POST";
            StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
            requestWriter.Write(gonderilecekVeri);
            requestWriter.Close();

            // Get the response.
            HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
            StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());

            //and read the response
            string responseData = responseReader.ReadToEnd();
            responseReader.Close();

            string result = Server.UrlDecode(responseData);

            string[] arrResult = result.Split('&');
            Hashtable htResponse = new Hashtable();
            string[] responseItemArray;
            foreach (string responseItem in arrResult)
            {
                responseItemArray = responseItem.Split('=');
                htResponse.Add(responseItemArray[0], responseItemArray[1]);
            }

            string strAck = htResponse["ACK"].ToString();
            string TokenID = htResponse["TOKEN"].ToString();

            if (strAck == "Success" || strAck == "SuccessWithWarning")
            {
                if (pModel.IslemTipi == "Sandbox")
                {
                    pModel.YonlenmeAdresi = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + TokenID;
                }
                else if (pModel.IslemTipi == "Live")
                {
                    pModel.YonlenmeAdresi = "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + TokenID;
                }

                Response.Redirect(pModel.YonlenmeAdresi);
            }
            return View();
        }

        public ActionResult Cevap()
        {
            PaymentDetailsType paymentDetail = new PaymentDetailsType();
            paymentDetail.PaymentAction = (PaymentActionCodeType)EnumUtils.GetValue("Sale", typeof(PaymentActionCodeType));
            paymentDetail.OrderTotal = new BasicAmountType((CurrencyCodeType)EnumUtils.GetValue(Session["ParaBirimi"].ToString(),
                typeof(CurrencyCodeType)), Session["ToplamTutar"].ToString());
            List<PaymentDetailsType> paymentDetails = new List<PaymentDetailsType>();
            paymentDetails.Add(paymentDetail);

            DoExpressCheckoutPaymentRequestType request = new DoExpressCheckoutPaymentRequestType();
            request.Version = "104.0";
            DoExpressCheckoutPaymentRequestDetailsType requestDetails = new DoExpressCheckoutPaymentRequestDetailsType();
            requestDetails.PaymentDetails = paymentDetails;
            requestDetails.Token = Request.QueryString["token"];
            requestDetails.PayerID = Request.QueryString["PayerID"];
            request.DoExpressCheckoutPaymentRequestDetails = requestDetails;

            DoExpressCheckoutPaymentReq wrapper = new DoExpressCheckoutPaymentReq();
            wrapper.DoExpressCheckoutPaymentRequest = request;
            Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
            sdkConfig.Add("mode", Session["IslemTipi"].ToString());
            sdkConfig.Add("account1.apiUsername", "business_api3.mibilisim.com");
            sdkConfig.Add("account1.apiPassword", "KXCNL4NKGXGSQSN6");
            sdkConfig.Add("account1.apiSignature", "AgqQ4gMWKeLg-ZKQ2BniQfIJB3MjApOUsJwR88Uq2io3o6OzjVDM.hjm");
            PayPalAPIInterfaceServiceService s = new PayPalAPIInterfaceServiceService(sdkConfig);
            DoExpressCheckoutPaymentResponseType doECResponse = s.DoExpressCheckoutPayment(wrapper);


            Session["IslemTipi"] = "";
            Session["ParaBirimi"] = "";
            Session["ToplamTutar"] = "";

            return View();
        }

    }
}
