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 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;
        private int test = 0;
       
        public PlatnoscController()
        {
            _context = new PlatnosciDataContext();
            _rep = new Repository<PotwierdzeniaEcard>(new DataContext1());
            _repPl = new Repository<PlatnosciEcard>(new DataContext1());
            _func = new FunkcjePlatnosci();
                      
        }
        public PlatnoscController(IDataContext datacontext, int czy_test)
        {
            _rep = new Repository<PotwierdzeniaEcard>(datacontext);
            _repPl = new Repository<PlatnosciEcard>(datacontext);
            _context1 = datacontext;
            _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 = _rep.FindInvoiceById(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 = _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);
                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 = _rep.FindInvoiceById(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 = _rep.FindInvoiceById(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 = _rep.FindInvoiceById(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;

            _rep.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 = _repPl.FindOne(ordernumber);
            if (platnosc != null && currentstate == ISPAID)
            {
                platnosc.Status = true;
                platnosc.Status_data = DateTime.Now;
                _repPl.SubmitChanges();
                
                System.Diagnostics.Debug.WriteLine("IsUpdate");
            }
        }               
    }
}
