using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Globalization;

namespace Baza_Reklam
{
    public partial class InfoForm : Form
    {
        private static InfoForm infoform;

        public static InfoForm getInfoForm(MDIBazaReklam parent)
        {
            if (infoform == null)
            {
                infoform = new InfoForm(parent);
            }
            return infoform;
        }

        private int ostRok = DateTime.Today.Year;
        private int ostMs = DateTime.Today.Month;

        private InfoForm(Form parent)
        {
            InitializeComponent();

            MdiParent = parent;

            //podmiana connstringa
            nAZWY_MODULOWTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            aGENCITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            gRZBIETYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            koszty_BiuraTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            bUDZET_BIURTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            nRTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            daty_publikacjiTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            pLANY_PROWIZJITableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kONTATableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            aGENCJETableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            lISTA_TYTULOWTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            pROMOCJETableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            kursy_WalutTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;

            ImageList imageList = new ImageList();
            imageList.Images.Add(Properties.Resources.bullet_ball_glass_green);
            imageList.Images.Add(Properties.Resources.bullet_ball_glass_red);
            datyPubTreeView.ImageList = imageList;
            datyPubTreeView.ImageIndex = 0;
            datyPubTreeView.SelectedImageIndex = 1;

            treeView3.ImageList = imageList;
            treeView3.ImageIndex = 0;
            treeView3.SelectedImageIndex = 1;

            treeView4.ImageList = imageList;
            treeView4.ImageIndex = 0;
            treeView4.SelectedImageIndex = 1;

            bindingNavigator3.Visible = true;
            bindingNavigator4.Visible = true;
            bindingNavigator6.Visible = true;
            bindingNavigator7.Visible = true;
            bindingNavigator8.Visible = true;
            bindingNavigator9.Visible = true;
            bindingNavigator10.Visible = true;
            bindingNavigator11.Visible = true;

        }

        private void InfoForm_Load(object sender, EventArgs e)
        {
            // this.aGENCJETableAdapter.FillByALL(this.sLOWNIKDataSet.AGENCJE);

            agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
            agencjeListBox.DisplayMember = "Symbol";
            agencjeListBox.ValueMember = "Id_agencji";

            aGENCJETableAdapter.FillByIdAgencji(sLOWNIKDataSet.AGENCJE, Convert.ToInt32(agencjeListBox.SelectedValue));
            aGENCITableAdapter.FillByIdAgencji(sLOWNIKDataSet.AGENCI, Convert.ToInt32(agencjeListBox.SelectedValue));

            nowyAgentComboBox.DataSource = aGENCITableAdapter.GetDataByIdAgencjiAktywni(Convert.ToInt32(agencjeListBox.SelectedValue));
            nowyAgentComboBox.DisplayMember = "Symbol";
            nowyAgentComboBox.ValueMember = "Symbol";

            staryAgentComboBox.DataSource = aGENCITableAdapter.GetDataByNieaktywniIDAgencji(Convert.ToInt32(agencjeListBox.SelectedValue));
            staryAgentComboBox.DisplayMember = "Symbol";
            staryAgentComboBox.ValueMember = "Symbol";


            iDBIURADataGridViewTextBoxColumn.DataSource = aGENCJETableAdapter.GetData();
            iDBIURADataGridViewTextBoxColumn.DisplayMember = "Symbol";
            iDBIURADataGridViewTextBoxColumn.ValueMember = "Id_agencji";

            WindowState = FormWindowState.Maximized;

            nAZWY_MODULOWTableAdapter.FillByAll(sLOWNIKDataSet.NAZWY_MODULOW);

            generateNodes();
            generujTytuly();
            uprawnienia();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                nRBindingSource.Filter = "[tyt]='" + e.Node.Text + "'";
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (infoTabControl.SelectedTab.Name)
            {
                case "naWydanTab":
                    sLOWNIKDataSet.NAZWY_MODULOW.Clear();
                    nRTableAdapter.Fill(sLOWNIKDataSet.NR);
                    treeView1.SelectedNode = treeView1.Nodes["AMTNode"];
                    uzupelnijKalendarz();
                    break;
                case "modulyTab":
                    sLOWNIKDataSet.NR.Clear();
                    nAZWY_MODULOWTableAdapter.FillByAll(sLOWNIKDataSet.NAZWY_MODULOW);
                    break;
                case "oddzialyTab":
                    sLOWNIKDataSet.NAZWY_MODULOW.Clear();
                    sLOWNIKDataSet.NR.Clear();
                    pLANY_PROWIZJITableAdapter.Fill(sLOWNIKDataSet.PLANY_PROWIZJI);
                    if (aGENCJEBindingSource.Current != null)
                    {
                        DataRowView row = (DataRowView)aGENCJEBindingSource.Current;
                        int idAgencji = Convert.ToInt32(row["Id_agencji"]);
                        kONTATableAdapter.FillByIdAgencji(sLOWNIKDataSet.KONTA, idAgencji);
                        aGENCITableAdapter.FillByIdAgencji(sLOWNIKDataSet.AGENCI, idAgencji);
                    }
                    break;
                case "kursyWalutTabPage":
                    daty_publikacjiTableAdapter.Fill(sLOWNIKDataSet.Daty_publikacji);

                    TreeNode node;
                    foreach (DataRowView row in datypublikacjiBindingSource.List)
                    {
                        node = new TreeNode();
                        node.Text = (Convert.ToDateTime(row["Data_Publikacji"])).ToShortDateString();
                        node.Name = row["Numer_Tabeli"].ToString();
                        datyPubTreeView.Nodes.Add(node);
                    }
                    uprawnienia();
                    break;
                case "grzbietyTabPage":
                    lISTA_TYTULOWTableAdapter.FillAll(sLOWNIKDataSet.LISTA_TYTULOW);
                    pROMOCJETableAdapter.Fill(sLOWNIKDataSet.PROMOCJE);
                    gRZBIETYTableAdapter.Fill(sLOWNIKDataSet.GRZBIETY);
                    break;
                case "planyProwizyjneTabPage":
                    pLANY_PROWIZJITableAdapter.Fill(sLOWNIKDataSet.PLANY_PROWIZJI);
                    break;
                case "kosztyBiurTabPage":
                    treeView3.SelectedNode = treeView3.Nodes[User.getUser().IdAgencji.ToString()];
                    break;
                case "budzetTabPage":
                    treeView4.SelectedNode = treeView4.Nodes[User.getUser().IdAgencji.ToString()];
                    break;
                default:
                    break;
            }
        }

        private void treeView2_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                switch (e.Node.Level)
                {
                    case 0:
                        switch (e.Node.Name)
                        {
                            case "wszystkieNode":
                                nAZWYMODULOWBindingSource.Filter = "";
                                break;
                            case "TylkoAktywne":
                                nAZWYMODULOWBindingSource.Filter = "St_aktywny=1";
                                break;
                        }
                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "wszystkieNode":
                                nAZWYMODULOWBindingSource.Filter = "[tytul]='" + e.Node.Text + "'";
                                break;
                            case "TylkoAktywne":
                                nAZWYMODULOWBindingSource.Filter = "St_aktywny=1 AND [tytul]='" + e.Node.Text + "'";
                                break;
                        }
                        break;
                    default:
                        nAZWYMODULOWBindingSource.Filter = "";
                        break;
                }
            }
        }
        private void InfoForm_Shown(object sender, EventArgs e)
        {
            uzupelnijKalendarz();
        }

        private void nRBindingSource_ListChanged(object sender, ListChangedEventArgs e)
        {
            uzupelnijKalendarz();
        }

        private void naWydanTab_Enter(object sender, EventArgs e)
        {
            uzupelnijKalendarz();
        }

        private void nrWydanDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane");
        }

        private void saveToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            nRBindingSource.EndEdit();
            nRTableAdapter.Update(sLOWNIKDataSet.NR);
            MessageBox.Show("Dane zapisane");
        }

        private void modulySaveToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            nAZWYMODULOWBindingSource.EndEdit();
            nAZWY_MODULOWTableAdapter.Update(sLOWNIKDataSet.NAZWY_MODULOW);
            MessageBox.Show("Dane zapisane");
        }

        private void modulyDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane");
        }

        private void zapiszGrzbietyToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            gRZBIETYBindingSource.EndEdit();
            gRZBIETYTableAdapter.Update(sLOWNIKDataSet.GRZBIETY);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszTytultoolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            lISTA_TYTULOWBindingSource.EndEdit();
            lISTA_TYTULOWTableAdapter.Update(sLOWNIKDataSet.LISTA_TYTULOW);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszPromocjeToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            pROMOCJEBindingSource.EndEdit();
            pROMOCJETableAdapter.Update(sLOWNIKDataSet.PROMOCJE);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszPlanProwToolStripButton_Click(object sender, EventArgs e)
        {
            Validate();
            pLANYPROWIZJIBindingSource.EndEdit();
            pLANY_PROWIZJITableAdapter.Update(sLOWNIKDataSet.PLANY_PROWIZJI);
            MessageBox.Show("Zmiany zapisane.");
        }

        private void zapiszKosztyBiuraToolStripButton_Click_1(object sender, EventArgs e)
        {
            if (rokTextBox.Text == "")
            {
                MessageBox.Show("Podaj rok");
                return;
            }

            if (miesiacTextBox.Text == "")
            {
                MessageBox.Show("Podaj miesiac");
                return;
            }

            Validate();

            if (koszty_BiuraBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)koszty_BiuraBindingSource.Current;
                row["id_Agencji"] = treeView3.SelectedNode.Name;
            }
            koszty_BiuraBindingSource.EndEdit();
            koszty_BiuraTableAdapter.Update(sLOWNIKDataSet.Koszty_Biura);
            MessageBox.Show("Zmiany zapisane.");

            podsumujKosztyBiura();
        }

        private void zapiszBudzetToolStripButton_Click(object sender, EventArgs e)
        {
            budzetyDataGridView.EndEdit();
            Validate();
            bUDZETBIURBindingSource.EndEdit();
            bUDZET_BIURTableAdapter.Update(sLOWNIKDataSet.BUDZET_BIUR);
            MessageBox.Show("Zmiany zapisane.");

        }

        private void pROMOCJEDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane.");
        }

        private void gRZBIETYDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane.");
        }

        private void pLANY_PROWIZJIDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane.");
        }

        private void treeView3_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                sLOWNIKDataSet.Koszty_Biura.Clear();
                koszty_BiuraTableAdapter.FillBy(sLOWNIKDataSet.Koszty_Biura, e.Node.Name);
                koszty_BiuraBindingSource.MoveLast();

                if (koszty_BiuraBindingSource.Current != null)
                {
                    DataRowView row = (DataRowView)koszty_BiuraBindingSource.Current;
                    ostRok = Convert.ToInt32(row["rok"]);
                    ostMs = Convert.ToInt32(row["miesiac"]);
                }
            }
        }

        private void treeView4_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                sLOWNIKDataSet.BUDZET_BIUR.Clear();
                bUDZET_BIURTableAdapter.FillByIdAgencji(sLOWNIKDataSet.BUDZET_BIUR, Convert.ToInt32(e.Node.Name));
            }
        }

        private void budzetyDataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            MessageBox.Show("Wprowadz poprawne dane");
        }

        private void modulyDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            // modulyDataGridView.EndEdit();
        }

        private void kursy_WalutDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            // kursy_WalutDataGridView.EndEdit();
        }

        private void nrWydanDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //nrWydanDataGridView.EndEdit();
        }

        private void gRZBIETYDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
        }

        private void pROMOCJEDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //pROMOCJEDataGridView.EndEdit();
        }

        private void pLANY_PROWIZJIDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //pLANY_PROWIZJIDataGridView.EndEdit();
        }

        private void budzetyDataGridView_Leave(object sender, EventArgs e)
        {
            ukrytyLabel.Select();
            //budzetyDataGridView.EndEdit();
        }

        private void pLANY_PROWIZJIDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            ukrytyLabel.Select();
            if (pLANY_PROWIZJIDataGridView.Columns[e.ColumnIndex].Name != "dataGridViewTextBoxColumn15")
            {
                pLANY_PROWIZJIDataGridView.EndEdit();
                if (Convert.ToDecimal(pLANY_PROWIZJIDataGridView[e.ColumnIndex, e.RowIndex].Value) >= 1)
                {
                    pLANY_PROWIZJIDataGridView[e.ColumnIndex, e.RowIndex].Value = Convert.ToDecimal(pLANY_PROWIZJIDataGridView[e.ColumnIndex, e.RowIndex].Value) / 100;
                }
            }
        }

        private void datyPubTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            kursy_WalutTableAdapter.ClearBeforeFill = true;
            if (datyPubTreeView.SelectedNode != null)
            {
                kursy_WalutTableAdapter.FillByNrTabeli(sLOWNIKDataSet.Kursy_Walut, datyPubTreeView.SelectedNode.Name);
            }
            kursy_WalutDataGridView.Refresh();
        }

        //private void pozycjaAktualnegoWydania(string tytul)
        //{
        //    int position = 0;
        //    return;
        //}

        // wpisuje dni tygodnia i nr tygodnia w roku
        private void uzupelnijKalendarz()
        {
            DateTime dzien;
            CultureInfo myCI = new CultureInfo("pl-PL");
            Calendar myCal = myCI.Calendar;

            foreach (DataGridViewRow r in nrWydanDataGridView.Rows)
            {
                dzien = Convert.ToDateTime(r.Cells["dATAWDataGridViewTextBoxColumn"].Value);
                r.Cells["dzienTygodniaColumn"].Value =
                CultureInfo.CurrentCulture.DateTimeFormat.DayNames[(int)dzien.DayOfWeek];
                r.Cells["nrTygodniaColumn"].Value = myCal.GetWeekOfYear(dzien, CalendarWeekRule.FirstDay, DayOfWeek.Monday).ToString();
            }
        }

        private void generateNodes()
        {
            SqlCommand command = new SqlCommand();

            command.Connection = new SqlConnection(ConnString.getConnString().Value);

            command.CommandText = "select ID_AGENCJI,Symbol from dbo.AGENCJE where aktywna = 1";

            command.Connection.Open();

            SqlDataReader reader = command.ExecuteReader();

            // ReSharper disable PossibleNullReferenceException
            while (reader.Read())
            // ReSharper restore PossibleNullReferenceException
            {
                TreeNode node = new TreeNode(reader.GetValue(1).ToString());
                TreeNode node1 = new TreeNode(reader.GetValue(1).ToString());
                node.Name = reader.GetValue(0).ToString();
                node1.Name = reader.GetValue(0).ToString();
                treeView3.Nodes.Add(node);
                treeView4.Nodes.Add(node1);
            }

            command.Connection.Close();
        }

        private void uprawnienia()
        {

            if (!User.getUser().St_kierownik)
            {
                infoTabControl.TabPages.Remove(grzbietyTabPage);
                infoTabControl.TabPages.Remove(planyProwizyjneTabPage);
                infoTabControl.TabPages.Remove(kosztyBiurTabPage);
                infoTabControl.TabPages.Remove(budzetTabPage);
            }

            if (!(User.getUser().St_kierownik | User.getUser().St_handlowiec | User.getUser().St_subhandlowiec | User.getUser().St_sekretarka))
            {
                infoTabControl.TabPages.Remove(kursyWalutTabPage);
                infoTabControl.TabPages.Remove(naWydanTab);
                infoTabControl.TabPages.Remove(agencjeTabPage);
            }



            dodajAgencjeButton.Enabled = User.getUser().St_kierownik;
            edytujAgencjeButton.Enabled = User.getUser().St_kierownik;
            dodajAgentaButton.Enabled = User.getUser().St_kierownik;
            edytujAgentaButton.Enabled = User.getUser().St_kierownik;
            dodajKontoButton.Enabled = User.getUser().St_kierownik;
            edytujKontoButton.Enabled = User.getUser().St_kierownik;

            nrWydanDataGridView.AllowUserToAddRows = User.getUser().St_kierownik;
            modulyDataGridView.AllowUserToAddRows = User.getUser().St_kierownik;

            bindingNavigatorAddNewItem2.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem3.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem5.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem6.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem7.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem8.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem9.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            bindingNavigatorAddNewItem10.Visible = User.getUser().St_kierownik | User.getUser().St_admin;

            zapiszGrzbietyToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszNrWydToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszTytultoolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszPromocjeToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            modulySaveToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszPlanProwToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszBudzetToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;
            zapiszKosztyBiuraToolStripButton.Visible = User.getUser().St_kierownik | User.getUser().St_admin;

            bindingNavigatorDeleteItem2.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem3.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem5.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem6.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem7.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem8.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem9.Visible = User.getUser().St_admin;
            bindingNavigatorDeleteItem10.Visible = User.getUser().St_admin;
        }


        private void koszty_BiuraBindingSource_AddingNew(object sender, AddingNewEventArgs e)
        {
            if (treeView3.SelectedNode != null)
            {
                DataView dataTableView = koszty_BiuraBindingSource.List as DataView;

                // ReSharper disable PossibleNullReferenceException
                DataRowView rowView = dataTableView.AddNew();
                // ReSharper restore PossibleNullReferenceException

                rowView["id_Agencji"] = treeView3.SelectedNode.Name;
                //  rowView["rok"] = DateTime.Today.Year;
                //  rowView["miesiac"] = DateTime.Today.Month;

                if (ostMs == 12)
                {
                    rowView["rok"] = ++ostRok;
                    rowView["miesiac"] = ostMs = 1;
                }
                else
                {
                    rowView["rok"] = ostRok;
                    rowView["miesiac"] = ++ostMs;
                }
                e.NewObject = rowView;

                koszty_BiuraBindingSource.MoveLast();
            }
        }

        private void bUDZETBIURBindingSource_AddingNew(object sender, AddingNewEventArgs e)
        {
            if (treeView4.SelectedNode != null)
            {
                DataView dataTableView = bUDZETBIURBindingSource.List as DataView;

                if (dataTableView != null)
                {
                    DataRowView rowView = dataTableView.AddNew();

                    rowView["ID_BIURA"] = treeView4.SelectedNode.Name;
                    rowView["rok"] = DateTime.Today.Year;
                    rowView["ms"] = DateTime.Today.Month;

                    e.NewObject = rowView;
                }

                bUDZETBIURBindingSource.MoveLast();
            }
        }

        private void podsumujKosztyBiura()
        {
            if (koszty_BiuraBindingSource.Current != null)
            {
                decimal suma = 0;

                DataRowView r = (DataRowView)koszty_BiuraBindingSource.Current;

                suma += r["czynsz"] == DBNull.Value ? 0 : Convert.ToDecimal(r["czynsz"]);
                suma += r["energia"] == DBNull.Value ? 0 : Convert.ToDecimal(r["energia"]);
                suma += r["telefony"] == DBNull.Value ? 0 : Convert.ToDecimal(r["telefony"]);
                suma += r["internet"] == DBNull.Value ? 0 : Convert.ToDecimal(r["internet"]);
                suma += r["parkingi"] == DBNull.Value ? 0 : Convert.ToDecimal(r["parkingi"]);
                suma += r["paliwo"] == DBNull.Value ? 0 : Convert.ToDecimal(r["paliwo"]);
                suma += r["place"] == DBNull.Value ? 0 : Convert.ToDecimal(r["place"]);
                suma += r["inne"] == DBNull.Value ? 0 : Convert.ToDecimal(r["inne"]);

                decimal ksiegowosc = r["ksiegowosc"] == DBNull.Value ? 0 : Convert.ToDecimal(r["ksiegowosc"]);

                decimal roznica = ksiegowosc - suma;

                razemLabel.Text = String.Format("{0:C}", suma);
                roznicaLabel.Text = String.Format("{0:C}", roznica);
            }
        }

        private void koszty_BiuraBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            podsumujKosztyBiura();
        }


        private void agencjeListBox_SelectedValueChanged(object sender, EventArgs e)
        {
            if (agencjeListBox.SelectedValue != null)
            {
                int idAgencji = Convert.ToInt32(agencjeListBox.SelectedValue);
                aGENCITableAdapter.FillByIdAgencji(sLOWNIKDataSet.AGENCI, idAgencji);
                kONTATableAdapter.FillByIdAgencji(sLOWNIKDataSet.KONTA, idAgencji);
                aGENCJETableAdapter.FillByIdAgencji(sLOWNIKDataSet.AGENCJE, idAgencji);
                nowyAgentComboBox.DataSource = aGENCITableAdapter.GetDataByIdAgencjiAktywni(idAgencji);
                staryAgentComboBox.DataSource = aGENCITableAdapter.GetDataByNieaktywniIDAgencji(idAgencji);

                groupBox1.Enabled = User.getUser().St_kierownik & (idAgencji == User.getUser().IdAgencji);
            }
        }

        private void dodajAgencjeButton_Click(object sender, EventArgs e)
        {
            AgencjaAddForm aaf = new AgencjaAddForm(0);

            if (aaf.ShowDialog() == DialogResult.OK)
            {
                agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
            }
        }

        private void edytujAgencjeButton_Click(object sender, EventArgs e)
        {
            if (agencjeListBox.SelectedValue != null)
            {
                AgencjaAddForm aaf = new AgencjaAddForm((int)agencjeListBox.SelectedValue);
                if (aaf.ShowDialog() == DialogResult.OK)
                {
                    agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
                }
            }
        }

        private void dodajAgentaButton_Click(object sender, EventArgs e)
        {
            AgentAddForm aaf = new AgentAddForm(0, Convert.ToInt32(agencjeListBox.SelectedValue));

            if (aaf.ShowDialog() == DialogResult.OK)
            {
                aGENCITableAdapter.FillByIdAgencji(sLOWNIKDataSet.AGENCI, Convert.ToInt32(agencjeListBox.SelectedValue));
                //agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
            }
        }

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

                int id = Convert.ToInt32(row["ID_AGENTA"]);
                AgentAddForm aaf = new AgentAddForm(id, Convert.ToInt32(agencjeListBox.SelectedValue));
                if (aaf.ShowDialog() == DialogResult.OK)
                {
                    aGENCITableAdapter.FillByIdAgencji(sLOWNIKDataSet.AGENCI, Convert.ToInt32(agencjeListBox.SelectedValue));
                }
            }
        }

        private void dodajKontoButton_Click(object sender, EventArgs e)
        {
            AddKontoForm aaf = new AddKontoForm(0, Convert.ToInt32(agencjeListBox.SelectedValue));

            if (aaf.ShowDialog() == DialogResult.OK)
            {

                kONTATableAdapter.FillByIdAgencji(sLOWNIKDataSet.KONTA, Convert.ToInt32(agencjeListBox.SelectedValue));
                //agencjeListBox.DataSource = aGENCJETableAdapter.GetDataByALL();
            }
        }

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

                int id = Convert.ToInt32(row["ID"]);
                AddKontoForm aaf = new AddKontoForm(id, Convert.ToInt32(agencjeListBox.SelectedValue));
                if (aaf.ShowDialog() == DialogResult.OK)
                {
                    kONTATableAdapter.FillByIdAgencji(sLOWNIKDataSet.KONTA, Convert.ToInt32(agencjeListBox.SelectedValue));
                }
            }
        }

        private void przepiszButton_Click(object sender, EventArgs e)
        {
            if ((staryAgentComboBox.SelectedValue == null) || (nowyAgentComboBox.SelectedValue == null))
            {
                MessageBox.Show("Wybierz symbole agentów");
                return;
            }

            Cursor = Cursors.WaitCursor;

            SqlCommand command = new SqlCommand();
            command.Connection = new SqlConnection(ConnString.getConnString().Value);

            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "przepiszKlientow";

            command.Parameters.AddWithValue("@staryUserName", staryAgentComboBox.SelectedValue);
            command.Parameters.AddWithValue("@nowyUserName", nowyAgentComboBox.SelectedValue);

            command.Connection.Open();

            SqlTransaction transaction = command.Connection.BeginTransaction();
            command.Transaction = transaction;

            try
            {
                command.ExecuteNonQuery();
                transaction.Commit();
                MessageBox.Show("Klienci zostali przepisani.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.GetType() + ex.Message);

                try
                {
                    transaction.Rollback();
                }
                catch (Exception ex2)
                {
                    MessageBox.Show("ROLLBACK:" + ex2.GetType() + ex.Message);
                }
            }

            command.Connection.Close();

            Cursor = Cursors.Default;

        }

        private void generujTytuly()
        {

            SLOWNIKDataSet.LISTA_TYTULOWDataTable dt = lISTA_TYTULOWTableAdapter.GetData();

            foreach (SLOWNIKDataSet.LISTA_TYTULOWRow r in dt)
            {
                treeView1.Nodes.Add(new TreeNode(r.SYMB));
                treeView2.Nodes["wszystkieNode"].Nodes.Add(new TreeNode(r.SYMB));
                treeView2.Nodes["TylkoAktywne"].Nodes.Add(new TreeNode(r.SYMB));
            }
        }

        private void kursy_WalutDataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (User.getUser().IdAgencji == 6)
            {
                if (e.ColumnIndex == 5 && e.RowIndex != -1)
                {
                    decimal poprzedniKurs = Convert.ToDecimal(
                        kursy_WalutDataGridView[e.ColumnIndex, e.RowIndex].Value);

                    KursyWalutPoznan kwp = new KursyWalutPoznan(poprzedniKurs);

                    if (kwp.ShowDialog() == DialogResult.OK)
                    {
                        kursy_WalutDataGridView[e.ColumnIndex, e.RowIndex].Value = kwp.KursSredni;
                        kursy_WalutDataGridView.EndEdit();
                        kursy_WalutBindingSource.EndEdit();
                        kursy_WalutTableAdapter.Update(sLOWNIKDataSet.Kursy_Walut);
                    }
                }
            }

        }

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

            ExcelHelper ex = new ExcelHelper();
            ex.Export(modulyDataGridView);

            Cursor = Cursors.Default;
        }

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

            ExcelHelper ex = new ExcelHelper();
            ex.Export(nrWydanDataGridView);

            Cursor = Cursors.Default;
        }

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

            ExcelHelper ex = new ExcelHelper();
            ex.Export(pLANY_PROWIZJIDataGridView);

            Cursor = Cursors.Default;
        }

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

            ExcelHelper ex = new ExcelHelper();
            ex.Export(budzetyDataGridView);

            Cursor = Cursors.Default;
        }
    }
}