using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using Baza_Reklam.Classes.Helpers;
using Baza_Reklam.Classes.Interfaces;
using Baza_Reklam.Classes.Model;
using Baza_Reklam.Classes.Repositories;

namespace Baza_Reklam
{
    public partial class ClientsForm : Form, IForm
    {
        private const int Panel1Height = 380;
        private const int splitConteiner1Height = 230;

        //zmienna pomocnicza do kontroli clientsDataGridView_CellLeave
        private bool dodajKlienta;

        //obiekty wykorzytywane przy wyszukiwaniu
        private readonly SqlDataAdapter sqlDataAdapter;
        private readonly SqlCommand command;
        private const string query = "select top 2000 K.* from KLIENCI K ";

        //sigleton
        private static ClientsForm clientsForm;

        public static ClientsForm getClientsForm(MDIBazaReklam parent)
        {
            if (clientsForm == null)
            {
                clientsForm = new ClientsForm(parent);
            }
            return clientsForm;
        }

        private ClientsForm(Form parent)
        {
            InitializeComponent();

            MdiParent = parent;

            //podmiana connstringa
            kL_1TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kL_2TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kL_3TableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kL_KLIENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kLIENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kONTAKTYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            zestawienieFakturTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            rEKLAMATableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            fakturA_DETAILSTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            fAKTURYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            shedulerTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            oFERTY_MAINTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            aGENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kLIENCI_TYTULTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            vIEW_KOREKTYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kontaktTypTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);

            command = new SqlCommand();
            command.CommandType = CommandType.Text;
            command.Connection = conn;

            sqlDataAdapter = new SqlDataAdapter();
            sqlDataAdapter.SelectCommand = command;

            //dodanie obrazkow do drzewka w zakladce KLASYFIKACJA KLIENTA
            ImageList imageList = new ImageList();
            imageList.Images.Add(Properties.Resources.bullet_ball_glass_green);
            imageList.Images.Add(Properties.Resources.bullet_ball_glass_red);
            klasyfikacjaTreeView.ImageList = imageList;
            klasyfikacjaTreeView.ImageIndex = 0;
            klasyfikacjaTreeView.SelectedImageIndex = 1;

            //generuje piersze węzły w drzewie
            generateNodes();

            //ustawia uprawnienia
            uprawnienia();

            //dodaje podpowiedzi do buttonow
            podpowiedzi();
        }

        private void ClientsForm_Load(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Maximized;

            //bez tego zakładki ZAMÓWIENIA i FAKTURY po wzięciu programu do paska i ponownym pokazaniu
            //rozjezdzaja sie...
            zamowieniaSplitContainer.Panel2MinSize = 200;
            fakturySplitContainer.Panel1MinSize = 180;

            DBBindings.bindujAgencje(agencjaToolStripComboBox);
            DBBindings.bindujAgentow(agentToolStripComboBox);
            agencjaToolStripComboBox.SelectedIndexChanged += agencjaToolStripComboBox_SelectedIndexChanged;

            aGENCITableAdapter.Fill(sLOWNIKDataSet.AGENCI);

            //pobiera pierwsze wezly w drzewku z klasyfikacji
            //klasyfikacjaWezlyGlowne();
            DBBindings.dodajKlasyfikacjePoziom1(klasyfikacjaTreeView);

            //SLOWNIKDataSetTableAdapters.LISTA_TYTULOWTableAdapter ta = new SLOWNIKDataSetTableAdapters.LISTA_TYTULOWTableAdapter();
            //ta.Connection.ConnectionString = ConnString.getConnString().Value;
            //tytulyListBox.DataSource = ta.GetData();
            //tytulyListBox.DisplayMember = "SYMB";
            //tytulyListBox.ValueMember = "SYMB";


            kontaktTypTableAdapter.Fill(sLOWNIKDataSet.KontaktTyp);
            cbKontaktTyp.ComboBox.DataSource = sLOWNIKDataSet.KontaktTyp;

            DBBindings.BindKontaktTyp(cbKontaktTyp);

        }

        private void clientsDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int customerId = Int32.Parse(row["CustomerId"].ToString());

                switch (tabs.SelectedTab.Name)
                {
                    case "daneKlientaTab":
                        groupBox1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox2.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox3.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox4.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox5.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        tabControl1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        kLIENCI_TYTULTableAdapter.FillByCustomerId(rEKLAMADataSet.KLIENCI_TYTUL, customerId);
                        break;
                    case "zamowieniaTab":
                        rEKLAMADataSet.REKLAMA.Clear();
                        rEKLAMATableAdapter.FillByCustomerId(rEKLAMADataSet.REKLAMA, customerId);
                        zamDataGridView.Sort(dATAZAMÓWIENIADataGridViewTextBoxColumn, ListSortDirection.Descending);
                        zamDataGridView.Refresh();
                        break;
                    case "fakturyTab":
                        rEKLAMADataSet.FAKTURY.Clear();
                        zestawienieFakturTableAdapter.FillByCustomerID(rEKLAMADataSet.ZestawienieFaktur, customerId);
                        fakturyDataGridView.Refresh();
                        break;
                    case "tabKorekty":
                        rEKLAMADataSet.VIEW_KOREKTY.Clear();
                        vIEW_KOREKTYTableAdapter.FillByCustomerId(rEKLAMADataSet.VIEW_KOREKTY, customerId);
                        gridKorekty.Refresh();
                        break;
                    case "tabAbonamenty":
                        RefreshSubscriptions();
                        break;
                    case "klasyfikacjaTabPage":
                        rEKLAMADataSet.KL_KLIENCI.Clear();
                        kL_KLIENCITableAdapter.ClearBeforeFill = true;
                        kL_KLIENCITableAdapter.FillByCustomerId(rEKLAMADataSet.KL_KLIENCI, customerId);
                        kL_1TableAdapter.Fill(sLOWNIKDataSet.KL_1);
                        kL_2TableAdapter.Fill(sLOWNIKDataSet.KL_2);
                        kL_3TableAdapter.Fill(sLOWNIKDataSet.KL_3);
                        break;
                    case "kontaktyTabPage":
                        rEKLAMADataSet.KONTAKTY.Clear();
                        kONTAKTYTableAdapter.FillByCustomerId(rEKLAMADataSet.KONTAKTY, customerId);
                        groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "osobyDoKontaktuTabPage":
                        rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.Clear();
                        kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.FillByCustomerId(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU, customerId);
                        groupBox6.Enabled = kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "doZalatwienia":
                        rEKLAMADataSet.sheduler.Clear();
                        shedulerTableAdapter.FillByCustomerId(rEKLAMADataSet.sheduler, customerId);
                        groupBox15.Enabled = shedulerBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "ofertyTabPage":
                        rEKLAMADataSet.OFERTY_MAIN.Clear();
                        oFERTY_MAINTableAdapter.FillByCustomerId(rEKLAMADataSet.OFERTY_MAIN, customerId);
                        break;
                    default:
                        break;
                }

                if (((REKLAMADataSet.KLIENCIRow)row.Row).IsCountryNull())
                {
                    countryComboBox.SelectedIndex = -1;
                }

                Cursor = Cursors.Default;
            }
        }


        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (tabs.SelectedTab.Name != "daneKlientaTab")
            {
                zapiszDaneToolStripButton.Enabled = false;
                usunToolStripButton.Enabled = false;
            }
            else
            {
                zapiszDaneToolStripButton.Enabled = true;
                usunToolStripButton.Enabled = true;
            }

            if (kLIENCIBindingSource.Current != null)
            {
                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int customerId = Int32.Parse(row["CustomerId"].ToString());

                switch (tabs.SelectedTab.Name)
                {
                    case "daneKlientaTab":
                        groupBox1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox2.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox3.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox4.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        groupBox5.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        tabControl1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
                        kLIENCI_TYTULTableAdapter.FillByCustomerId(rEKLAMADataSet.KLIENCI_TYTUL, customerId);
                        break;
                    case "zamowieniaTab":
                        rEKLAMADataSet.REKLAMA.Clear();
                        rEKLAMATableAdapter.FillByCustomerId(rEKLAMADataSet.REKLAMA, customerId);
                        zamDataGridView.Sort(dATAZAMÓWIENIADataGridViewTextBoxColumn, ListSortDirection.Descending);
                        zamDataGridView.Refresh();
                        break;
                    case "fakturyTab":
                        rEKLAMADataSet.FAKTURY.Clear();
                        zestawienieFakturTableAdapter.FillByCustomerID(rEKLAMADataSet.ZestawienieFaktur, customerId);
                        fakturyDataGridView.Refresh();
                        break;
                    case "tabKorekty":
                        rEKLAMADataSet.VIEW_KOREKTY.Clear();
                        vIEW_KOREKTYTableAdapter.FillByCustomerId(rEKLAMADataSet.VIEW_KOREKTY, customerId);
                        gridKorekty.Refresh();
                        break;
                    case "tabAbonamenty":
                        RefreshSubscriptions();
                        break;
                    case "klasyfikacjaTabPage":
                        rEKLAMADataSet.KL_KLIENCI.Clear();
                        kL_KLIENCITableAdapter.ClearBeforeFill = true;
                        kL_KLIENCITableAdapter.FillByCustomerId(rEKLAMADataSet.KL_KLIENCI, customerId);
                        kL_1TableAdapter.Fill(sLOWNIKDataSet.KL_1);
                        kL_2TableAdapter.Fill(sLOWNIKDataSet.KL_2);
                        kL_3TableAdapter.Fill(sLOWNIKDataSet.KL_3);
                        break;
                    case "kontaktyTabPage":
                        rEKLAMADataSet.KONTAKTY.Clear();
                        kONTAKTYTableAdapter.FillByCustomerId(rEKLAMADataSet.KONTAKTY, customerId);
                        groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "osobyDoKontaktuTabPage":
                        rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.Clear();
                        kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.FillByCustomerId(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU, customerId);
                        groupBox6.Enabled = kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "doZalatwienia":
                        rEKLAMADataSet.sheduler.Clear();
                        shedulerTableAdapter.FillByCustomerId(rEKLAMADataSet.sheduler, customerId);
                        groupBox15.Enabled = shedulerBindingSource.List.Count == 0 ? false : true;
                        break;
                    case "ofertyTabPage":
                        rEKLAMADataSet.OFERTY_MAIN.Clear();
                        oFERTY_MAINTableAdapter.FillByCustomerId(rEKLAMADataSet.OFERTY_MAIN, customerId);
                        break;
                    default:
                        break;
                }
                Cursor = Cursors.Default;
            }

        }

        private void pokSzczegButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;

            try
            {
                Cursor = Cursors.WaitCursor;
                DataRowView row = (DataRowView) rEKLAMABindingSource.Current;
                int idRek = Int32.Parse(row["reklamaId"].ToString());
                int custId = Int32.Parse(row["customerId"].ToString());

                OrderDetails.getOrderDetails().PokazSzczegolyZamowienia(idRek);

                if (OrderDetails.getOrderDetails().ShowDialog() == DialogResult.OK)
                {
                    rEKLAMADataSet.REKLAMA.Clear();
                    rEKLAMATableAdapter.FillByCustomerId(rEKLAMADataSet.REKLAMA, custId);
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void nowaButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current == null) return;

            try
            {
                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView) kLIENCIBindingSource.Current;
                REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow) row.Row;

                if (klient.IskodKlientaNull())
                {
                    MessageBox.Show("Proszę uzupełnić kod klienta");
                    return;
                }

                OrderDetails.getOrderDetails().DodajNoweZamowienie(klient.CustomerID, klient.kodKlienta);

                if (OrderDetails.getOrderDetails().ShowDialog() == DialogResult.OK)
                {
                    rEKLAMADataSet.REKLAMA.Clear();
                    rEKLAMATableAdapter.FillByCustomerId(rEKLAMADataSet.REKLAMA, klient.CustomerID);
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void usunButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current != null)
            {
                bool ok = MessageBox.Show("Czy na pewno chcesz usunąć reklamę?", "", MessageBoxButtons.YesNo) == DialogResult.Yes ? true : false;

                DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
                if (row["id_faktury"] != DBNull.Value)
                {
                    MessageBox.Show("Wystawiono już fakturę. Nie można usunąć reklamy.");
                    return;
                }

                if (row["ZATWIERDZONO DO DRUKU"] != DBNull.Value)
                {
                    if (Convert.ToBoolean(row["ZATWIERDZONO DO DRUKU"]))
                    {
                        MessageBox.Show("Reklama zatwierdzona do druku. Nie można usunąć reklamy.");
                        return;
                    }
                }

                if (row["ZAPŁACONO"] != DBNull.Value)
                {
                    if (Convert.ToBoolean(row["ZAPŁACONO"]))
                    {
                        MessageBox.Show("Reklama zapłacona. Nie można usunąć reklamy.");
                        return;
                    }
                }

                if (ok)
                {
                    int idRek = Int32.Parse(row["reklamaId"].ToString());
                    rEKLAMABindingSource.RemoveCurrent();
                    rEKLAMATableAdapter.Update(rEKLAMADataSet.REKLAMA);

                    SqlCommand cmd = new SqlCommand("DELETE FROM [UKAŻE SIĘ W NR] WHERE (ReklamaId = @rekID)");

                    try
                    {
                        cmd.Parameters.AddWithValue("@rekID", idRek);
                        cmd.Connection = new SqlConnection(ConnString.getConnString().Value);
                        cmd.Connection.Open();

                        cmd.ExecuteNonQuery();
                    }
                    finally
                    {
                        if (cmd.Connection!=null)
                        {
                            cmd.Connection.Close();
                            cmd.Connection.Dispose();
                            cmd.Dispose();
                        }
                    }
                }
            }
        }

        private void wnowButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;

            try
            {
                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView) rEKLAMABindingSource.Current;
                int idRek = Int32.Parse(row["reklamaId"].ToString());
                int custId = Int32.Parse(row["customerId"].ToString());

                OrderDetails.getOrderDetails().WznowZamowienie(idRek);

                if (OrderDetails.getOrderDetails().ShowDialog() == DialogResult.OK)
                {
                    rEKLAMADataSet.REKLAMA.Clear();
                    rEKLAMATableAdapter.FillByCustomerId(rEKLAMADataSet.REKLAMA, custId);
                }
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void usunToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current == null) return;
            
            const string caption = "Klient - usuwanie klienta";

            DialogResult dialogResult = MessageBox.Show("Czy na pewno checsz usunąć klienta?",
                                                        caption,
                                                        MessageBoxButtons.YesNo,
                                                        MessageBoxIcon.Question);
            
            if (dialogResult != DialogResult.Yes) return;


            DataRowView row = (DataRowView) kLIENCIBindingSource.Current;
            int custId = Int32.Parse(row["CustomerId"].ToString());

            if (kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.GetDataByCustomerId(custId).Count != 0
                || rEKLAMATableAdapter.GetDataByCustomerId(custId).Count != 0
                || kL_KLIENCITableAdapter.GetDataByCustomerId(custId).Count != 0)
            {

                dialogResult = MessageBox.Show("Istnieją dane (reklamy, osoby do kontaktu lub klasyfikacja klienta) związane z klientem! Usunąć klienta?", 
                                                caption,
                                               MessageBoxButtons.YesNo,
                                               MessageBoxIcon.Question);
                
                if (dialogResult == DialogResult.Yes)
                {
                    kLIENCIBindingSource.RemoveCurrent();
                    kLIENCIBindingSource.EndEdit();
                    kLIENCITableAdapter.Update(rEKLAMADataSet.KLIENCI);
                }
            }
            else
            {
                kLIENCIBindingSource.RemoveCurrent();
                kLIENCIBindingSource.EndEdit();
                kLIENCITableAdapter.Update(rEKLAMADataSet.KLIENCI);
            }

            groupBox1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            groupBox2.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            groupBox3.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            groupBox4.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            groupBox5.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
            tabControl1.Enabled = kLIENCIBindingSource.List.Count == 0 ? false : true;
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                command.CommandText = query;
                command.Parameters.Clear();

                sqlDataAdapter.SelectCommand = command;

                switch (e.Node.Level)
                {
                    case 0:
                        switch (e.Node.Name)
                        {
                            case "MoiKlienci":
                                Cursor = Cursors.WaitCursor;

                                rEKLAMADataSet.KLIENCI.Clear();
                                command.CommandText += " where K.UserName=@agent order by data desc";
                                command.Parameters.AddWithValue("@agent", User.Instance().Symbol_agenta);
                                command.CommandType = CommandType.Text;
                                sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                clientsDataGridView.Refresh();

                                Cursor = Cursors.Default;
                                break;
                            default:
                                break;
                        }
                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "MoiKlienci":
                                switch (e.Node.Name)
                                {
                                    case "Aktywni":

                                        Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.KLIENCI.Clear();
                                        command.CommandText += " where K.UserName=@agent AND K.Aktywny=1 order by K.data desc";
                                        command.Parameters.AddWithValue("@agent", User.Instance().Symbol_agenta);
                                        command.CommandType = CommandType.Text;
                                        sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                        clientsDataGridView.Refresh();

                                        Cursor = Cursors.Default;
                                        break;
                                    case "AktywniExpo":

                                        Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.KLIENCI.Clear();
                                        command.CommandText += " where K.AgentExpo=@agent AND K.Aktywny=1 order by K.data desc";
                                        command.Parameters.AddWithValue("@agent", User.Instance().Symbol_agenta);
                                        command.CommandType = CommandType.Text;
                                        sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                        clientsDataGridView.Refresh();

                                        Cursor = Cursors.Default;
                                        break;
                                    case "Nieaktywni":

                                        Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.KLIENCI.Clear();
                                        command.CommandText += " where K.UserName=@agent AND K.Aktywny=0 order by K.data desc";
                                        command.Parameters.AddWithValue("@agent", User.Instance().Symbol_agenta);
                                        command.CommandType = CommandType.Text;
                                        sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                        clientsDataGridView.Refresh();

                                        Cursor = Cursors.Default;
                                        break;
                                    case "NieaktywniExpo":

                                        Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.KLIENCI.Clear();
                                        command.CommandText += " where K.AgentExpo=@agent AND K.Aktywny=0 order by K.data desc";
                                        command.Parameters.AddWithValue("@agent", User.Instance().Symbol_agenta);
                                        command.CommandType = CommandType.Text;
                                        sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                        clientsDataGridView.Refresh();

                                        Cursor = Cursors.Default;
                                        break;
                                    default:
                                        break;
                                }
                                break;
                            case "Biura":
                                Cursor = Cursors.WaitCursor;

                                rEKLAMADataSet.KLIENCI.Clear();
                                command.CommandText += " left join dbo.AGENCI A on K.UserName = A.Symbol where A.Id_agencji = @idAgencji";
                                command.Parameters.AddWithValue("@idAgencji", e.Node.Name);
                                command.CommandType = CommandType.Text;
                                sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                clientsDataGridView.Refresh();

                                Cursor = Cursors.Default;
                                break;
                            case "Niesklasyfikowani":
                                Cursor = Cursors.WaitCursor;

                                rEKLAMADataSet.KLIENCI.Clear();
                                command.CommandText += " left join KL_KLIENCI K2 on K.CustomerID = K2.Customerid  left join dbo.AGENCI A";
                                command.CommandText += " on K.UserName = A.Symbol where K2.ID_KL_KLIENCI is null  AND A.Id_agencji = @idAgencji";
                                command.Parameters.AddWithValue("@idAgencji", e.Node.Name);
                                command.CommandType = CommandType.Text;
                                sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                clientsDataGridView.Refresh();

                                Cursor = Cursors.Default;
                                break;
                            case "NiesklasyfikowaniT":
                                Cursor = Cursors.WaitCursor;

                                rEKLAMADataSet.KLIENCI.Clear();
                                command.CommandText += " left join KLIENCI_TYTUL KT on K.customerId = KT.customerId left join dbo.AGENCI A";
                                command.CommandText += " on K.UserName = A.Symbol where K.aktywny=1 AND KT.id_klienci_tytul is null  AND A.Id_agencji = @idAgencji";
                                command.Parameters.AddWithValue("@idAgencji", e.Node.Name);
                                command.CommandType = CommandType.Text;
                                sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                clientsDataGridView.Refresh();

                                Cursor = Cursors.Default;
                                break;
                            case "Klasyfikacja":
                                wyszukiwaniePoKlasyfikacji(e);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 2:
                        if (e.Node.Parent.Parent.Name == "Klasyfikacja")
                        {
                            wyszukiwaniePoKlasyfikacji(e);
                        }
                        else
                        {
                            switch (e.Node.Parent.Parent.Name)
                            {
                                case "Niesklasyfikowani":
                                    Cursor = Cursors.WaitCursor;

                                    rEKLAMADataSet.KLIENCI.Clear();
                                    command.CommandText += " left join KL_KLIENCI K2 on K.CustomerID = K2.Customerid  left join dbo.AGENCI A";
                                    command.CommandText += " on K.UserName = A.Symbol where K2.ID_KL_KLIENCI is null  AND A.Symbol = @symAgenta";
                                    command.Parameters.AddWithValue("@symAgenta", e.Node.Name);
                                    command.CommandType = CommandType.Text;
                                    sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                    clientsDataGridView.Refresh();

                                    Cursor = Cursors.Default;
                                    break;
                                case "NiesklasyfikowaniT":
                                    Cursor = Cursors.WaitCursor;

                                    rEKLAMADataSet.KLIENCI.Clear();
                                    command.CommandText += " left join KLIENCI_TYTUL KT on K.customerId = KT.customerId left join dbo.AGENCI A";
                                    command.CommandText += " on K.UserName = A.Symbol where K.aktywny=1 AND KT.id_klienci_tytul is null  AND A.Symbol = @symAgenta";
                                    command.Parameters.AddWithValue("@symAgenta", e.Node.Name);
                                    command.CommandType = CommandType.Text;
                                    sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                    clientsDataGridView.Refresh();

                                    Cursor = Cursors.Default;
                                    break;
                            }
                        }
                        break;
                    case 3:
                        if (e.Node.Parent.Parent.Parent.Name == "Klasyfikacja")
                        {
                            wyszukiwaniePoKlasyfikacji(e);
                        }
                        else
                        {
                            switch (e.Node.Parent.Name)
                            {
                                case "Agenci":
                                    Cursor = Cursors.WaitCursor;

                                    rEKLAMADataSet.KLIENCI.Clear();
                                    command.CommandText += " where UserName=@agent";
                                    command.Parameters.AddWithValue("@agent", e.Node.Name);
                                    command.CommandType = CommandType.Text;
                                    sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                    clientsDataGridView.Refresh();

                                    Cursor = Cursors.Default;
                                    break;
                                case "BrakKontaktu":
                                    Cursor = Cursors.WaitCursor;

                                    rEKLAMADataSet.KLIENCI.Clear();
                                    
                                    command.CommandText = "sp_GetClientsWithNoContact";
                                    command.CommandType = CommandType.StoredProcedure;

                                    command.Parameters.AddWithValue("@agencyId", e.Node.Parent.Parent.Name);
                                    command.Parameters.AddWithValue("@numberOfDaysStart", e.Node.Name);
                                    if (e.Node.NextNode != null)
                                        command.Parameters.AddWithValue("@numberOfDaysEnd", e.Node.NextNode.Name);
                                    else
                                        command.Parameters.AddWithValue("@numberOfDaysEnd", 9999);

                                    sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
                                    clientsDataGridView.Refresh();

                                    Cursor = Cursors.Default;
                                    break;
                                case "Klasyfikacja":
                                    wyszukiwaniePoKlasyfikacjiWgAgencji(e, Int32.Parse(e.Node.Parent.Parent.Name));
                                    break;
                                default:
                                    break;
                            }
                        }
                        break;
                    case 4:
                        if (e.Node.Parent.Parent.Name == "Klasyfikacja")
                        {
                            wyszukiwaniePoKlasyfikacjiWgAgencji(e, Int32.Parse(e.Node.Parent.Parent.Parent.Name));
                        }
                        break;
                    case 5:
                        if (e.Node.Parent.Parent.Parent.Name == "Klasyfikacja")
                        {
                            wyszukiwaniePoKlasyfikacjiWgAgencji(e, Int32.Parse(e.Node.Parent.Parent.Parent.Parent.Name));
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void szukajToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            cmd.CommandText = "select top 2000 K.* from klienci K where 1=1 ";
            cmd.Parameters.Clear();

            if (agencjaToolStripComboBox.Text.Trim() != "")
            {
                cmd.CommandText = "select  top 2000 K.* from klienci K left join dbo.AGENCI A on K.UserName = A.Symbol left join " +
                " dbo.AGENCJE A2 on A.ID_AGENCJI = A2.Id_agencji where 1=1 AND A2.Symbol=@agencja ";
                cmd.Parameters.AddWithValue("@agencja", agencjaToolStripComboBox.Text.Trim());
            }

            if (nazwaToolStripTextBox.Text.Trim() != "")
            {
                cmd.CommandText = cmd.CommandText +
                    "AND (K.[firstname] like '%' + @nazwa + '%' " +
                    "OR K.[lastname] like '%' + @nazwa + '%' " +
                    "OR K.[organizationname] like '%' + @nazwa + '%') ";
                cmd.Parameters.AddWithValue("@nazwa", nazwaToolStripTextBox.Text.Trim());
            }

            if (ulicaToolStripTextBox.Text.Trim() != "")
            {
                cmd.CommandText = cmd.CommandText + "AND K.[address] like '%' + @ulica + '%' ";
                cmd.Parameters.AddWithValue("@ulica", ulicaToolStripTextBox.Text.Trim());
            }

            if (kodToolStripTextBox.Text.Trim() != "")
            {
                cmd.CommandText = cmd.CommandText + "AND K.[postalCode] like '%' + @kod + '%' ";
                cmd.Parameters.AddWithValue("@kod", kodToolStripTextBox.Text.Trim());
            }

            if (miastoToolStripTextBox.Text.Trim() != "")
            {
                cmd.CommandText = cmd.CommandText + "AND K.[city] like '%' + @miasto + '%' ";
                cmd.Parameters.AddWithValue("@miasto", miastoToolStripTextBox.Text.Trim());
            }

            if (NIPStripTextBox.Text.Trim() != "")
            {
                cmd.CommandText = cmd.CommandText + "AND K.[Nip]=@nip ";
                cmd.Parameters.AddWithValue("@nip", NIPStripTextBox.Text.Trim());
            }

            if (agentToolStripComboBox.Text.Trim() != "")
            {
                cmd.CommandText = cmd.CommandText + "AND K.[UserName]=@agent ";
                cmd.Parameters.AddWithValue("@agent", agentToolStripComboBox.Text.Trim());
            }

            if (panstwoToolStripTextBox.Text.Trim() != "")
            {
                cmd.CommandText = cmd.CommandText + "AND K.[country] like '%' + @panstwo + '%' ";
                cmd.Parameters.AddWithValue("@panstwo", panstwoToolStripTextBox.Text.Trim());
            }

            if (kodKlientaToolStripTextBox.Text.Trim() != "")
            {
                cmd.CommandText = cmd.CommandText + "AND K.[kodKlienta] like '%' + @kodKlienta + '%' ";
                cmd.Parameters.AddWithValue("@kodKlienta", kodKlientaToolStripTextBox.Text.Trim());
            }

            sqlDataAdapter.SelectCommand = cmd;

            rEKLAMADataSet.KLIENCI.Clear();
            command.CommandType = CommandType.Text;

            sqlDataAdapter.Fill(rEKLAMADataSet.KLIENCI);
            
            clientsDataGridView.Refresh();

            treeView1.CollapseAll();
            treeView1.SelectedNode = null;

            Cursor = Cursors.Default;

        }

        private void fakturaButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;
            
            DataRowView row = (DataRowView) rEKLAMABindingSource.Current;
            int idReklamy = Convert.ToInt32(row["reklamaId"]);
            Facturer f = new Facturer(idReklamy);

            if (f.ShowDialog() == DialogResult.OK)
            {
                rEKLAMADataSet.REKLAMA.Clear();
                DataRowView r = (DataRowView) kLIENCIBindingSource.Current;
                int customerId = Int32.Parse(r["CustomerId"].ToString());
                rEKLAMATableAdapter.FillByCustomerId(rEKLAMADataSet.REKLAMA, customerId);
                zamDataGridView.Sort(dATAZAMÓWIENIADataGridViewTextBoxColumn, ListSortDirection.Descending);
                zamDataGridView.Refresh();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;

            DataRowView row = (DataRowView) rEKLAMABindingSource.Current;
            REKLAMADataSet.REKLAMARow reklama = (REKLAMADataSet.REKLAMARow) row.Row;

            if (AdHelper.IsOgloszenie(reklama))
            {
                OgloszenieForm ogloszenieForm = new OgloszenieForm(reklama, "klient");
                ogloszenieForm.ShowDialog();
            }
            else
            {
                ProjectForm pf = new ProjectForm(reklama.ReklamaID);
            pf.ShowDialog();
        }
        }

        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                TreeNode node;

                switch (e.Node.Level)
                {
                    case 0:
                        switch (e.Node.Name)
                        {
                            case "MoiKlienci":
                                e.Node.Nodes.Clear();

                                node = new TreeNode("Aktywni - AMT, GS, adMot...");
                                node.Name = "Aktywni";
                                treeView1.Nodes["MoiKlienci"].Nodes.Add(node);

                                node = new TreeNode("Nieaktywni - AMT, GS, adMot...");
                                node.Name = "Nieaktywni";
                                treeView1.Nodes["MoiKlienci"].Nodes.Add(node);

                                node = new TreeNode("Aktywni - Expo");
                                node.Name = "AktywniExpo";
                                treeView1.Nodes["MoiKlienci"].Nodes.Add(node);

                                node = new TreeNode("Nieaktywni - Expo");
                                node.Name = "NieaktywniExpo";
                                treeView1.Nodes["MoiKlienci"].Nodes.Add(node);

                                break;
                            case "Biura":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom1(e.Node);
                                break;
                            case "Niesklasyfikowani":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            case "NiesklasyfikowaniT":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "MoiKlienci":
                                break;
                            case "Biura":
                                e.Node.Nodes.Clear();

                                node = new TreeNode("Agenci");
                                node.Name = "Agenci";
                                e.Node.Nodes.Add(node);

                                //dodaje agentow do podwezla Agenci
                                DBBindings.dodajAgentowDoWezla(node, e.Node.Name);

                                node = new TreeNode("Brak kontaktu");
                                node.Name = "BrakKontaktu";
                                e.Node.Nodes.Add(node);

                                node = new TreeNode("90 dni");
                                node.Name = "90";
                                e.Node.Nodes["BrakKontaktu"].Nodes.Add(node);

                                node = new TreeNode("300 dni");
                                node.Name = "300";
                                e.Node.Nodes["BrakKontaktu"].Nodes.Add(node);

                                node = new TreeNode("Klasyfikacja");
                                node.Name = "Klasyfikacja";
                                DBBindings.dodajKlasyfikacjePoziom1(node);
                                e.Node.Nodes.Add(node);
                                break;
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom2(e.Node);
                                break;
                            case "Niesklasyfikowani":
                                DBBindings.dodajAgentowDoWezla(e.Node, e.Node.Name);
                                break;
                            case "NiesklasyfikowaniT":
                                DBBindings.dodajAgentowDoWezla(e.Node, e.Node.Name);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 2:
                        switch (e.Node.Parent.Parent.Name)
                        {
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom3(e.Node);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 3:
                        switch (e.Node.Parent.Name)
                        {
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom2(e.Node);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 4:
                        switch (e.Node.Parent.Parent.Name)
                        {
                            case "Klasyfikacja":
                                DBBindings.dodajKlasyfikacjePoziom3(e.Node);
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void clientsDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (!dodajKlienta)
                kLIENCIBindingSource.CancelEdit();
            else
                dodajKlienta = false;
        }

        private void usunFakture_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current == null) return;

            DataRowView row = (DataRowView) zestawienieFakturBindingSource.Current;

            //nie ma faktury
            if (row["id_faktury"] == DBNull.Value) return;

            bool ok = MessageBox.Show("Czyna pewno chcesz usunąć fakturę?", "", MessageBoxButtons.YesNo) ==
                      DialogResult.Yes
                          ? true
                          : false;

            //jednak nie usuwaj faktury
            if (!ok) return;

            //usun fakture
            Cursor = Cursors.WaitCursor;

            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);

            int idFaktury = Convert.ToInt32(row["id_faktury"]);

            //usuwanie faktury
            SqlCommand command3 = new SqlCommand();
            command3.CommandText = "delete from faktury where id_faktury = @param ";
            command3.CommandType = CommandType.Text;
            command3.Parameters.AddWithValue("@param", idFaktury);

            command3.Connection = conn;

            conn.Open();
            command3.ExecuteNonQuery();
            conn.Close();

            //usuwanie pozycji faktury
            command3 = new SqlCommand();
            command3.CommandText = "delete from faktura_details where id_faktury = @param ";
            command3.CommandType = CommandType.Text;
            command3.Parameters.AddWithValue("@param", idFaktury);

            command3.Connection = conn;

            conn.Open();
            command3.ExecuteNonQuery();
            conn.Close();

            //usuniecie informacji o fakturze z tabeli REKLAMA
            command3.CommandText = "update REKLAMA set ID_FAKTURY = null where ID_FAKTURY = @param ";

            conn.Open();
            command3.ExecuteNonQuery();
            conn.Close();

            zestawienieFakturBindingSource.RemoveCurrent();

            Cursor = Cursors.Default;
        }

        private void ukryjToolStripButton_Click(object sender, EventArgs e)
        {
            if (panel1.Visible)
            {
                panel1.Visible = false;
                ukryjToolStripButton.ToolTipText = "Pokaż szczegóły";
                usunToolStripButton.Enabled = false;
                zapiszDaneToolStripButton.Enabled = false;
            }
            else
            {
                panel1.Visible = true;
                ukryjToolStripButton.ToolTipText = "Ukryj szczegóły";
                usunToolStripButton.Enabled = true;
                zapiszDaneToolStripButton.Enabled = true;
            }
        }

        private void wyszukajToolStripButton_Click(object sender, EventArgs e)
        {
            szukajToolStrip.Visible = szukajToolStrip.Visible ? false : true;
        }

        private void dodajToolStripButton_Click(object sender, EventArgs e)
        {
            AddClient addClient = new AddClient();
            addClient.ShowDialog();

            if (addClient.Reload)
                pokazKlienta(addClient.Client.CustomerID);
        }

        public void pokazKlienta(int customerId)
        {
            treeView1.SelectedNode = treeView1.Nodes["test"];
            rEKLAMADataSet.KLIENCI.Clear();
            kLIENCITableAdapter.FillByCustomerId(rEKLAMADataSet.KLIENCI, customerId);
            clientsDataGridView.Refresh();
        }

        private void dodajKontaktToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {

                kONTAKTYBindingSource.EndEdit();

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Int32.Parse(row["CustomerId"].ToString());

                DataView datatable = (DataView)kONTAKTYBindingSource.List;



                DataRowView r = datatable.AddNew();
                kONTAKTYBindingSource.MoveLast();
                


                rodzajComboBox.SelectedIndex = 0;
                cbTypKontaktu.SelectedIndex = 0;
                opisTextBox1.Text = string.Empty;

                AddUpdateKontakt(r, custId);

                

                kONTAKTYBindingSource.EndEdit();


                groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;

            }
        }


        private void usunKontaktToolStripButton_Click(object sender, EventArgs e)
        {
            if (kONTAKTYBindingSource.Current == null) return;
            
            if (MessageBox.Show("Czy na pewno chcesz usunąć rekord?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                kONTAKTYBindingSource.RemoveCurrent();
                kONTAKTYTableAdapter.Update(rEKLAMADataSet.KONTAKTY);
                groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;
            }
        }

        private void wplataButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;

            DataRowView row = (DataRowView) rEKLAMABindingSource.Current;
            int idReklamy = Convert.ToInt32(row["reklamaId"]);
            int custId = Convert.ToInt32(row["customerId"]);
            PaymentForm p = new PaymentForm(idReklamy);
            if (p.ShowDialog() == DialogResult.OK)
            {
                rEKLAMATableAdapter.ClearBeforeFill = true;
                rEKLAMATableAdapter.FillByCustomerId(rEKLAMADataSet.REKLAMA, custId);
            }
        }

        private void pokFaktureButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;

            DataRowView row = (DataRowView) rEKLAMABindingSource.Current;
            REKLAMADataSet.REKLAMARow reklama = (REKLAMADataSet.REKLAMARow) row.Row;

            if (reklama.IsID_FAKTURYNull())
            {
                MessageBox.Show("Nie wystawiono faktury dla zlecenia");
                return;
            }

            Cursor = Cursors.WaitCursor;

            int idFaktury = Convert.ToInt32(row["id_faktury"]);

            FactureViewer fv = new FactureViewer(idFaktury, false, 0);
            fv.ShowDialog();

            Cursor = Cursors.Default;

        }

        private void pokazZamButton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;

            Cursor = Cursors.WaitCursor;

            DataRowView row = (DataRowView)rEKLAMABindingSource.Current;
            int idRek = Convert.ToInt32(row["reklamaId"]);
            OrderViewer ov = new OrderViewer(idRek);

            Cursor = Cursors.Default;

            ov.ShowDialog();
        }

        //TODO: usunac ten przycisk, bo nie ma juz racji bytu
        private void zapiszDaneToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current == null) return;
            
            MessageBox.Show("Dane zapisano", "Klient");
        }

        private void zapiszKontaktToolStripButton_Click(object sender, EventArgs e)
        {
            if (kONTAKTYBindingSource.Current == null) return;

            if (cbTypKontaktu.SelectedValue == null)
            {
                MessageBox.Show("Proszę wybrać tytuł");
                return;
            }
            DataRowView klientRow = (DataRowView)kLIENCIBindingSource.Current;
            REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow)klientRow.Row;

            DataRowView r = (DataRowView)kONTAKTYBindingSource.Current;
            AddUpdateKontakt(r, klient.CustomerID);

            kONTAKTYBindingSource.EndEdit();
            kONTAKTYTableAdapter.Update(rEKLAMADataSet.KONTAKTY);
            MessageBox.Show("Dane zapisano", "Kontakty z klientem");
        }

        private void PDFbutton_Click(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;
            DataRowView row = (DataRowView)rEKLAMABindingSource.Current;

            string symbolReklamy = row["id reklamy"].ToString();

            Cursor = Cursors.WaitCursor;
            try
            {
                PdfHelper pdfHelper = new PdfHelper(symbolReklamy);
                if (!pdfHelper.DisplayPdf())
                    MessageBox.Show(pdfHelper.ErrorMessage);
            }
            catch (System.Net.WebException exception)
            {
                PdfHelper.HandleWebException(exception);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private void clientsDataGridView_Leave(object sender, EventArgs e)
        {
            clientsDataGridView.EndEdit();
        }

        private void kLIENCIBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            wyczyscDaneKlienta();

            if (kLIENCIBindingSource.Current != null)
            {

                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);
                decimal zal = zaleglosciKlienta(custId);
                zalegaTextBox.Text = String.Format("{0:C}", zal);
                if (zal > 0)
                {
                    zalegaTextBox.BackColor = Color.LightYellow;
                    zalegaTextBox.ForeColor = Color.Red;
                }
                else
                {
                    zalegaTextBox.BackColor = Color.White;
                    zalegaTextBox.ForeColor = Color.Black;
                }

                agencjaLabel.Text = DbUtils.nazwaAgencji(row["username"].ToString());

                userNameComboBox.SelectedIndex = userNameComboBox.FindString(row["username"].ToString());
                cbAgentExpo.SelectedIndex = cbAgentExpo.FindString(row["AgentExpo"].ToString());


                if (((REKLAMADataSet.KLIENCIRow)row.Row).IsCountryNull()) 
                    countryComboBox.SelectedIndex = -1;

                Cursor = Cursors.Default;
            }
        }

        private void kryteriumWyszukiwania_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13) 
                szukajToolStripButton.PerformClick();
        }

        private void wyczyscPolaToolStripButton_Click(object sender, EventArgs e)
        {
            rEKLAMADataSet.KLIENCI.Clear();

            nazwaToolStripTextBox.Text = "";
            ulicaToolStripTextBox.Text = "";
            kodToolStripTextBox.Text = "";
            miastoToolStripTextBox.Text = "";
            NIPStripTextBox.Text = "";
            panstwoToolStripTextBox.Text = "";
            kodToolStripTextBox.Text = string.Empty;

            agencjaToolStripComboBox.SelectedIndex = -1;
            agentToolStripComboBox.Text = "";

            agentToolStripComboBox.SelectedIndex = -1;
            agentToolStripComboBox.Text = "";
        }

        private void zestawienieFakturBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            podsumujFaktury();
        }

        private void zapiszOsobeDoKontaktuToolStripButton_Click(object sender, EventArgs e)
        {
            kLIENCI_OSOBY_DO_KONTAKTUBindingSource.EndEdit();
            kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Update(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU);
            MessageBox.Show("Dane zapisane");
        }

        private void dodajOsobeDoKontaktuToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                kLIENCI_OSOBY_DO_KONTAKTUBindingSource.AddNew();

                kLIENCI_OSOBY_DO_KONTAKTUBindingSource.MoveLast();
                kLIENCI_OSOBY_DO_KONTAKTUBindingSource.EndEdit();

                groupBox6.Enabled = kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List.Count == 0 ? false : true;
            }
        }

        private void usunOsobeDoKontaktuToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCI_OSOBY_DO_KONTAKTUBindingSource.Current != null)
            {
                if (MessageBox.Show("Czy na pewno chcesz usunąć rekord?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    kLIENCI_OSOBY_DO_KONTAKTUBindingSource.RemoveCurrent();
                    kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Update(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU);
                }
                groupBox6.Enabled = kLIENCI_OSOBY_DO_KONTAKTUBindingSource.List.Count == 0 ? false : true;
            }
        }

        private void pokazFaktureButton_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;
                REKLAMADataSet.ZestawienieFakturRow faktura = (REKLAMADataSet.ZestawienieFakturRow)row.Row;

                Cursor = Cursors.WaitCursor;

                if (faktura.IsidZamowieniaNull())
                {
                    FactureViewer fv = new FactureViewer(faktura.ID_FAKTURY, false, 0);
                    fv.ShowDialog();
                }
                else
                {
                    FactureViewer fv = new FactureViewer(faktura.ID_FAKTURY, false);
                    fv.ShowDialog();
                }

                Cursor = Cursors.Default;
            }

        }

        private void daneKlientaTab_Leave(object sender, EventArgs e)
        {
            //if (!ValidateChildren())
            //{
            //    MessageBox.Show("Proszę uzupełnić dane klienta.", "Walidacja danych [daneKlientaTab_Leave]");
            //    //daneKlientaTab.Select();
            //    daneKlientaTab.Show();
            //    return;
            //}

            kLIENCIBindingSource.EndEdit();

            REKLAMADataSet.KLIENCIDataTable changes =
                rEKLAMADataSet.KLIENCI.GetChanges(
                DataRowState.Added | DataRowState.Modified)
                as REKLAMADataSet.KLIENCIDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    foreach (DataRow r in changes)
                    {
                        r["Last_Modify"] = DateTime.Now;
                        r["Modify_User"] = User.Instance().Login;
                    }

                    kLIENCITableAdapter.Update(rEKLAMADataSet.KLIENCI);
                }
                else
                {
                    rEKLAMADataSet.KLIENCI.RejectChanges();
                    daneKlientaTab.Select();
                }
            }
        }

        private void tabControl2_Leave(object sender, EventArgs e)
        {
            //if (tabs.SelectedIndex == 0 && !ValidateChildren())
            //{
            //    MessageBox.Show("Proszę uzupełnić dane klienta.", "Walidacja danych [tabControl2_Leave]");
            //    return;
            //}

            kLKLIENCIBindingSource.EndEdit();

            REKLAMADataSet.KL_KLIENCIDataTable changes = rEKLAMADataSet.KL_KLIENCI.GetChanges(
              DataRowState.Added | DataRowState.Modified)
              as REKLAMADataSet.KL_KLIENCIDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DataRowView row = (DataRowView)kLKLIENCIBindingSource.Current;
                    row["username"] = User.Instance().Login;

                    kL_KLIENCITableAdapter.Update(rEKLAMADataSet.KL_KLIENCI);
                }
                else
                {
                    rEKLAMADataSet.KONTAKTY.RejectChanges();
                }
            }
        }

        private void kontaktyTabPage_Leave(object sender, EventArgs e)
        {
            kONTAKTYBindingSource.EndEdit();

            REKLAMADataSet.KONTAKTYDataTable changes =
                rEKLAMADataSet.KONTAKTY.GetChanges(DataRowState.Added | DataRowState.Modified)
              as REKLAMADataSet.KONTAKTYDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    AddUpdateKontakt();
                    kONTAKTYTableAdapter.Update(rEKLAMADataSet.KONTAKTY);
                }
                else
                {
                    rEKLAMADataSet.KONTAKTY.RejectChanges();
                }
            }

        }

        private void osobyDoKontaktuTabPage_Leave(object sender, EventArgs e)
        {
            kLIENCI_OSOBY_DO_KONTAKTUBindingSource.EndEdit();

            REKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTUDataTable changes =
               rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.GetChanges(
               DataRowState.Added | DataRowState.Modified)
               as REKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTUDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    kLIENCI_OSOBY_DO_KONTAKTUTableAdapter.Update(rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU);
                }
                else
                {
                    rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.RejectChanges();
                }
            }
        }


        private void doZalatwienia_Leave(object sender, EventArgs e)
        {
            shedulerBindingSource.EndEdit();

            REKLAMADataSet.shedulerDataTable changes = rEKLAMADataSet.sheduler.GetChanges(
                DataRowState.Added | DataRowState.Modified)
                as REKLAMADataSet.shedulerDataTable;

            if (changes != null)
            {
                if (MessageBox.Show("Czy zapisać zmiany?", "", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
                }
                else
                {
                    rEKLAMADataSet.sheduler.RejectChanges();
                }
            }
        }

        private void klasyfikacjaTreeView_AfterExpand(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);
                SqlCommand comand = new SqlCommand();
                comand.Connection = conn;
                comand.CommandType = CommandType.Text;
                SqlDataReader reader;
                TreeNode node;

                switch (e.Node.Level)
                {
                    case 0:
                        e.Node.Nodes.Clear();

                        comand.CommandText = "select KL_2,ID_KL_2 from dbo.KL_2 where ID_KL_1=@param  order by KL_2";
                        comand.Parameters.Clear();
                        comand.Parameters.AddWithValue("@param", e.Node.Name);

                        conn.Open();
                        reader = comand.ExecuteReader();
                        while (reader.Read())
                        {
                            node = new TreeNode(reader.GetValue(0).ToString());
                            node.Name = reader.GetValue(1).ToString();
                            node.Nodes.Add(new TreeNode());
                            e.Node.Nodes.Add(node);
                        }
                        conn.Close();
                        break;

                    case 1:
                        e.Node.Nodes.Clear();

                        comand.CommandText = "select KL_3,ID_KL_3 from dbo.KL_3 where ID_KL_1=@param1 and ID_KL_2=@param2  order by KL_3";
                        comand.Parameters.Clear();
                        comand.Parameters.AddWithValue("@param1", e.Node.Parent.Name);
                        comand.Parameters.AddWithValue("@param2", e.Node.Name);

                        conn.Open();
                        reader = comand.ExecuteReader();
                        while (reader.Read())
                        {
                            node = new TreeNode(reader.GetValue(0).ToString());
                            node.Name = reader.GetValue(1).ToString();
                            e.Node.Nodes.Add(node);
                        }
                        conn.Close();

                        break;
                    default:
                        break;
                }
            }
        }

        private void dodKlasKlientaButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current == null) return;

            if (klasyfikacjaTreeView.SelectedNode == null)
            {
                MessageBox.Show("Wybierz klasyfikację.");
                return;
            }

            DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
            int custId = Int32.Parse(row["CustomerId"].ToString());

            if (klasyfikacjaTreeView.SelectedNode.Level != 2)
            {
                MessageBox.Show("Wybierz klasyfikację szczegółową.");
            }
            else
            {
                TreeNode n = klasyfikacjaTreeView.SelectedNode;
                int kl1 = Convert.ToInt32(n.Parent.Parent.Name);
                int kl2 = Convert.ToInt32(n.Parent.Name);
                int kl3 = Convert.ToInt32(n.Name);

                kL_KLIENCITableAdapter.Insert(kl1, kl2, kl3, custId, User.Instance().Login, DateTime.Now);
                kL_KLIENCITableAdapter.FillByCustomerId(rEKLAMADataSet.KL_KLIENCI, custId);
            }

        }

        private void usunKlasKlientaButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                if (kLKLIENCIBindingSource.Current != null)
                {
                    kLKLIENCIBindingSource.RemoveCurrent();
                    kL_KLIENCITableAdapter.Update(rEKLAMADataSet.KL_KLIENCI);
                }
            }
        }

        private void dodajKlButton_Click(object sender, EventArgs e)
        {
            if (klasyfikacjaTreeView.SelectedNode == null)
            {
                if (klTextBox.Text != "")
                {
                    kL_1TableAdapter.Insert(klTextBox.Text);
                    DBBindings.dodajKlasyfikacjePoziom1(klasyfikacjaTreeView);
                    klTextBox.Clear();
                    klasyfikacjaTreeView.SelectedNode = null;
                    return;
                }
            }

            switch (klasyfikacjaTreeView.SelectedNode.Level)
            {
                case 0:
                    if (klTextBox.Text != "")
                    {
                        string node = klasyfikacjaTreeView.SelectedNode.Name;
                        kL_2TableAdapter.Insert(Convert.ToInt32(node), klTextBox.Text);
                        DBBindings.dodajKlasyfikacjePoziom1(klasyfikacjaTreeView);
                        klasyfikacjaTreeView.Nodes[node].Expand();
                        klTextBox.Clear();
                    }
                    break;
                case 1:
                    if (klTextBox.Text != "")
                    {
                        string parentNode = klasyfikacjaTreeView.SelectedNode.Parent.Name;
                        string node = klasyfikacjaTreeView.SelectedNode.Name;
                        kL_3TableAdapter.Insert(Convert.ToInt32(parentNode), Convert.ToInt32(node), klTextBox.Text);
                        klasyfikacjaTreeView.Nodes[parentNode].Expand();
                        klasyfikacjaTreeView.Nodes[parentNode].Nodes[node].Collapse();
                        klasyfikacjaTreeView.Nodes[parentNode].Nodes[node].Expand();
                        klTextBox.Clear();
                    }
                    break;
                case 2:
                    MessageBox.Show("Nie można dodac kolejnej podkategorii.");
                    break;
            }
            klasyfikacjaTreeView.SelectedNode = null;
        }

        private void usunKlButton_Click(object sender, EventArgs e)
        {
            if (klasyfikacjaTreeView.SelectedNode != null)
            {
                string parentNode;
                switch (klasyfikacjaTreeView.SelectedNode.Level)
                {
                    case 0:
                        klasyfikacjaTreeView.SelectedNode.Expand();

                        if (klasyfikacjaTreeView.SelectedNode.Nodes.Count == 0)
                        {
                            kL_1TableAdapter.Delete(Convert.ToInt32(klasyfikacjaTreeView.SelectedNode.Name));

                            DBBindings.dodajKlasyfikacjePoziom1(klasyfikacjaTreeView);
                        }
                        else
                        {
                            MessageBox.Show("Nie można usunąć kategorii, jeżeli istnieją podkategorie.");
                        }
                        break;
                    case 1:
                        klasyfikacjaTreeView.SelectedNode.Expand();

                        if (klasyfikacjaTreeView.SelectedNode.Nodes.Count == 0)
                        {
                            parentNode = klasyfikacjaTreeView.SelectedNode.Parent.Name;

                            kL_2TableAdapter.Delete(Convert.ToInt32(klasyfikacjaTreeView.SelectedNode.Name));

                            klasyfikacjaTreeView.Nodes[parentNode].Collapse();
                            klasyfikacjaTreeView.Nodes[parentNode].Expand();
                        }
                        else
                        {
                            MessageBox.Show("Nie można usunąć kategorii, jeżeli istnieją podkategorie.");
                        }
                        break;
                    case 2:
                        string parentParentNode = klasyfikacjaTreeView.SelectedNode.Parent.Parent.Name;
                        parentNode = klasyfikacjaTreeView.SelectedNode.Parent.Name;

                        kL_3TableAdapter.Delete(Convert.ToInt32(klasyfikacjaTreeView.SelectedNode.Name));

                        klasyfikacjaTreeView.Nodes[parentParentNode].Nodes[parentNode].Collapse();
                        klasyfikacjaTreeView.Nodes[parentParentNode].Nodes[parentNode].Expand();
                        break;
                }
            }
            klasyfikacjaTreeView.SelectedNode = null;
        }

        private void klasyfikacjaTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            klasyfikacjaTreeView.SelectedNode = null;
        }

        private void generateNodes()
        {
            TreeNode node = new TreeNode("***");
            node.Name = "test";
            treeView1.Nodes.Add(node);

            if (User.Instance().IsHandlowiec)
            {
                node = new TreeNode("Moi klienci");
                node.Name = "MoiKlienci";
                node.Nodes.Add(new TreeNode());
                treeView1.Nodes.Add(node);
            }

            node = new TreeNode("Biura");
            node.Name = "Biura";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);

            node = new TreeNode("Klasyfikacja");
            node.Name = "Klasyfikacja";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);

            node = new TreeNode("Niesklasyfikowani");
            node.Name = "Niesklasyfikowani";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);

            node = new TreeNode("Niesklasyfikowani - tytuły");
            node.Name = "NiesklasyfikowaniT";
            node.Nodes.Add(new TreeNode());
            treeView1.Nodes.Add(node);
        }

        private void podpowiedzi()
        {

            ToolTip toolTip = new ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(pokazZamButton, "Wydruk zamówienia");
            toolTip.SetToolTip(pokFaktureButton, "Wydruk faktury");
            toolTip.SetToolTip(dodKlasKlientaButton, "Dodaj klasyfikację klienta");
            toolTip.SetToolTip(usunKlasKlientaButton, "Usuń klasyfikację klienta");
            toolTip.SetToolTip(usunKlButton, "Usuń nową kategorię");
            toolTip.SetToolTip(dodajKlButton, "Dodaj nową kategorię");
            toolTip.SetToolTip(openWWWbutton, "Otwórz stronę");
        }

        private void uprawnienia()
        {
            //usuwanie faktury
            usunFakture.Enabled = User.Instance().IsKierownik;
            usunFakture.Visible = false;

            //dodawanie klasyfikacji
            klTextBox.Visible = User.Instance().IsKierownik;
            dodajKlButton.Visible = User.Instance().IsKierownik;
            usunKlButton.Visible = User.Instance().IsKierownik;

            dodajLogoToolStripButton.Enabled = User.Instance().IsKierownik | User.Instance().IsProdukcja;
        }

        private void podsumujFaktury()
        {
            if (zestawienieFakturBindingSource.List.Count != 0)
            {
                decimal brutto = Convert.ToDecimal(rEKLAMADataSet.ZestawienieFaktur.Compute("Sum(BRUTTO)", ""));
                object sumaZaplat = rEKLAMADataSet.ZestawienieFaktur.Compute("Sum(suma_zaplat)", "");
                decimal zaplata = decimal.Zero;
                if (sumaZaplat != DBNull.Value)
                    zaplata = Convert.ToDecimal(rEKLAMADataSet.ZestawienieFaktur.Compute("Sum(suma_zaplat)", ""));

                bruttoTextBox.Text = String.Format("{0:C}", brutto);
                zaplataTextBox.Text = String.Format("{0:C}", zaplata);
            }
            else
            {
                bruttoTextBox.Clear();
                zaplataTextBox.Clear();
            }
        }

        private static decimal zaleglosciKlienta(int customerId)
        {
            decimal zalega = 0;

            SqlCommand cmd = new SqlCommand();
            cmd.Connection = new SqlConnection(ConnString.getConnString().Value);
            cmd.CommandText = "select zalega from dbo.view_klient_winien_ma_zalega where customerid=@custId";
            cmd.Parameters.AddWithValue("@custId", customerId);

            cmd.Connection.Open();
            zalega = (decimal)(cmd.ExecuteScalar() ?? zalega);
            cmd.Connection.Close();
            return zalega;
        }

        private void openWWWbutton_Click(object sender, EventArgs e)
        {
            string adres = httpTextBox.Text.Trim();

            if (adres != "")
            {
                adres = adres.Contains("http://") ? adres : "http://" + adres;

                if (Uri.IsWellFormedUriString(adres, UriKind.Absolute))
                {
                    System.Diagnostics.ProcessStartInfo n = new System.Diagnostics.ProcessStartInfo();
                    n.CreateNoWindow = false;
                    n.FileName = adres;
                    System.Diagnostics.Process.Start(n);
                }
                else
                {
                    MessageBox.Show("Podany adres jest niepoprawny");
                }
            }
        }

        private void pokZam_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;

                if (row["reklamaId"] != DBNull.Value)
                {
                    int idRek = Convert.ToInt32(row["reklamaId"]);

                    OrderDetails.getOrderDetails().PokazSzczegolyZamowienia(idRek);
                    OrderDetails.getOrderDetails().ShowDialog();
                }
            }
        }

        private void dodajSprDoZalatButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                shedulerBindingSource.EndEdit();

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Int32.Parse(row["CustomerId"].ToString());

                DataView datatable = (DataView)shedulerBindingSource.List;

                DataRowView r = datatable.AddNew();
                r["customerId"] = custId;
                r["CustomerName"] = row["FirstName"].ToString();
                r["Akwizytor"] = User.Instance().Login;
                r["DataWprowadzenia"] = DateTime.Now;
                r["DataPrzypomnienia"] = DateTime.Now.AddDays(7);

                shedulerBindingSource.MoveLast();
                shedulerBindingSource.EndEdit();

                groupBox15.Enabled = shedulerBindingSource.List.Count == 0 ? false : true;

            }
        }

        private void usunSprDoZalatButton_Click(object sender, EventArgs e)
        {
            if (shedulerBindingSource.Current != null)
            {
                if (MessageBox.Show("Czy na pewno chcesz usunąć rekord?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    shedulerBindingSource.RemoveCurrent();
                    shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
                    // MessageBox.Show("Dane usunięte");
                    groupBox15.Enabled = shedulerBindingSource.List.Count == 0 ? false : true;
                }
            }
        }

        private void zapiszSprDoZalatButton_Click(object sender, EventArgs e)
        {
            shedulerBindingSource.EndEdit();
            shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
            MessageBox.Show("Dane zapisane");
        }

        private void wplata2Button_Click(object sender, EventArgs e)
        {
            if (zestawienieFakturBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)zestawienieFakturBindingSource.Current;
                int custId = Convert.ToInt32(row["ID_NABYWCY"]);
                if (Convert.IsDBNull(row["reklamaId"]))
                {
                    if (Convert.ToBoolean(row["Korekta"])) return;

                    //wyswietl nowe okno wplat
                    PaymentForm2 pf2;
                    if (Convert.IsDBNull(row["idWplaty"]))
                        pf2 = new PaymentForm2(0, Convert.ToInt32(row["ID_FAKTURY"]));
                    else
                        pf2 = new PaymentForm2(Convert.ToInt32(row["idWplaty"]), Convert.ToInt32(row["ID_FAKTURY"]));

                    if (pf2.ShowDialog() == DialogResult.OK)
                    {
                        zestawienieFakturTableAdapter.ClearBeforeFill = true;
                        zestawienieFakturTableAdapter.FillByCustomerID(rEKLAMADataSet.ZestawienieFaktur, custId);
                    }
                }
                else
                {
                    int idReklamy = Convert.ToInt32(row["reklamaId"]);
                    PaymentForm p = new PaymentForm(idReklamy);
                    if (p.ShowDialog() == DialogResult.OK)
                    {
                        zestawienieFakturTableAdapter.ClearBeforeFill = true;
                        zestawienieFakturTableAdapter.FillByCustomerID(rEKLAMADataSet.ZestawienieFaktur, custId);
                    }
                }
            }
        }

        private void nowaOfertaButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                OferForm of = new OferForm(custId, 0, true);


                Cursor = Cursors.Default;

                of.ShowDialog();

                rEKLAMADataSet.OFERTY_MAIN.Clear();
                oFERTY_MAINTableAdapter.FillByCustomerId(rEKLAMADataSet.OFERTY_MAIN, custId);
            }
        }

        private void edycjaOfertyButton_Click(object sender, EventArgs e)
        {
            if ((kLIENCIBindingSource.Current != null) & (oFERTY_MAINBindingSource.Current != null))
            {
                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                DataRowView r = (DataRowView)oFERTY_MAINBindingSource.Current;
                int ofertaId = Convert.ToInt32(r["id_oferty"]);

                OferForm of = new OferForm(custId, ofertaId, false);

                Cursor = Cursors.Default;

                of.ShowDialog();
            }
        }

        private void ClientsForm_Resize(object sender, EventArgs e)
        {
            if (MdiParent != null)
            {
                if (MdiParent.WindowState == FormWindowState.Maximized)
                {
                    double h = MdiParent.Height;

                    int ph = (int)Math.Floor((65 * h) / 100);

                    panel1.Height = ph;

                }
                else
                {
                    splitContainer1.Height = splitConteiner1Height;
                    panel1.Height = Panel1Height;
                }
            }
        }

        private void przeniesAdresButton_Click(object sender, EventArgs e)
        {
            //string[] adres = new string[4];

            //adres[0] = firstNameTextBox.Text;
            //adres[1] = addressTextBox.Text;
            //adres[2] = postalCodeTextBox.Text + " " + cityTextBox.Text;
            //adres[3] = stateComboBox.Text + " " + countryComboBox.Text;

            //adres_FkaturaTextBox.Lines = adres;
            //adres_KorTextBox.Lines = adres;
        }

        private void wyczyscDaneKlienta()
        {
            rEKLAMADataSet.KLIENCI_OSOBY_DO_KONTAKTU.Clear();
            rEKLAMADataSet.sheduler.Clear();
            rEKLAMADataSet.REKLAMA.Clear();
            rEKLAMADataSet.ZestawienieFaktur.Clear();
            rEKLAMADataSet.KL_KLIENCI.Clear();
            rEKLAMADataSet.KONTAKTY.Clear();
            rEKLAMADataSet.OFERTY_MAIN.Clear();

            zalegaTextBox.Clear();
            agencjaLabel.Text = "";
        }

        private void EmailButton_Click(object sender, EventArgs e)
        {

            if ((kLIENCIBindingSource.Current != null) & (oFERTY_MAINBindingSource.Current != null))
            {
                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                DataRowView r = (DataRowView)oFERTY_MAINBindingSource.Current;
                int ofertaId = Convert.ToInt32(r["id_oferty"]);

                string temat = "Oferta nr: " + ofertaId + "/" + User.Instance().Kod_agenta.ToUpper() + "/" + DateTime.Today.Year;

                string ofertaFile = @"g:\reklamafiles\oferty\" + r["id_oferty"] + ".doc";

                if (File.Exists(ofertaFile))
                {
                    MailForm mf = new MailForm(custId, temat, ofertaFile);
                    mf.ShowDialog();
                }
                else
                {
                    MessageBox.Show("Nie można odnaleźć oferty: " + ofertaFile);
                }

            }
        }

        private void stateComboBox_Leave(object sender, EventArgs e)
        {
            kLIENCIBindingSource.EndEdit();
        }

        private void countryComboBox_Leave(object sender, EventArgs e)
        {
            kLIENCIBindingSource.EndEdit();
        }

        private void emailToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                MailForm mf = new MailForm(custId, "", "");
                mf.ShowDialog();
            }
        }

        private void smsToolStripButton_Click(object sender, EventArgs e)
        {
            //format +48602315947
            if (kLIENCI_OSOBY_DO_KONTAKTUBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)kLIENCI_OSOBY_DO_KONTAKTUBindingSource.Current;
                string nrTel = row["Tel"].ToString();
                if (string.IsNullOrEmpty(nrTel))
                {
                    MessageBox.Show("Brak numeru telefonu. Prawidłowy nr musi być w formacie +48xxxxxxxxx lub 0xxxxxxxxx");
                    return;
                }

                int customerId = Convert.ToInt32(row["customerId"]);

                nrTel = nrTel.Replace("-", "");
                nrTel = nrTel.Replace(" ", "");
                nrTel = nrTel.Replace("+48", "");

                if ((nrTel.Length == 10) & (nrTel[0] == Char.Parse("0")))
                {
                    nrTel = nrTel.Substring(1, 9);
                }

                if (!Regex.IsMatch(nrTel, "^[1-9]{1}[0-9]{8}"))
                {
                    MessageBox.Show("Podany nr telefony jest z złym formacie. Prawidłowy nr musi być w formacie +48xxxxxxxxx lub 0xxxxxxxxx");
                }
                else
                {
                    SMSform sf = new SMSform("+48" + nrTel, customerId);
                    sf.ShowDialog();
                }
            }
        }

        private void userNameComboBox_TextChanged(object sender, EventArgs e)
        {
            agencjaLabel.Text = DbUtils.nazwaAgencji(userNameComboBox.Text);
        }


        private void zrobioneToolStripButton_Click(object sender, EventArgs e)
        {
            if (shedulerBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)shedulerBindingSource.Current;
                row["zalatwione"] = false;
                shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
                shedulerDataGridView.Refresh();
            }
        }

        private void niezrobioneToolStripButton_Click(object sender, EventArgs e)
        {
            if (shedulerBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)shedulerBindingSource.Current;
                row["zalatwione"] = true;
                shedulerTableAdapter.Update(rEKLAMADataSet.sheduler);
                shedulerDataGridView.Refresh();
            }
        }

        private void ECARDbutton_Click(object sender, EventArgs e)
        {
            System.Diagnostics.ProcessStartInfo n = new System.Diagnostics.ProcessStartInfo();
            n.CreateNoWindow = false;
            n.FileName = "http://platnosci.admoto.pl/";
            System.Diagnostics.Process.Start(n);
        }

        private void wyszukiwaniePoKlasyfikacji(TreeViewEventArgs e)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = new SqlConnection(ConnString.getConnString().Value);

            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;

            switch (e.Node.Level)
            {
                case 1:
                    Cursor = Cursors.WaitCursor;
                    rEKLAMADataSet.KLIENCI.Clear();
                    cmd.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    cmd.CommandText += " K.CustomerID = K2.Customerid where K2.ID_KL_1=@idkl1 ";
                    cmd.Parameters.AddWithValue("@idkl1", e.Node.Name);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    Cursor = Cursors.Default;
                    break;
                case 2:
                    Cursor = Cursors.WaitCursor;
                    rEKLAMADataSet.KLIENCI.Clear();
                    cmd.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    cmd.CommandText += " K.CustomerID = K2.Customerid where K2.ID_KL_1=@idkl1 AND K2.ID_KL_2=@idkl2  ";
                    cmd.Parameters.AddWithValue("@idkl1", e.Node.Parent.Name);
                    cmd.Parameters.AddWithValue("@idkl2", e.Node.Name);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    Cursor = Cursors.Default;
                    break;
                case 3:
                    Cursor = Cursors.WaitCursor;
                    rEKLAMADataSet.KLIENCI.Clear();
                    cmd.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    cmd.CommandText += " K.CustomerID = K2.Customerid where K2.ID_KL_1=@idkl1 AND K2.ID_KL_2=@idkl2 AND K2.ID_KL_3=@idkl3";
                    cmd.Parameters.AddWithValue("@idkl1", e.Node.Parent.Parent.Name);
                    cmd.Parameters.AddWithValue("@idkl2", e.Node.Parent.Name);
                    cmd.Parameters.AddWithValue("@idkl3", e.Node.Name);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    Cursor = Cursors.Default;
                    break;
            }
        }

        private void wyszukiwaniePoKlasyfikacjiWgAgencji(TreeViewEventArgs e, int idAgencji)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = new SqlConnection(ConnString.getConnString().Value);

            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;

            switch (e.Node.Level)
            {
                case 3:
                    Cursor = Cursors.WaitCursor;
                    rEKLAMADataSet.KLIENCI.Clear();
                    cmd.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    cmd.CommandText += " K.CustomerID = K2.Customerid ";
                    cmd.CommandText += " left join dbo.AGENCI A on K.UserName = A.Symbol ";
                    cmd.CommandText += " where A.Id_agencji = @idAgencji AND K2.ID_KL_1=@idkl1 ";
                    cmd.Parameters.AddWithValue("@idkl1", e.Node.Name);
                    cmd.Parameters.AddWithValue("@idAgencji", idAgencji);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    Cursor = Cursors.Default;
                    break;
                case 4:
                    Cursor = Cursors.WaitCursor;
                    rEKLAMADataSet.KLIENCI.Clear();
                    cmd.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    cmd.CommandText += " K.CustomerID = K2.Customerid ";
                    cmd.CommandText += " left join dbo.AGENCI A on K.UserName = A.Symbol ";
                    cmd.CommandText += " where A.Id_agencji = @idAgencji AND K2.ID_KL_1=@idkl1 AND K2.ID_KL_2=@idkl2 ";
                    cmd.Parameters.AddWithValue("@idkl1", e.Node.Parent.Name);
                    cmd.Parameters.AddWithValue("@idkl2", e.Node.Name);
                    cmd.Parameters.AddWithValue("@idAgencji", idAgencji);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    Cursor = Cursors.Default;
                    break;
                case 5:
                    Cursor = Cursors.WaitCursor;
                    rEKLAMADataSet.KLIENCI.Clear();
                    cmd.CommandText = "select distinct top 2000 K.* from KLIENCI K left join KL_KLIENCI K2 on ";
                    cmd.CommandText += " K.CustomerID = K2.Customerid ";
                    cmd.CommandText += " left join dbo.AGENCI A on K.UserName = A.Symbol ";
                    cmd.CommandText += " where A.Id_agencji = @idAgencji";
                    cmd.CommandText += " and K2.ID_KL_1=@idkl1 AND K2.ID_KL_2=@idkl2 AND K2.ID_KL_3=@idkl3";
                    cmd.Parameters.AddWithValue("@idkl1", e.Node.Parent.Parent.Name);
                    cmd.Parameters.AddWithValue("@idkl2", e.Node.Parent.Name);
                    cmd.Parameters.AddWithValue("@idkl3", e.Node.Name);
                    cmd.Parameters.AddWithValue("@idAgencji", idAgencji);
                    adapter.Fill(rEKLAMADataSet.KLIENCI);
                    clientsDataGridView.Refresh();
                    Cursor = Cursors.Default;
                    break;
            }
        }

        private void wydrukDanychKlientaButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                Cursor = Cursors.WaitCursor;

                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Convert.ToInt32(row["customerId"]);

                DaneKlientaViewer dnv = new DaneKlientaViewer(custId);
                dnv.ShowDialog();

                Cursor = Cursors.Default;
            }
        }

        //TODO: replace ExcelHelper Export method with ExportToCsv to remove unneccesary depedencies..
        private void excelToolStripButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            ExcelHelper excelHelper = new ExcelHelper();
            excelHelper.Export(clientsDataGridView);
            
            Cursor = Cursors.Default;
        }

        private void agencjaToolStripComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((ComboBox)agencjaToolStripComboBox.Control).SelectedValue != null)
            {
                ((BindingSource)((ComboBox)agentToolStripComboBox.Control).DataSource).Filter = "ID_AGENCJI = " + ((ComboBox)agencjaToolStripComboBox.Control).SelectedValue;
                agentToolStripComboBox.SelectedIndex = -1;
                agentToolStripComboBox.SelectedIndex = -1;
            }
        }

        private void wstecznyKontaktToolStripButton_Click(object sender, EventArgs e)
        {
            if (DbUtils.iloscKontaktowAgenta(User.Instance().Login) == 0)
            {
                if (kLIENCIBindingSource.Current != null)
                {
                    kONTAKTYBindingSource.EndEdit();

                    DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                    int custId = Int32.Parse(row["CustomerId"].ToString());

                    DataView datatable = (DataView)kONTAKTYBindingSource.List;

                    DataRowView r = datatable.AddNew();
                    AddUpdateKontakt(r, custId, DateTime.Now.AddMonths(-1));

                    kONTAKTYBindingSource.MoveLast();
                    kONTAKTYBindingSource.EndEdit();

                    groupBox7.Enabled = kONTAKTYBindingSource.List.Count == 0 ? false : true;
                }
            }
            else
            {
                MessageBox.Show("Nie można dodać kontaktu. Istnieją kontakty z poprzedniego miesiąca.");
            }
        }

        private void dodajLogoToolStripButton_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                int custId = Int32.Parse(row["CustomerId"].ToString());

                LogaKlientowForm logaForm = new LogaKlientowForm(custId);
                logaForm.ShowDialog();
            }
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (kLIENCIBindingSource.Current == null) return;
            
            try
            {
                Cursor = Cursors.WaitCursor;
                DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
                REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow)row.Row;

                ZamowieniaForm zam = new ZamowieniaForm(klient);
                zam.ShowDialog();                
            }
            finally
            {
                Cursor = Cursors.Default;
            }

        }

        private void zamDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (rEKLAMABindingSource.Current == null) return;
            REKLAMADataSet.REKLAMARow reklama = (REKLAMADataSet.REKLAMARow)((DataRowView)rEKLAMABindingSource.Current).Row;

            pokazZamButton.Enabled = AdHelper.IsReklamaOldExpo(reklama) || !AdHelper.IsReklamaNew(reklama);
            fakturaButton.Enabled = pokazZamButton.Enabled;
            pokFaktureButton.Enabled = pokazZamButton.Enabled;
            wplataButton.Enabled = pokazZamButton.Enabled;
        }

        private void btnKorekta_Click(object sender, EventArgs e)
        {
            if (vIEWKOREKTYBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)vIEWKOREKTYBindingSource.Current;
                REKLAMADataSet.VIEW_KOREKTYRow faktura = (REKLAMADataSet.VIEW_KOREKTYRow)row.Row;

                Cursor = Cursors.WaitCursor;
                FactureViewer fv = new FactureViewer(faktura.ID_FAKTURY, faktura.idFakturyVAT, faktura.idFakturyKorekta);
                fv.ShowDialog();

                Cursor = Cursors.Default;
            }
        }

        private void fakturyDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            foreach (DataGridViewRow row in fakturyDataGridView.Rows)
            {
                DataRowView r = (DataRowView)row.DataBoundItem;

                if (Convert.IsDBNull(r.Row["IsKorekta"])) continue;

                if (Convert.ToBoolean(r.Row["IsKorekta"]))
                {
                    row.DefaultCellStyle.ForeColor = Color.Red;
                }
            }
        }

        private void cbKontaktTyp_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sender == null) return;
            if (((ToolStripComboBox)(sender)).ComboBox.SelectedItem is DataRowView || kLIENCIBindingSource.Current == null) return;

            rEKLAMADataSet.KONTAKTY.Clear();
            ComboItem comboItem = (ComboItem)((ToolStripComboBox)(sender)).ComboBox.SelectedItem;
            DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
            int customerId = Int32.Parse(row["CustomerId"].ToString());
            if (string.IsNullOrEmpty(comboItem.Display))
                kONTAKTYTableAdapter.FillByCustomerId(rEKLAMADataSet.KONTAKTY, customerId);
            else
                kONTAKTYTableAdapter.FillByKontaktTyp(rEKLAMADataSet.KONTAKTY, customerId, comboItem.Value);
        }

        private void kontaktyDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (kONTAKTYBindingSource.Current == null) return;

            DataRowView row = (DataRowView)kONTAKTYBindingSource.Current;
            cbTypKontaktu.SelectedIndex = -1;
            cbTypKontaktu.SelectedValue = row.Row["KontaktTypId"];
            opisTextBox1.Text = row.Row["opis"].ToString();
        }


        private void AddUpdateKontakt(DataRowView r, int customerId)
        {
            r["customerId"] = customerId;
            r["data"] = DateTime.Now;
            r["symbol_agenta"] = User.Instance().Login;
            r["rodzaj"] = rodzajComboBox.SelectedItem.ToString();
            r["opis"] = opisTextBox1.Text;
            if (cbTypKontaktu.Enabled && cbTypKontaktu.SelectedValue != null)
                r["KontaktTypId"] = (byte)cbTypKontaktu.SelectedValue;
            else
                r["KontaktTypId"] = 1;

            AddUpdateKontakt(r, customerId, DateTime.Now);
        }

        private void AddUpdateKontakt(DataRowView r, int customerId, DateTime dateTime)
        {
            r["customerId"] = customerId;
            r["data"] = dateTime;
            r["symbol_agenta"] = User.Instance().Login;
            r["rodzaj"] = rodzajComboBox.SelectedItem.ToString();
            r["opis"] = opisTextBox1.Text;
            if (cbTypKontaktu.Enabled && cbTypKontaktu.SelectedValue != null)
                r["KontaktTypId"] = (byte)cbTypKontaktu.SelectedValue;
            else
                r["KontaktTypId"] = 1;
        }

        private void AddUpdateKontakt()
        {
            //DataRowView r, int customerId
            if (kLIENCIBindingSource.Current == null || kONTAKTYBindingSource.Current == null) return;
            DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
            AddUpdateKontakt((DataRowView)kONTAKTYBindingSource.Current, Int32.Parse(row["CustomerId"].ToString()), DateTime.Now);
        }

        private void btnEditClient_Click(object sender, EventArgs e)
        {
            EditClient();
        }

        private void clientsDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            EditClient();
        }

        private void EditClient()
        {
            if (kLIENCIBindingSource.Current == null) return;

            DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
            REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow)row.Row;

            AddClient addClient = new AddClient(klient.CustomerID, kLIENCIBindingSource);
            addClient.ShowDialog();
        }

        #region IForm Members

        public void CloseForm()
        {
            clientsForm = null;
        }

        #endregion

        private void btnAddSubscription_Click(object sender, EventArgs e)
        {
            EditSubscription(true);
        }

        private void EditSubscription(bool bNew)
        {
            if (kLIENCIBindingSource.Current == null) return;

            Subscription subscript = null;

            if (!bNew)
            {
                if (gridSubscriptions.CurrentRow == null ||
                    gridSubscriptions.CurrentRow.DataBoundItem == null)
                    return;

                subscript = (Subscription)gridSubscriptions.CurrentRow.DataBoundItem;
            }

           // if (idSubscription > 0  && gridSubscriptions.DataSource
            List<Subscription> subscriptions = (List<Subscription>)gridSubscriptions.DataSource;

            DataRowView row = (DataRowView) kLIENCIBindingSource.Current;
            REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow) row.Row;

            SubscriptionForm subscriptionForm = new SubscriptionForm(klient.CustomerID, subscript);
            if (subscriptionForm.ShowDialog() == DialogResult.OK)
                RefreshSubscriptions();
        }

        private void RefreshSubscriptions()
        {
            if (kLIENCIBindingSource.Current == null) return;

            DataRowView row = (DataRowView)kLIENCIBindingSource.Current;
            REKLAMADataSet.KLIENCIRow klient = (REKLAMADataSet.KLIENCIRow)row.Row;

            CustomerRepository customerRepository = new CustomerRepository(ConnString.getConnString().Value);
            List<Subscription> subscriptions = customerRepository.FindSubscriptions(klient.CustomerID);
            gridSubscriptions.AutoGenerateColumns = false;
            gridSubscriptions.DataSource = subscriptions;

            foreach (DataGridViewRow dgRow in gridSubscriptions.Rows)
            {
                if (((Subscription)dgRow.DataBoundItem).InvoiceId > 0)
                    dgRow.DefaultCellStyle.ForeColor = Color.Gray;
                else
                    dgRow.DefaultCellStyle.ForeColor = Color.Black;
            }

            EnableSubscriptionBtn((subscriptions.Count > 0) ? 0 : -1);
        }

        private void btnEditSubscription_Click(object sender, EventArgs e)
        {
            EditSubscription(false);
        }

        private void btnDelSubscription_Click(object sender, EventArgs e)
        {
            if (gridSubscriptions.CurrentRow == null ||
                gridSubscriptions.CurrentRow.DataBoundItem == null)
                return;

            Subscription subscript = (Subscription)gridSubscriptions.CurrentRow.DataBoundItem;
            if (subscript.InvoiceId > 0)
            {
                MessageBox.Show("Nie można usunąć abonamentu - abonament jest zafakturowany.", "Baza Reklam",
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (MessageBox.Show("Czy napewno chcesz usunąć abonament " + subscript.SubscriptionItems
                            + " m-cy od " + subscript.StartDate.ToString("yyyy-MM-dd") + "?", "Baza Reklam",
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;

            CustomerRepository customerRepository = new CustomerRepository(ConnString.getConnString().Value);
            customerRepository.RemoveSubscription(subscript.Id);

            RefreshSubscriptions();
        }

        private void gridSubscriptions_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            EnableSubscriptionBtn(e.RowIndex);
        }

        private void EnableSubscriptionBtn(int row)
        {
            if (row < 0 ||
                gridSubscriptions.RowCount <= row ||
                gridSubscriptions.Rows[row].DataBoundItem == null)
            {
                btnEditSubscription.Enabled = false;
                btnDelSubscription.Enabled = false;
                return;
            }

            Subscription subscript = (Subscription)gridSubscriptions.Rows[row].DataBoundItem;

            btnEditSubscription.Enabled = !(subscript.InvoiceId > 0);
            btnDelSubscription.Enabled = !(subscript.InvoiceId > 0);
        }
    }
}