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;

namespace Platnosci.Controllers
{
    [Authorize]
    public class PlatnoscController : Controller
    {
        private readonly PlatnosciDataContext _context;
        private readonly IDataContext _context1;
        private readonly IRepository<PotwierdzeniaEcard> _rep;
        private readonly IRep<PotwierdzeniaEcard> _repository;
        private FunkcjePlatnosci _func;


        public PlatnoscController()
        {
            _context = new PlatnosciDataContext();
            _rep = new Repository<PotwierdzeniaEcard>(new DataContext1()); 
            _func = new FunkcjePlatnosci();
        }
        public PlatnoscController(IDataContext datacontext){
            _rep = new Repository<PotwierdzeniaEcard>(datacontext);
            _context1 = datacontext;
        }
        public ActionResult Show(string id, string language)
        {
            language = _func.setLanguage(language);
            string jezyk = Thread.CurrentThread.CurrentCulture.Name.ToString();
            int id1 = 0;
            try
            {
                id1 = (id != null) ? Convert.ToInt32(id) : 0;
            }
            catch
            {
            }
           
            vPlatnosciEcard platnosc = _rep.FindInvoiceById(id1).SingleOrDefault();
            //sprawdzamy czy numer faktury dotyczy zalogowanego usera
            ErrorViewData errorViewData = new ErrorViewData();
            if (platnosc == null)
            {
               errorViewData.error = HttpContext.GetGlobalResourceObject("tlumaczenia", "brakdanych").ToString();
               return View("Error1", errorViewData);                
            }
            else if (!_func.UserIdentity(platnosc, ControllerContext.HttpContext.User.Identity.Name))
            {
                errorViewData.error = HttpContext.GetGlobalResourceObject("tlumaczenia", "weryfikacja").ToString();
                return View("Error1", errorViewData);
            }
            
            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(HttpContext.GetGlobalResourceObject("tlumaczenia", "zaplacono").ToString(), 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);
            string userName = ControllerContext.HttpContext.User.Identity.Name;
            int id1 = 0;
            try
            {
                id1 = (payer.Id_faktury != null) ? Convert.ToInt32(payer.Id_faktury) : 0;
            }
            catch
            {
            }
            vPlatnosciEcard platnosc = _rep.FindInvoiceById(id1).SingleOrDefault();
            ErrorViewData errorViewData = new ErrorViewData();
            if (platnosc == null)
            {
                errorViewData.error = HttpContext.GetGlobalResourceObject("tlumaczenia", "brakdanych").ToString();
                return View("Error1", errorViewData);
            }
            else if (!_func.UserIdentity(platnosc, ControllerContext.HttpContext.User.Identity.Name))
            {
                errorViewData.error = HttpContext.GetGlobalResourceObject("tlumaczenia", "weryfikacja").ToString();
                return View("Error1", errorViewData);  
            }

            if (String.IsNullOrEmpty(payer.FirstName))
            {
                string err_imieWK = HttpContext.GetGlobalResourceObject("tlumaczenia", "err_imieWK").ToString();
                ModelState.AddModelError("Payer.FirstName", err_imieWK);
            }
            if (String.IsNullOrEmpty(payer.LastName))
            {
                string err_nazwiskoWK = HttpContext.GetGlobalResourceObject("tlumaczenia", "err_nazwiskoWK").ToString();
                ModelState.AddModelError("Payer.LastName", 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)
                return RedirectToAction("Merchant", "Merchant", payer);
            else return View("Error");
        }
        public ActionResult Potwierdzenie(string id, string status, string language)
        {
            language = _func.setLanguage(language);

            int id1 = 0;
            try
            {
                id1 = (id != null) ? Convert.ToInt32(id) : 0;
            }
            catch
            {
                //id1=0 -> error type =  platnoscIsNotExist;
            }
            vPlatnosciEcard platnosc = _rep.FindInvoiceById(id1).SingleOrDefault();
            ErrorViewData errorViewData = new ErrorViewData();
            if (platnosc == null)
            {
                errorViewData.error = HttpContext.GetGlobalResourceObject("tlumaczenia", "faktura_error").ToString();
                return View("Error1", errorViewData);
            }
            else if (!_func.UserIdentity(platnosc, ControllerContext.HttpContext.User.Identity.Name))
            {
                errorViewData.error = HttpContext.GetGlobalResourceObject("tlumaczenia", "weryfikacja").ToString();
                return View("Error1", errorViewData);
            }
            var invoiceDeatailsViewData = InitInvoiceDetailsViewData(platnosc, null, status, "" );
            return View(invoiceDeatailsViewData);
        }
        public ActionResult Status()
        {
            if (string.IsNullOrEmpty(Request.Form["MERCHANTNUMBER"]))
                throw new ArgumentException("MERCHANTNUMBER");

            //TODO: validate the Form

            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);
            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;
        }
               
    }
}
