using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Data.SqlClient;
using System.Threading;
using System.Globalization;

public partial class _Default : System.Web.UI.Page
{
    protected override void InitializeCulture()
    {
        if (Session["culture"] != null)
        {
            UICulture = Session["culture"].ToString();
            Culture = Session["culture"].ToString();

            Thread.CurrentThread.CurrentCulture =
              CultureInfo.CreateSpecificCulture(Session["culture"].ToString());
            Thread.CurrentThread.CurrentUICulture =
              new CultureInfo(Session["culture"].ToString());
        }
        base.InitializeCulture();
    }

    protected string wartoscNaString(SqlDataReader reader, int i, string rodzajZmiennej)
    {
        string wartosc = "";
        if (rodzajZmiennej == "string")
        {
            try
            {
                if (!reader[i].Equals(System.DBNull.Value)) { wartosc = (string)reader[i]; };
            }
            catch (System.NullReferenceException err)
            {
                wartosc = "Error: " + err.ToString();
            }
            return wartosc;
        }
        if (rodzajZmiennej == "DateTime")
        {
            DateTime data;
            try
            {
                if (!reader[i].Equals(System.DBNull.Value))
                {
                    data = (DateTime)reader[i];
                    wartosc = data.ToShortDateString();
                }

            }
            catch (System.NullReferenceException err)
            {
                wartosc = "Error: " + err.ToString();
            }
        }
        if (rodzajZmiennej == "double")
        {
            double liczba;
            try
            {
                if (!reader[i].Equals(System.DBNull.Value))
                {
                    liczba = (double)reader[i];
                    wartosc = liczba.ToString();
                }

            }
            catch (System.NullReferenceException err)
            {
                wartosc = "Error: " + err.ToString();
            }
        }
        return wartosc;

    }

    protected string przeliczNaGrosze(SqlDataReader reader, int i)
    {
        string grosze = "";
        double dGrosze;
        try
        {
            if (!reader[i].Equals(System.DBNull.Value))
            {
                dGrosze = (double)reader[i];
                dGrosze = dGrosze * 100;
                grosze = dGrosze.ToString();
            }

        }
        catch (System.NullReferenceException err)
        {
            grosze = "Error: " + err.ToString();
        }
        return grosze;
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            string connString = ConfigurationManager.ConnectionStrings["BazaReklamConn"].ConnectionString;
            string cmdText = "SELECT [ID Reklamy], FirstName, LastName, Address, PostalCode, City, State, Country, [Faktura Numer], Nabywca_nip, Brutto, [Faktura Data Wystawienia], Termin_zaplaty, Sposob_zaplaty, ID_faktury, [Imię], Nazwisko, ulica, kod, miasto, telefon, fax, waluta_brutto, waluta_miano, SystemKsiegowyId FROM dbo.vDanePlatnosciEcard WHERE nip=@nip AND [Faktura Numer]=@nrFaktury";
            string nip = (string)Session["nip"];
            string nrZlec = (string)Session["nrFaktury"];
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand(cmdText, conn);
                cmd.Parameters.Add("@nip", SqlDbType.NVarChar, 50).Value = nip;
                cmd.Parameters.Add("@nrFaktury", SqlDbType.NVarChar, 20).Value = nrZlec;

                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                reader.Read();

                // formaPlatnosci i waluta                
                string formaPlatnosci = wartoscNaString(reader, 13, "string");
                string walBrutto = wartoscNaString(reader, 22, "double");
                string walMiano = wartoscNaString(reader, 23, "string");
                string systemKsiegowy = reader.GetByte(24).ToString();
                if (walMiano != "" && walBrutto != "")
                {
                    WyborWaluty.Enabled = true;
                    ArrayList values = new ArrayList();
                    values.Add("PLN");
                    values.Add(walMiano);
                    WyborWaluty.DataSource = values;
                    WyborWaluty.DataBind();                                        
                }
                formaPlatnosci = "karta";
                // Czy faktura jest zapłacona?
                /*string formaPlatnosci = "";
                try
                {
                    if (!reader[13].Equals(System.DBNull.Value)) { formaPlatnosci = (string)reader[13]; };
                }
                catch (System.NullReferenceException err)
                {
                    formaPlatnosci = "Error: " + err.ToString();
                }*/
                if (formaPlatnosci == "karta")
                {
                    FormaPlatnosci = "karta";

                    string firstName = wartoscNaString(reader, 1, "string");
                    string lastName = wartoscNaString(reader, 2, "string");
                    string adres = wartoscNaString(reader, 3, "string");
                    string kod = wartoscNaString(reader, 4, "string");
                    string miasto = wartoscNaString(reader, 5, "string");
                    string tNIP = wartoscNaString(reader, 9, "string");
                    string tNrFaktury = wartoscNaString(reader, 8, "string");
                    Session["NrFaktury"] = tNrFaktury;
                    string tDataWystawienia = wartoscNaString(reader, 11, "DateTime");
                    string tTerminPlatnosci = wartoscNaString(reader, 12, "DateTime");
                    string tBrutto = wartoscNaString(reader, 10, "double");
                    // Amount
                    string AmountPLN = przeliczNaGrosze(reader, 10);
                    string AmountWaluta = przeliczNaGrosze(reader, 22);
                    // tIDFaktury
                    string tIDFaktury = "";
                    int iIDFaktury;
                    try
                    {
                        if (!reader[14].Equals(System.DBNull.Value))
                        {
                            iIDFaktury = (int)reader[14];
                            tIDFaktury = iIDFaktury.ToString();
                        }

                    }
                    catch (System.NullReferenceException err)
                    {
                        tIDFaktury = "Error: " + err.ToString();
                    }

                    string ImieHandlowca = wartoscNaString(reader, 15, "string");
                    string NazwiskoHandlowca = wartoscNaString(reader, 16, "string");
                    string AdresBiuraUlica = wartoscNaString(reader, 17, "string");
                    string AdresBiuraKod = wartoscNaString(reader, 18, "string");
                    string AdresBiuraMiasto = wartoscNaString(reader, 19, "string");
                    string AdresBiuraTelefony = wartoscNaString(reader, 20, "string");
                    string WalutaBrutto = wartoscNaString(reader, 22, "double");
                    string WalutaMiano = wartoscNaString(reader, 23, "string");

                    // ------------- Ustawienie zmiennych -----------------------
                    kwotaPLN = tBrutto;
                    kwotaWaluta = WalutaBrutto;
                    kwotaGroszePLN = AmountPLN;
                    kwotaGroszeWaluta = AmountWaluta;
                    // ------------ Dane do wyświetlenia ------------------------

                    // --------- Nazwa
                    string nazwa = "";
                    if (firstName == "")
                    {
                        nazwa = lastName;
                    }
                    else
                    {
                        nazwa = firstName + " " + lastName;
                    }

                    Nazwa.Text = nazwa;
                    // --------- Adres
                    Adres.Text = adres + ", " + kod + " " + miasto;
                    // --------- NIP
                    NIP.Text = tNIP;
                    // -------- NrFaktury
                    NrFaktury.Text = tNrFaktury;
                    // --------- DataWystawienia
                    DataWystawienia.Text = tDataWystawienia;
                    // --------- TerminPlatnosci
                    TerminPlatnosci.Text = tTerminPlatnosci;

                    //------------- Informacje do kontaktu z handlowcem
                    Handlowiec.Text = ImieHandlowca + " " + NazwiskoHandlowca;
                    BiuroAdres.Text = AdresBiuraUlica + ", " + AdresBiuraKod + " " + AdresBiuraMiasto;
                    BiuroTelefon.Text = AdresBiuraTelefony;

                    // ---------------------- Dane przekazywane do sesji ------------

                    // -------------- ORDERDESCRIPTION
                    string ORDERDESCRIPTION = (string)Session["nrFaktury"];
                    Session["ORDERDESCRIPTION"] = ORDERDESCRIPTION;
                    // ---------------- ORDERNUMBER 
                    string ORDERNUMBER = "1";
                    Session["ORDERNUMBER"] = ORDERNUMBER;
                    // ----------------- SESSIONID
                    string SESSIONID = Session.SessionID;
                    Session["SESSIONID"] = SESSIONID;
                    // ------------- LANGUAGE PL - polski, EN - angielski, DE - niemiecki, FR - francuski, RU - rosyjski
                    string LANGUAGE = "PL";

                    Session["SystemKsiegowy"] = systemKsiegowy;

                    if ((string)Session["CURRENCY"] == "978")
                    {
                        Session["CURRENCY"] = "978";
                        Session["AMOUNT"] = kwotaGroszeWaluta;
                        Brutto.Text = kwotaWaluta + " €";
                        WyborWaluty.SelectedValue = "EUR";
                    }
                    else if ((string)Session["CURRENCY"] == "985")
                    {
                        Session["CURRENCY"] = "985";
                        Session["AMOUNT"] = kwotaGroszePLN;
                        Brutto.Text = kwotaPLN + " zł";
                        WyborWaluty.SelectedValue = "PLN";
                    }
                    //else if ((string)Session["CURRENCY"] == "826")
                    //{
                    //    Session["CURRENCY"] = "826";
                    //    Session["AMOUNT"] = kwotaGroszeWaluta;
                    //    Brutto.Text = kwotaWaluta + " £";
                    //    WyborWaluty.SelectedValue = "GBP";
                    //}
                    else
                    {
                        Session["CURRENCY"] = "985";
                        Session["AMOUNT"] = kwotaGroszePLN;
                        Brutto.Text = kwotaPLN + " zł";
                        WyborWaluty.SelectedValue = "PLN";
                    }
                    if (Thread.CurrentThread.CurrentCulture.Name == "pl-PL")
                    {
                        Session["culture"] = "pl-PL";
                        LANGUAGE = "PL";
                    }
                    else if (Thread.CurrentThread.CurrentCulture.Name == "en-US")
                    {
                        Session["culture"] = "en-US";
                        LANGUAGE = "EN";                        
                    }
                    else if (Thread.CurrentThread.CurrentCulture.Name == "fr-FR")
                    {
                        Session["culture"] = "fr-FR";
                        LANGUAGE = "FR";
                    }
                    else if (Thread.CurrentThread.CurrentCulture.Name == "it-IT")
                    {
                        Session["culture"] = "it-IT";
                        LANGUAGE = "IT";
                    }
                    else if (Thread.CurrentThread.CurrentCulture.Name == "de-DE")
                    {
                        Session["culture"] = "de-DE";
                        LANGUAGE = "DE";
                    }
                    else
                    {
                        Session["culture"] = "en-US";
                        LANGUAGE = "EN";
                    }
                    Session["LANGUAGE"] = LANGUAGE;
                    // ----------------- CHARSET 
                    string CHARSET = "ISO-8859-2";
                    Session["CHARSET"] = CHARSET;
                    // ---------------- COUNTRY 616 - Polska
                    string COUNTRY = "616";
                    Session["COUNTRY"] = COUNTRY;
                    // ---------------- PAYMENTTYPE
                    string PAYMENTTYPE = "CARDS";
                    Session["PAYMENTTYPE"] = PAYMENTTYPE;
                    // --------------- MERCHANTID
                    Session["MERCHANTID"] = Int32.Parse(systemKsiegowy) == 1 ? "170906000" : "171485000";
                    // ---------------- AUTODEPOSIT
                    Session["AUTODEPOSIT"] = "1";
                    // ---------------- IDFAKTURY
                    Session["IDFaktury"] = tIDFaktury;
                }

                else
                {
                    FormaPlatnosci = "";
                }
                reader.Close();
                conn.Close();

            }
        }
        else
        {
            string connString = ConfigurationManager.ConnectionStrings["BazaReklamConn"].ConnectionString;
            string cmdText = "SELECT [ID Reklamy], FirstName, LastName, Address, PostalCode, City, State, Country, [Faktura Numer], Nabywca_nip, Brutto, [Faktura Data Wystawienia], Termin_zaplaty, Sposob_zaplaty, ID_faktury, [Imię], Nazwisko, ulica, kod, miasto, telefon, fax, waluta_brutto, waluta_miano, SystemKsiegowyId FROM dbo.vDanePlatnosciEcard WHERE nip=@nip AND [Faktura Numer]=@nrFaktury";
            string nip = (string)Session["nip"];
            string nrZlec = (string)Session["nrFaktury"];
            using (SqlConnection conn = new SqlConnection(connString))
            {
                SqlCommand cmd = new SqlCommand(cmdText, conn);
                cmd.Parameters.Add("@nip", SqlDbType.NVarChar, 50).Value = nip;
                cmd.Parameters.Add("@nrFaktury", SqlDbType.NVarChar, 20).Value = nrZlec;

                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                reader.Read();

                // Wartości         
                string tBrutto = wartoscNaString(reader, 10, "double");
                string WalutaBrutto = wartoscNaString(reader, 22, "double");
                string AmountPLN = przeliczNaGrosze(reader, 10);
                string AmountWaluta = przeliczNaGrosze(reader, 22);

                // ------------- Ustawienie zmiennych -----------------------
                kwotaPLN = tBrutto;
                kwotaWaluta = WalutaBrutto;
                kwotaGroszePLN = AmountPLN;
                kwotaGroszeWaluta = AmountWaluta;                

                reader.Close();
                conn.Close();                
            }
        }
        
    }

    protected void WyborWaluty_SelectedIndexChanged(object sender, EventArgs e)
    {
        string waluta = WyborWaluty.SelectedItem.Value;
        string kwota = "";        
        if (waluta == "PLN")
        {
            kwota = kwotaPLN + " zł";
            Session["CURRENCY"] = "985";
            Session["AMOUNT"] = kwotaGroszePLN;            
        }
        if (waluta == "EUR")
        {
            kwota = kwotaWaluta + " €";
            Session["CURRENCY"] = "978";
            Session["AMOUNT"] = kwotaGroszeWaluta;            
        }
        //if (waluta == "GBP")
        //{
        //    kwota = kwotaWaluta + " £";
        //    Session["CURRENCY"] = "826";
        //    Session["AMOUNT"] = kwotaGroszeWaluta;            
        //}
        Session["kwotaBrutto"] = kwota;
        Brutto.Text = kwota;         
    }

    protected void PlaceButton_Click(object sender, EventArgs e)
    {
        // ------------------ NAME
        string NAME = ImieTextBox.Text;
        Session["NAME"] = NAME;
        // ------------------ SURNAME
        string SURNAME = NazwiskoTextBox.Text;
        Session["SURNAME"] = SURNAME;
        // -------------- Przekierowanie
        Response.Redirect("Merchant.aspx");
    }

    protected void ZamknijButton_Click(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Server.Transfer("login.aspx");
    }

    private string forma;
    public string FormaPlatnosci
    {
        get
        {
            return forma;
        }
        set
        {
            forma = value;
            if (forma == "karta")
            {
                forma = "karta";
            }
            else
            {
                forma = "";
            }            
        }
    }

    private bool czyWyswietlicWyborWaluty;
    public bool WyswietlicWyborWaluty
    {
        get
        {
            return czyWyswietlicWyborWaluty;
        }
        set
        {
            czyWyswietlicWyborWaluty = value;            
        }
    }    
    
    private string kwotaPLN;
    public string kwotaBruttoPLN
    {
        get
        {
            return kwotaPLN;
        }
        set
        {
            kwotaPLN = value;
            if (kwotaPLN == "") { kwotaPLN = "0"; }
        }
    }

    private string kwotaWaluta;
    public string kwotaBruttoWaluta
    {
        get
        {
            return kwotaWaluta;
        }
        set
        {
            kwotaWaluta = value;
            if (kwotaWaluta == "") { kwotaWaluta = "0"; }
        }
    }

    private string amPLN;
    public string kwotaGroszePLN
    {
        get
        {
            return amPLN;
        }
        set
        {
            amPLN = value;
            if (amPLN == "") { kwotaGroszePLN = "0"; }
        }
    }

    private string amWaluta;
    public string kwotaGroszeWaluta
    {
        get
        {
            return amWaluta;
        }
        set
        {
            amWaluta = value;
            if (amWaluta == "") { kwotaGroszeWaluta = "0"; }
        }
    }

    
}
