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

namespace Baza_Reklam
{
    public partial class FacturesFormNEW : Form
    {
        private const string query = "SELECT top 2000 * from VIEW_ZESTAWIENIE_FAKTUR_NOWE ";

        private static FacturesFormNEW fakturesForm;
        private readonly SqlCommand command;
        private readonly SqlDataAdapter sqlDataAdapter;

        private bool commandExecuted;

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

        private FacturesFormNEW(Form parent)
        {
            InitializeComponent();

            MdiParent = parent;

            //podmiana connstringa
            VIEW_ZESTAWIENIE_FAKTUR_NOWETableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
            reklamaTableAdapter.Connection.ConnectionString = ConnString.getConnString().Value;
         
            //obiekty wykorzytywane przy wyszukiwaniu
            SqlConnection conn = new SqlConnection(ConnString.getConnString().Value);
           
            command = new SqlCommand();
            command.CommandType = CommandType.Text;
            command.Connection = conn;
            
            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;

            PoznanKatowicetoolStripButton.Enabled = User.getUser().St_produkcja;
        }

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

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

        private void generateNodes()
        {
            TreeNode 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":
                                        Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE.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(rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE);
                                        commandExecuted = true;
                                        fakturyDataGridView.Refresh();

                                        Cursor = Cursors.Default;

                                        break;

                                    case "BrakWReklamie":
                                        Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE.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(rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE);
                                        commandExecuted = true;
                                        fakturyDataGridView.Refresh();

                                        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":
                                        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(rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE);
                                        commandExecuted = true;
                                        fakturyDataGridView.Refresh();

                                        Cursor = Cursors.Default;
                                        break;

                                    case "BrakWReklamie":
                                        Cursor = Cursors.WaitCursor;

                                        rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE.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(rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE);
                                        commandExecuted = true;
                                        fakturyDataGridView.Refresh();

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

                                        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;
                                }
                                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 fakturyDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            VIEW_ZESTAWIENIE_FAKTUR_NOWEBindingSource.CancelEdit();
        }
       
        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;

            rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE.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 NUMER=@nr";
                command.Parameters.AddWithValue("@nr", nrFakturyToolStripTextBox.Text.Trim());
            }

            if (kodRozliczeniowyToolStripTextBox.Text.Trim() != "")
            {
                command.CommandText += " AND NR_FK 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_SPRZEDAZY)=@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_SPRZEDAZY)=@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 ((waluta_miano IS NOT NULL AND ROUND((waluta_brutto - wplata_waluta_brutto), 0) > 1)";
                command.CommandText += " OR (waluta_miano IS NULL AND ROUND((BRUTTO - suma_zaplat), 0) > 1))";
            }
            else if (((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState == CheckState.Unchecked)
            {
                command.CommandText += " AND ((waluta_miano IS NOT NULL AND ROUND((waluta_brutto - wplata_waluta_brutto), 0) <= 1)";
                command.CommandText += " OR (waluta_miano IS NULL AND ROUND((BRUTTO - suma_zaplat), 0) <= 1))";
            }

            if (!string.IsNullOrEmpty(cbSposobZaplaty.Text.Trim()))
            {
                command.CommandText += " AND SposobZaplaty=@sposobZaplaty";
                command.Parameters.AddWithValue("@sposobZaplaty", cbSposobZaplaty.Text.Trim());
            }
         
            //MessageBox.Show(command.CommandText + nrFakturyToolStripTextBox.Text);
            sqlDataAdapter.SelectCommand = command;

            Cursor = Cursors.WaitCursor;

            try
            {
                sqlDataAdapter.Fill(rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE);
                commandExecuted = true;
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }

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

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

        /// <summary>
        /// Podsumowuje brutto i zaplate z wyswietlonych faktur
        /// </summary>
        private void podsumuj() {

            if (VIEW_ZESTAWIENIE_FAKTUR_NOWEBindingSource.List.Count != 0)
            {
            decimal brutto = Convert.ToDecimal(rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE.Compute("Sum(BRUTTO)",""));
            decimal netto = Convert.ToDecimal(rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE.Compute("Sum(netto)", ""));

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

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

        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();
            kodRozliczeniowyToolStripTextBox.Clear();
            rokToolStripTextBox.Clear();
            miesiacToolStripTextBox.Clear();
            agencjaToolStripComboBox.SelectedIndex = -1;
            agencjaToolStripComboBox.Text = "";
            ((CheckBox)((ToolStripControlHost)wyszukajToolStrip.Items["zalegleCheckBox"]).Control).CheckState = CheckState.Indeterminate;
            cbSposobZaplaty.SelectedIndex = -1;
            cbSposobZaplaty.Text = string.Empty;
        }

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

                Cursor = Cursors.WaitCursor;
                FactureViewer fv = new FactureViewer(faktura.ID_FAKTURY,false);
                fv.ShowDialog();
                
                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 (VIEW_ZESTAWIENIE_FAKTUR_NOWEBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)VIEW_ZESTAWIENIE_FAKTUR_NOWEBindingSource.Current;
                
                int custID = Convert.ToInt32(row["ID_NABYWCY"]);
                ClientsForm.getClientsForm((MDIBazaReklam)MdiParent).pokazKlienta(custID);

                Hide();

                ClientsForm.getClientsForm((MDIBazaReklam)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)
        {
            Cursor = Cursors.WaitCursor;

            ExcelHandler ex = new ExcelHandler();
            ex.exportToExcel(fakturyDataGridView);

            Cursor = Cursors.Default;
        }

        private void fakturyDataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            if (e.ListChangedType == ListChangedType.Reset)
            {
                foreach (DataGridViewRow r in fakturyDataGridView.Rows)
                {
                    DataRowView row = (DataRowView)r.DataBoundItem;
                    REKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWERow
                    fakt = (REKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWERow)
                    row.Row;

                    if (fakt.ilEmisji != fakt.ilPozycji)
                    {
                        r.DefaultCellStyle.ForeColor = Color.Crimson;
                    }
                }
            }
        }

        private void wplata2toolStripButton_Click(object sender, EventArgs e)
        {
            if (VIEW_ZESTAWIENIE_FAKTUR_NOWEBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)VIEW_ZESTAWIENIE_FAKTUR_NOWEBindingSource.Current;
                REKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWERow f = (REKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWERow)row.Row;

                PaymentForm2 pf2 = f.IsidWplatyNull() ? new PaymentForm2(0,f.ID_FAKTURY) : 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 (VIEW_ZESTAWIENIE_FAKTUR_NOWEBindingSource.Current != null)
            {
                DataRowView row = (DataRowView)VIEW_ZESTAWIENIE_FAKTUR_NOWEBindingSource.Current;
                REKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWERow f = (REKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWERow)row.Row;

                ZamowieniaForm zf = new ZamowieniaForm(f.ID_NABYWCY,f.idZamowienia);
                zf.ShowDialog();
            }
        }

        private void PoznanKatowicetoolStripButton_Click(object sender, EventArgs e)
        {
            FakturowaniePoznanKatowice fpk = new FakturowaniePoznanKatowice();
            fpk.ShowDialog();
        }

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

                rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE.Clear();
                sqlDataAdapter.Fill(rEKLAMADataSet.VIEW_ZESTAWIENIE_FAKTUR_NOWE);
                fakturyDataGridView.Refresh();

                Cursor = Cursors.Default;
            }
        }
    }
}