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
    {
        private readonly PlatnosciDataContext _context;
        private readonly IDataContext _context1;
        private readonly IRepository<PotwierdzeniaEcard> _rep;
        private readonly IRepository<PlatnosciEcard> _repPl;
        private FunkcjePlatnosci _func;
        private string weryfikacja = "";
        private string brakdanych = "";
        private string zaplacono = "";
        private string err_imie = "";
        private string err_nazwisko = "";

        protected override void Initialize(RequestContext requestContext)
        {            
            base.Initialize(requestContext);
            weryfikacja = HttpContext.GetGlobalResourceObject("tlumaczenia", "weryfikacja").ToString();
            brakdanych = HttpContext.GetGlobalResourceObject("tlumaczenia", "brakdanych").ToString();
            zaplacono = HttpContext.GetGlobalResourceObject("tlumaczenia", "zaplacono").ToString();
            err_imie = HttpContext.GetGlobalResourceObject("tlumaczenia", "err_imieWK").ToString();
            err_nazwisko = HttpContext.GetGlobalResourceObject("tlumaczenia", "err_nazwiskoWK").ToString();           
        }       

        public PlatnoscController()
        {
            _context = new PlatnosciDataContext();
            _rep = new Repository<PotwierdzeniaEcard>(new DataContext1());
            _repPl = new Repository<PlatnosciEcard>(new DataContext1());
            _func = new FunkcjePlatnosci();
                      
        }
        public PlatnoscController(IDataContext datacontext)
        {
            _rep = new Repository<PotwierdzeniaEcard>(datacontext);
            _repPl = new Repository<PlatnosciEcard>(datacontext);
            _context1 = datacontext;
            _func = new FunkcjePlatnosci();
        }
        public ActionResult Show(string id, string language)
        {
          
            language = _func.setLanguage(language);
            int id1 = ConvertId(id); 

            vPlatnosciEcard platnosc = _rep.FindInvoiceById(id1).SingleOrDefault();
            ErrorViewData errorViewData = new ErrorViewData();
            if (Iserror(platnosc).error != null) return View("Error1", Iserror(platnosc));
            
            var tablica_potwierdzenia = _rep.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);
                errorViewData.error = String.Format(zaplacono, platnosc.Faktura_Numer, data_zaplaty);
                return View("Error1", errorViewData);
            }            
            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);           
            return View(invoiceDeatailsViewData);
        }        
        [Authorize]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Show(Payer payer, string language)
        {
            language = _func.setLanguage(language);

            vPlatnosciEcard platnosc = _rep.FindInvoiceById(payer.Id_faktury).SingleOrDefault();
            if (Iserror(platnosc).error != null) return View("Error1", Iserror(platnosc));
            
            if (String.IsNullOrEmpty(payer.FirstName))
            {
                ModelState.AddModelError("Payer.FirstName", err_imie);
            }
            if (String.IsNullOrEmpty(payer.LastName))
            {
                ModelState.AddModelError("Payer.LastName", err_nazwisko);
            }
            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("P;atnosciController: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 = _rep.FindInvoiceById(id1).SingleOrDefault();
            if (Iserror(platnosc).error != null) 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 = _rep.FindInvoiceById(id1).SingleOrDefault();
            if (Iserror(platnosc).error != null) return View("Error1", Iserror(platnosc));
            
            var invoiceDeatailsViewData = InitInvoiceDetailsViewData(platnosc, null, "", "");
            return View(invoiceDeatailsViewData);
        }
        public ActionResult Potwierdzenie(string status, string id)
        {
            if (status == "ok") return RedirectToAction("Ok", "Platnosc", new {id});
            return RedirectToAction("Fail", "Platnosc", new {id}); 
        }
        public ActionResult Status()
        {
            string MERCHANTNUMBER = Request.Form["MERCHANTNUMBER"];
            int ORDERNUMBER = Convert.ToInt32(Request.Form["ORDERNUMBER"]);
            string COMMTYPE = Request.Form["COMMTYPE"];
            string CURRENTSTATE = Request.Form["CURRENTSTATE"];
            string PREVIOUSSTATE = Request.Form["PREVIOUSSTATE"];
            bool PAYMENTTYPE = Convert.ToBoolean(Request.Form["PAYMENTTYPE"]);
            bool EVENTTYPE = Convert.ToBoolean(Request.Form["EVENTTYPE"]);
            bool PAYMENTNUMBER = Convert.ToBoolean(Request.Form["PAYMENTNUMBER"]);
            string APPROVALCODE = Request.Form["APPROVALCODE"];
            string VALIDATIONCODE = Request.Form["VALIDATIONCODE"];
            string BIN = Request.Form["BIN"];
            DateTime AUTHTIME = Convert.ToDateTime(Request.Form["AUTHTIME"]);
            string TYPE = Request.Form["TYPE"];
            string WITHCVC = Request.Form["WITHCVC"];
            DateTime DATATRANSMISJI = Convert.ToDateTime(Request.Form["DATATRANSMISJI"]);
            
            PotwierdzeniaEcard potwierdzenie = new PotwierdzeniaEcard();
            potwierdzenie.APPROVALCODE = APPROVALCODE;
            potwierdzenie.AUTHTIME = AUTHTIME;
            potwierdzenie.BIN = BIN;
            potwierdzenie.COMMTYPE = COMMTYPE;
            potwierdzenie.CURRENTSTATE = CURRENTSTATE;
            potwierdzenie.DATATRANSMISJI = DATATRANSMISJI;
            potwierdzenie.EVENTTYPE = EVENTTYPE;
            potwierdzenie.MERCHANTNUMBER = MERCHANTNUMBER;
            potwierdzenie.ORDERNUMBER = ORDERNUMBER;
            potwierdzenie.PAYMENTNUMBER = PAYMENTNUMBER;
            potwierdzenie.PAYMENTTYPE = PAYMENTTYPE;
            potwierdzenie.PREVIOUSSTATE = PREVIOUSSTATE;
            potwierdzenie.TYPE = TYPE;
            potwierdzenie.VALIDATIONCODE = VALIDATIONCODE;
            potwierdzenie.WITHCVC = WITHCVC;

            _rep.Insert(potwierdzenie);
            UpdateStatus(ORDERNUMBER, VALIDATIONCODE);
            return View();
        }
        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 void setWeryfikacja(string value)
        {
            this.weryfikacja = value;

        }
        public void setBrakDanych(string value)
        {
            this.brakdanych = value;

        }
        public void setZaplacono(string value)
        {
            this.zaplacono = value;

        }
        public int ConvertId(string id)
        {
            int id1 = 0;
            try
            {
                id1 = (id != null) ? Convert.ToInt32(id) : 0;
            }
            catch
            {
            }
            return id1;
        }
        public ErrorViewData Iserror(vPlatnosciEcard platnosc)
        {
            ErrorViewData errorViewData = new ErrorViewData();
            if (platnosc == null)
            {
                errorViewData.error = brakdanych;
            }
            else if (!_func.UserIdentity(platnosc, HttpContext.User.Identity.Name))
            {
                errorViewData.error = weryfikacja;
            }
            return errorViewData;
        }
        public void UpdateStatus(int ordernumber, string validationcode)
        {
            var platnosc = _repPl.FindOne(i => i.ORDERNUMBER == ordernumber);
            if (platnosc != null && platnosc.Status == true && validationcode == "000")
            {
                platnosc.Status = true;
                platnosc.Status_data = DateTime.Now;
                _repPl.Update(platnosc);
            }
        }               
    }
}
