using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Baza_Reklam
{
    public partial class KorektyForm : Form
    {
        string query = "SELECT top 2000 * from VIEW_KOREKTY ";

        private static KorektyForm fakturesForm;
        private SqlCommand command;
        private SqlDataAdapter sqlDataAdapter;

        private bool commandExecuted = false;

        public static KorektyForm getFacturesForm(MDIBazaReklam parent)
        {
            if (fakturesForm == null){
                fakturesForm = new KorektyForm(parent);
            }
            return fakturesForm;
        }

        private KorektyForm(MDIBazaReklam parent)
        {
            InitializeComponent();
            this.MdiParent = parent;

            //podmiana connstringa
            vIEW_KOREKTYTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
         
            //obiekty wykorzytywane przy wyszukiwaniu
            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);
            command = new SqlCommand();
            command.Connection = conn;
            
            this.sqlDataAdapter = new SqlDataAdapter();

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

            //ustawia domyslny rok i miesiąc w pasku wyszukiwania
            rokToolStripTextBox.Text = DateTime.Today.Year.ToString();
            miesiacToolStripTextBox.Text = DateTime.Today.Month.ToString();

            wyszukajToolStrip.Items.Insert(10, new ToolStripLabel("nieuregulowane:"));
            wyszukajToolStrip.Items.Insert(11, new ToolStripControlHost(new CheckBox(), "zalegleCheckBox"));
            ((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).ThreeState = true;
            ((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState = CheckState.Indeterminate;           
        }

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

            DBBindings.bindujAgencje(agencjaToolStripComboBox);
         
            command.CommandText = this.query;
            sqlDataAdapter.SelectCommand = command;
        }

        private void generateNodes()
        {
            TreeNode node;

            node = new TreeNode("Wpłaty - księgowość");
            node.Name = "WplatyKsiegowosc";
            treeView1.Nodes.Add(node);

            node = new TreeNode("Różnice wpłat");
            node.Nodes.Add(new TreeNode());
            node.Name = "BrakWKsiegowosci";

            treeView1.Nodes["WplatyKsiegowosc"].Nodes.Add(node);

            node = new TreeNode("Brak w reklamie");
            node.Nodes.Add(new TreeNode());
            node.Name = "BrakWReklamie";

            treeView1.Nodes["WplatyKsiegowosc"].Nodes.Add(node);
                        
            command.Connection.Close();                         
        }
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null)
            {
                command.CommandText = query;
                command.Parameters.Clear();

                switch (e.Node.Level)
                {
                    case 0:
                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "WplatyKsiegowosc":
                                break;
                            default:
                                break;
                        }
                        break;
                    case 2:
                        /*
                        switch (e.Node.Parent.Parent.Name)
                        {
                                
                            case "WplatyKsiegowosc":
                                switch (e.Node.Parent.Name)
                                {
                                    case "BrakWKsiegowosci":
                                        this.Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.VIEW_KOREKTY.Clear();

                                        command.CommandText += " WHERE YEAR(dataWplaty) = @rok AND (suma_zaplat is null OR (CONVERT(int, suma_zaplat * 100) <> CONVERT(int, BRUTTO * 100))) order by dataWplaty";

                                        command.Parameters.AddWithValue("@rok", e.Node.Name);
                                        sqlDataAdapter.Fill(this.rEKLAMADataSet.VIEW_KOREKTY);
                                        commandExecuted = true;
                                        fakturyDataGridView.Refresh();

                                        this.Cursor = Cursors.Default;

                                        break;

                                    case "BrakWReklamie":
                                        this.Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.VIEW_KOREKTY.Clear();
                                        command.CommandText += " WHERE YEAR(DATA_SPRZEDAZY) = @rok AND (suma_zaplat is not null AND suma_zaplat<>0) AND (dataWplaty is null) order by DATA_SPRZEDAZY";
                                        command.Parameters.AddWithValue("@rok", e.Node.Name);
                                        sqlDataAdapter.Fill(this.rEKLAMADataSet.VIEW_KOREKTY);
                                        commandExecuted = true;
                                        fakturyDataGridView.Refresh();

                                        this.Cursor = Cursors.Default;

                                        break;
                                    default:
                                        break;
                                }
                                break;
                            default:
                                break;
                        }*/
                        break;
                    case 3:
                        switch (e.Node.Parent.Parent.Parent.Name)
                        {
                            case "WplatyKsiegowosc":
                                switch (e.Node.Parent.Parent.Name)
                                {
                                    case "BrakWKsiegowosci":
                                        this.Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE.Clear();
                                        command.CommandText += " WHERE YEAR([dataWplaty]) = @rok AND MONTH(dataWplaty) = @miesiac AND (suma_zaplat is null OR (CONVERT(int, suma_zaplat * 100) <> CONVERT(int, BRUTTO * 100))) order by dataWplaty";
                                        command.Parameters.AddWithValue("@rok", e.Node.Parent.Name);
                                        command.Parameters.AddWithValue("@miesiac", e.Node.Name);
                                        sqlDataAdapter.Fill(this.rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE);
                                        commandExecuted = true;
                                        fakturyDataGridView.Refresh();

                                        this.Cursor = Cursors.Default;
                                        break;

                                    case "BrakWReklamie":
                                        this.Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.VIEW_KOREKTY.Clear();
                                        command.CommandText += " WHERE YEAR(DATA_SPRZEDAZY) = @rok AND MONTH(DATA_SPRZEDAZY) = @miesiac AND (suma_zaplat is not null AND suma_zaplat<>0) AND (dataWplaty is null) order by DATA_SPRZEDAZY";
                                        command.Parameters.AddWithValue("@rok", e.Node.Parent.Name);
                                        command.Parameters.AddWithValue("@miesiac", e.Node.Name);
                                        sqlDataAdapter.Fill(this.rEKLAMADataSet.VIEW_KOREKTY);
                                        commandExecuted = true;
                                        fakturyDataGridView.Refresh();

                                        this.Cursor = Cursors.Default;
                                        break;
                                }
                                break;
                            default:
                                break;
                        }
                        break;
                    default:
                        break;
                }

            }
        }

        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            TreeNode node;
            SqlDataReader reader;

            if (e.Node != null)
            {
                switch (e.Node.Level)
                {
                    case 0:
                        break;
                    case 1:
                        switch (e.Node.Parent.Name)
                        {
                            case "WplatyKsiegowosc":
                                switch (e.Node.Name)
                                {
                                    case "BrakWKsiegowosci":
                                        e.Node.Nodes.Clear();

                                        command.CommandText = "select distinct datepart(year,DATA_W) as rok from dbo.NR where datepart(year,DATA_W) is not null order by rok desc";
                                        command.Connection.Open();
                                        reader = command.ExecuteReader();

                                        while (reader.Read())
                                        {
                                            node = new TreeNode(reader.GetValue(0).ToString());
                                            node.Name = reader.GetValue(0).ToString();

                                            for (int i = 12; i >= 1; i--)
                                            {
                                                TreeNode node2 = new TreeNode(i.ToString());
                                                node2.Name = i.ToString();
                                                //node2.Nodes.Add(new TreeNode());
                                                node.Nodes.Add(node2);
                                            }
                                            e.Node.Nodes.Add(node);
                                        }

                                        command.Connection.Close();

                                        break;
                                    case "BrakWReklamie":
                                        e.Node.Nodes.Clear();
                                        DBBindings.bindujDatyWydan(e.Node);
                                        break;
                                }
                                break;
                            default:
                                e.Node.Nodes.Clear();

                                node = new TreeNode("Biura");
                                node.Name = "Biura";
                                node.Nodes.Add(new TreeNode());
                                e.Node.Nodes.Add(node);
                                break;
                        }
                        break;
                    case 2:

                        switch (e.Node.Name)
                        {
                            case "Biura":
                                DBBindings.dodajAgencjeDoWezla(e.Node);
                                break;
                            default:
                                break;
                        }

                        break;
                    case 3:
                        switch (e.Node.Parent.Name)
                        {
                            case "Biura":
                                DBBindings.dodajAgentowDoWezla(e.Node, e.Node.Name);
                                break;
                            default:
                                break;
                        }
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
            }
        }
   
        private void wyszukajToolStripButton_Click(object sender, EventArgs e)
        {
            wyszukajToolStrip.Visible = wyszukajToolStrip.Visible ? false : true;
        }

        private void szukajToolStripButton_Click(object sender, EventArgs e)
        {
            command.CommandText = query;
            this.rEKLAMADataSet.VIEW_KOREKTY.Clear();

            command.CommandText += " where 1=1 ";
            command.Parameters.Clear();

            if (nrFakturyToolStripTextBox.Text.Trim() != "")
            {
                int i;
                if (!Int32.TryParse(nrFakturyToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj prawidłowy numer faktury.");
                    return;
                }

                command.CommandText += " AND nr_korygowanej=@nr";
                command.Parameters.AddWithValue("@nr", nrFakturyToolStripTextBox.Text.Trim());
            }

            if (nrKorygowanejToolStripTextBox.Text.Trim() != "")
            {
                int i;
                if (!Int32.TryParse(nrKorygowanejToolStripTextBox.Text, out i))
                {
                    MessageBox.Show("Podaj prawidłowy numer faktury.");
                    return;
                }

                command.CommandText += " AND nr_korygowanej=@nr2";
                command.Parameters.AddWithValue("@nr2", nrKorygowanejToolStripTextBox.Text.Trim());
            }


            if (kodRozliczeniowyToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText += " AND NUMER_ROZ like '%' + @kod + '%'";
                command.Parameters.AddWithValue("@kod", kodRozliczeniowyToolStripTextBox.Text.Trim());
            }

            if (rokToolStripTextBox.Text.Trim() != "")
            {
                int i;
                if (!Int32.TryParse(rokToolStripTextBox.Text.Trim(), out i))
                {
                    MessageBox.Show("Podaj prawidłowy rok.");
                    return;
                }

                command.CommandText += " AND YEAR(DATA_WYSTAWIENIA)=@rok";
                command.Parameters.AddWithValue("@rok", rokToolStripTextBox.Text.Trim());
            }

            if (miesiacToolStripTextBox.Text.Trim() != "")
            {
                int i;
                if (!Int32.TryParse(miesiacToolStripTextBox.Text.Trim(), out i))
                {
                    MessageBox.Show("Podaj prawidłowy miesiąc.");
                    return;
                }

                command.CommandText += " AND MONTH(DATA_WYSTAWIENIA)=@miesiac";
                command.Parameters.AddWithValue("@miesiac", miesiacToolStripTextBox.Text.Trim());
            }

            if (agencjaToolStripComboBox.Text.Trim() != "")
            {
                command.CommandText += " AND Agencja=@agencja";
                command.Parameters.AddWithValue("@agencja", agencjaToolStripComboBox.Text.Trim());
            }
            
            /*
            if (((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState == CheckState.Checked)
            {
                command.CommandText += " AND (BRUTTO - suma_zaplat) > 0";
            }
            else if (((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState == CheckState.Unchecked)
            {
                command.CommandText += " AND (BRUTTO - suma_zaplat) <= 0 ";
            }*/
         
            //MessageBox.Show(command.CommandText + nrFakturyToolStripTextBox.Text);
            sqlDataAdapter.SelectCommand = command;

            this.Cursor = Cursors.WaitCursor;

            try
            {
                int t = sqlDataAdapter.Fill(this.rEKLAMADataSet.VIEW_KOREKTY);
                commandExecuted = true;
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }

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

            this.Cursor = Cursors.Default;
        }

        private void fakturyDataGridView_Leave(object sender, EventArgs e)
        {
            fakturyDataGridView.EndEdit();
        }

        private void kryteriumWyszukiwania_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                wyszukajToolStripButton.PerformClick();
            } 
        }
               
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            PrintDGV.Print_DataGridView(fakturyDataGridView,50);
        }

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

            nrFakturyToolStripTextBox.Clear();
            nrKorygowanejToolStripTextBox.Clear();
            kodRozliczeniowyToolStripTextBox.Clear();
            rokToolStripTextBox.Clear();
            miesiacToolStripTextBox.Clear();
            agencjaToolStripComboBox.SelectedIndex = -1;
            agencjaToolStripComboBox.Text = "";
            ((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState = CheckState.Indeterminate;
        }

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

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

        /// <summary>
        /// Przechodzi do okna KLIENCI i wyświetla dane klienta związanego z  fakturą.
        /// </summary>
        private void klientToolStripButton_Click(object sender, EventArgs e)
        {
            if (vIEWKOREKTYBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)vIEWKOREKTYBindingSource.Current;
                REKLAMADataSet.VIEW_KOREKTYRow korekta = (REKLAMADataSet.VIEW_KOREKTYRow)row.Row;
           
                ClientsForm.getClientsForm((MDIBazaReklam)this.MdiParent).pokazKlienta(korekta.CustomerId);
                this.Hide();

                ClientsForm.getClientsForm((MDIBazaReklam)this.MdiParent).Show();
            }   
        }

        private void FacturesForm_Shown(object sender, EventArgs e)
        {
            if (User.getUser().St_kierownik)
            {
                agencjaToolStripComboBox.Text = User.getUser().SymbolAgencji;
            }
            else if (User.getUser().St_handlowiec | User.getUser().St_subhandlowiec)
            {
                kodRozliczeniowyToolStripTextBox.Text = User.getUser().Kod_agenta;
            }

          
        }

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

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

            this.Cursor = Cursors.Default;
        }

        private void fakturyDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (e.ListChangedType == ListChangedType.Reset)
            {
                foreach (DataGridViewRow r in fakturyDataGridView.Rows)
                {
                    if (r.Cells[8].Value != DBNull.Value && r.Cells[9].Value != DBNull.Value)
                    {
                        if (Convert.ToDecimal(r.Cells[8].Value) != Convert.ToDecimal(r.Cells[9].Value))
                        {
                         //   r.DefaultCellStyle.ForeColor = Color.Red;
                        }
                    }
                }
            }
        }

        private void wplata2toolStripButton_Click(object sender, EventArgs e)
        {
            if (vIEWKOREKTYBindingSource.Current != null)
            {
                /*
                DataRowView row = (DataRowView)vIEWKOREKTYBindingSource.Current;
                REKLAMADataSet.KONTAKTYRow f = (REKLAMADataSet.KONTAKTYRow)row.Row;
                
                PaymentForm2 pf2;

                if (f.IsidWplatyNull())
                {
                    pf2 = new PaymentForm2(0,f.ID_FAKTURY);
                }
                else
                {
                    pf2 = new PaymentForm2(f.idWplaty, f.ID_FAKTURY);
                }

                if (pf2.ShowDialog() == DialogResult.OK)
                {
                    f.idWplaty = pf2.IdWplaty;
                    f.EndEdit();
                    fakturyDataGridView.Refresh();
                }*/
                
            }
    
        }

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

                if (!f.IsidZamowieniaNull())
                {
                    ZamowieniaForm zf = new ZamowieniaForm(f.CustomerId, f.idZamowienia);
                    zf.ShowDialog();
                }
            }
        }
    }
}