using System;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Platnosci.Models;
using Platnosci.Core.Linq;
using Platnosci.Core.Interface;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Threading;
using System.Data.Linq;
using System.Web.Configuration;
using System.Web.Routing;

namespace Platnosci.Controllers
{
    
    [Authorize]
    public class PlatnoscController : Controller
    {
        public const string ISPAID = "payment_deposited";       //transakcja potwierdzona do rozliczenia
        private readonly IRepository<vPlatnosciEcard> _repVPayment;       
        private IRepository<PlatnosciEcard> _repPayment;
        private readonly IRepository<PotwierdzeniaEcard> _repConfirm;
        private ITranslate _t;
        private FunkcjePlatnosci _func;
              
        public PlatnoscController()
        {
            _repVPayment = new Repository<vPlatnosciEcard>(new DataContext1());
            _repPayment = new Repository<PlatnosciEcard>(new DataContext1());
            _repConfirm = new Repository<PotwierdzeniaEcard>(new DataContext1());
            _func = new FunkcjePlatnosci();
            _t = new Translate();         
        }
        public PlatnoscController(IRepository<vPlatnosciEcard> repVPayment, IRepository<PlatnosciEcard> repPayment, IRepository<PotwierdzeniaEcard> repConfirm, ITranslate translate)
        {
            _repVPayment = repVPayment;
            _repPayment = repPayment;
            _repConfirm = repConfirm;
            _func = new FunkcjePlatnosci();
            _t = translate;
        }
        public ActionResult Show(string id, string language)
        {
            language = _func.setLanguage(language);
            int id1 = ConvertId(id);

            vPlatnosciEcard platnosc = _repVPayment.Find(p => p.ID_faktury == id1).SingleOrDefault();
            if (!String.IsNullOrEmpty(Iserror(platnosc).error)) return View("Error1", Iserror(platnosc));

            string kwota = "";
            kwota = _func.BruttoToString(platnosc.Brutto, platnosc.waluta_brutto, platnosc.waluta_miano);
            var payer = InitPayer("", "", platnosc.ID_faktury);
            var invoiceDeatailsViewData = InitInvoiceDetailsViewData(platnosc, payer, "", kwota);  

            var tablica_potwierdzenia = _repConfirm.FindItemsByIdFaktury(id1);
            if (tablica_potwierdzenia.Count > 0) //platnosc za fakture zostala uregulowana
            {
                string data_zaplaty = String.Format("{0:dd-MM-yyyy}", tablica_potwierdzenia[0].AUTHTIME);
                invoiceDeatailsViewData.info = String.Format(_t.TranslateStr("tlumaczenia","zaplacono"), platnosc.Faktura_Numer, data_zaplaty);
                invoiceDeatailsViewData.termin = data_zaplaty;
                return View("Paid", invoiceDeatailsViewData);
            }       
            return View(invoiceDeatailsViewData);            
        }        
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Show(Payer payer, string language)
        {
            language = _func.setLanguage(language);
            vPlatnosciEcard platnosc = _repVPayment.Find(p => p.ID_faktury == payer.Id_faktury).SingleOrDefault();
            if (!String.IsNullOrEmpty(Iserror(platnosc).error)) return View("Error1", Iserror(platnosc));
            
            if (String.IsNullOrEmpty(payer.FirstName))
            {
                ModelState.AddModelError("Payer.FirstName", _t.TranslateStr("tlumaczenia", "err_imieWK"));
            }
            if (String.IsNullOrEmpty(payer.LastName))
            {
                ModelState.AddModelError("Payer.LastName", _t.TranslateStr("tlumaczenia", "err_nazwiskoWK"));
            }
            if (ModelState.IsValid == false)
            {
                string kwota = "";
                kwota = _func.BruttoToString(platnosc.Brutto, platnosc.waluta_brutto, platnosc.waluta_miano); 
                var viewData = InitInvoiceDetailsViewData(platnosc, payer, "", kwota );
                return View("Show",viewData);
            } 
            if (payer != null)
            {                
                System.Diagnostics.Debug.WriteLine("PlatnosciController:Show");
                return RedirectToAction("Merchant", "Merchant", payer);
            }                
            else return View("Error");
        }
        public ActionResult Ok(string id, string language)
        {
            language = _func.setLanguage(language);
            int id1 = ConvertId(id);
            vPlatnosciEcard platnosc = _repVPayment.Find(p => p.ID_faktury == id1).SingleOrDefault();
            if (!String.IsNullOrEmpty(Iserror(platnosc).error)) return View("Error1", Iserror(platnosc));            
            
            var invoiceDeatailsViewData = InitInvoiceDetailsViewData(platnosc, null, "" , "");
            return View(invoiceDeatailsViewData);
        }
        public ActionResult Fail(string id, string language)
        {
            language = _func.setLanguage(language);
            int id1 = ConvertId(id);
            vPlatnosciEcard platnosc = _repVPayment.Find(p => p.ID_faktury == id1).SingleOrDefault();
            if (!String.IsNullOrEmpty(Iserror(platnosc).error)) return View("Error1", Iserror(platnosc));
            
            var invoiceDeatailsViewData = InitInvoiceDetailsViewData(platnosc, null, "", "");
            return View(invoiceDeatailsViewData);
        }
        public ActionResult Form()
        {
            return View();
        }
        public ActionResult Status()
        {
            string CURRENTSTATE = "";
            int ORDERNUMBER = 0;
            
            PotwierdzeniaEcard potwierdzenie = new PotwierdzeniaEcard();
            var content = new ContentResult();
            try
            {
                if (!String.IsNullOrEmpty(Request.Form["APPROVALCODE"])) potwierdzenie.APPROVALCODE = Request.Form["APPROVALCODE"];
                if (!String.IsNullOrEmpty(Request.Form["AUTHTIME"])) potwierdzenie.AUTHTIME = Convert.ToDateTime(Request.Form["AUTHTIME"]);
                if (!String.IsNullOrEmpty(Request.Form["BIN"])) potwierdzenie.BIN = Request.Form["BIN"];
                if (!String.IsNullOrEmpty(Request.Form["COMMTYPE"])) potwierdzenie.COMMTYPE = Request.Form["COMMTYPE"];
                if (!String.IsNullOrEmpty(Request.Form["CURRENTSTATE"]))
                {
                    CURRENTSTATE = Request.Form["CURRENTSTATE"];
                    potwierdzenie.CURRENTSTATE = CURRENTSTATE;
                }
                if (!String.IsNullOrEmpty(Request.Form["DATATRANSMISJI"])) potwierdzenie.DATATRANSMISJI = Convert.ToDateTime(Request.Form["DATATRANSMISJI"]);
                if (!String.IsNullOrEmpty(Request.Form["EVENTTYPE"])) potwierdzenie.EVENTTYPE = Convert.ToBoolean(Request.Form["EVENTTYPE"]);
                if (!String.IsNullOrEmpty(Request.Form["MERCHANTNUMBER"])) potwierdzenie.MERCHANTNUMBER = Request.Form["MERCHANTNUMBER"];
                if (!String.IsNullOrEmpty(Request.Form["ORDERNUMBER"]))
                {
                    ORDERNUMBER = Convert.ToInt32(Request.Form["ORDERNUMBER"]);
                    potwierdzenie.ORDERNUMBER = ORDERNUMBER;
                }
                if (!String.IsNullOrEmpty(Request.Form["PAYMENTNUMBER"])) potwierdzenie.PAYMENTNUMBER = Convert.ToBoolean(Request.Form["PAYMENTNUMBER"]);
                if (!String.IsNullOrEmpty(Request.Form["PAYMENTTYPE"])) potwierdzenie.PAYMENTTYPE = Convert.ToBoolean(Request.Form["PAYMENTTYPE"]);
                if (!String.IsNullOrEmpty(Request.Form["PREVIOUSSTATE"])) potwierdzenie.PREVIOUSSTATE = Request.Form["PREVIOUSSTATE"];
                if (!String.IsNullOrEmpty(Request.Form["TYPE"])) potwierdzenie.TYPE = Request.Form["TYPE"];
                if (!String.IsNullOrEmpty(Request.Form["VALIDATIONCODE"])) potwierdzenie.VALIDATIONCODE = Request.Form["VALIDATIONCODE"];
                if (!String.IsNullOrEmpty(Request.Form["WITHCVC"])) potwierdzenie.WITHCVC = Request.Form["WITHCVC"];

                _repConfirm.Insert(potwierdzenie);
                UpdateStatus(ORDERNUMBER, CURRENTSTATE);
                content.Content = "OK";
            }
            catch(Exception ex)
            {
                content.Content = "NOTOK " + ex.Message + " " + ex.GetType();
            }       
            
            return content;
        }
        private Payer InitPayer(string FirstName, string LastName, int Id_faktury)
        {
            Payer payer = new Payer();
            payer.FirstName = "";
            payer.LastName = "";
            payer.Id_faktury = Id_faktury;
            return payer;
        }
        private InvoiceDetailsViewData InitInvoiceDetailsViewData(vPlatnosciEcard platnosc, Payer payer, string status, string brutto )
        {
            var invoiceDeatailsViewData = new InvoiceDetailsViewData();
            invoiceDeatailsViewData.vPlatnosciEcard = platnosc;
            invoiceDeatailsViewData.Payer = payer;
            invoiceDeatailsViewData.Status = status;
            invoiceDeatailsViewData.brutto = brutto;
            return invoiceDeatailsViewData;
        }
        public int ConvertId(string id)
        {
            int id1 = 0;
            try
            {
                id1 = (id != null) ? Convert.ToInt32(id) : 0;
            }
            catch
            {
            }
            return id1;
        }
        public ErrorViewData Iserror(vPlatnosciEcard platnosc)
        {
            string errortxt = "";
            if (platnosc == null) errortxt = _t.TranslateStr("tlumaczenia", "brakdanych");
            else if (!_func.UserIdentity(platnosc, HttpContext.User.Identity.Name)) errortxt = _t.TranslateStr("tlumaczenia","weryfikacja");
            ErrorViewData errorViewData = _func.InitErrorViewData(errortxt);
            return errorViewData;
        }
        public void UpdateStatus(int ordernumber, string currentstate)
        {
            PlatnosciEcard platnosc = _repPayment.Find(p => p.ORDERNUMBER == ordernumber).SingleOrDefault();
            if (platnosc != null && currentstate == ISPAID)
            {
                platnosc.Status = true;
                platnosc.Status_data = DateTime.Now;
                _repPayment.SubmitChanges();
                
                System.Diagnostics.Debug.WriteLine("IsUpdate");
            }
        }
        public IRepository<vPlatnosciEcard> getRepVPayment()
        {
            return this._repVPayment;
        }
        public IRepository<PlatnosciEcard> getRepPayment()
        {
            return this._repPayment;
        }
        public IRepository<PotwierdzeniaEcard> getRepConfirm()
        {
            return this._repConfirm;
        }   
    }
}
