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 readonly IRepository<PlatnosciEcard> _repPayment;
        private readonly IRepository<PotwierdzeniaEcard> _repConfirm;       
        private FunkcjePlatnosci _func;
        private string weryfikacja;
        private string brakdanych;
        private string zaplacono;
        private string err_imie;
        private string err_nazwisko;
        private int test = 0;
       
        public PlatnoscController()
        {
            _repVPayment = new Repository<vPlatnosciEcard>(new DataContext1());
            _repPayment = new Repository<PlatnosciEcard>(new DataContext1());
            _repConfirm = new Repository<PotwierdzeniaEcard>(new DataContext1());
            _func = new FunkcjePlatnosci();                      
        }
        public PlatnoscController(IRepository<vPlatnosciEcard> repVPayment, IRepository<PlatnosciEcard> repPayment, IRepository<PotwierdzeniaEcard> repConfirm, int czy_test)
        {
            _repVPayment = repVPayment;
            _repPayment = repPayment;
            _repConfirm = repConfirm;
            _func = new FunkcjePlatnosci();
            test = czy_test;
        }
        public ActionResult Show(string id, string language)
        {
            language = _func.setLanguage(language);
            ustawTlumaczenia(test);
            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(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);
            ustawTlumaczenia(test);
            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", 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("PlatnosciController:Show");
                return RedirectToAction("Merchant", "Merchant", payer);
            }                
            else return View("Error");
        }
        public ActionResult Ok(string id, string language)
        {
            language = _func.setLanguage(language);
            ustawTlumaczenia(test);
            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);
            ustawTlumaczenia(test);
            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 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;

            _repConfirm.Insert(potwierdzenie);
            UpdateStatus(ORDERNUMBER, CURRENTSTATE);
            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;
        }
        private void ustawTlumaczenia(int test) 
        {
            if (test == 0) 
            {
                weryfikacja = Resources.tlumaczenia.weryfikacja.ToString();
                brakdanych = Resources.tlumaczenia.brakdanych.ToString();
                zaplacono = Resources.tlumaczenia.zaplacono.ToString();
                err_imie = Resources.tlumaczenia.err_imieWK.ToString();
                err_nazwisko = Resources.tlumaczenia.err_nazwiskoWK.ToString();
            }
        } 
        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)
        {
            string errortxt = "";
            if (platnosc == null) errortxt = brakdanych;
            else if (!_func.UserIdentity(platnosc, HttpContext.User.Identity.Name)) errortxt = 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");
            }
        }               
    }
}
