private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentInvoice == null)
            {
                MainWindow.WarningMessage = ((string)Application.Current.FindResource("Morate_odabrati_fakturu_za_brisanjeUzvičnik"));
                return;
            }

            if (CurrentInvoice.Id < 1)
            {
                var localResult = new InvoiceSQLiteRepository().Delete(CurrentInvoice.Identifier);
                if (localResult.Success)
                {
                    foreach (var item in InvoiceItemsFromDB)
                    {
                        if (item.Invoice != null && item.Invoice.Identifier == CurrentInvoice.Identifier)
                        {
                            var localResultItem = new InvoiceItemSQLiteRepository().Delete(item.Identifier);
                            if (!localResultItem.Success)
                            {
                                MainWindow.ErrorMessage = localResultItem.Message;
                            }
                        }
                    }

                    MainWindow.SuccessMessage = ((string)Application.Current.FindResource("Podaci_su_uspešno_obrisaniUzvičnik"));

                    Thread displayThread = new Thread(() => SyncData());
                    displayThread.IsBackground = true;
                    displayThread.Start();
                }
                else
                {
                    MainWindow.ErrorMessage = localResult.Message;
                }

                return;
            }
            else
            {
                // Delete data
                var result = invoiceService.Delete(CurrentInvoice.Identifier);
                if (result.Success)
                {
                    MainWindow.SuccessMessage = ((string)Application.Current.FindResource("Podaci_su_uspešno_obrisaniUzvičnik"));

                    Thread displayThread = new Thread(() => SyncData());
                    displayThread.IsBackground = true;
                    displayThread.Start();
                }
                else
                {
                    MainWindow.ErrorMessage = result.Message;
                }
            }
        }
        private void DisplayInvoiceItemData()
        {
            InvoiceItemDataLoading = true;

            InvoiceItemListResponse response = new InvoiceItemSQLiteRepository()
                                               .GetInvoiceItemsByInvoice(MainWindow.CurrentCompanyId, CurrentInvoice.Identifier);

            if (response.Success)
            {
                InvoiceItemsFromDB = new ObservableCollection <InvoiceItemViewModel>(
                    response.InvoiceItems ?? new List <InvoiceItemViewModel>());
            }
            else
            {
                InvoiceItemsFromDB = new ObservableCollection <InvoiceItemViewModel>();
            }

            InvoiceItemDataLoading = false;
        }
        private void BtnDelete_Click(object sender, RoutedEventArgs e)
        {
            var response = new InvoiceItemSQLiteRepository().SetStatusDeleted(CurrentInvoiceItemDG.Identifier);

            if (response.Success)
            {
                MainWindow.SuccessMessage = ((string)Application.Current.FindResource("Stavka_je_uspešno_obrisanaUzvičnik"));

                CurrentInvoiceItemForm = new InvoiceItemViewModel()
                {
                    Discount = CurrentInvoice?.Discount?.Amount ?? 0
                };
                CurrentInvoiceItemForm.Identifier = Guid.NewGuid();
                CurrentInvoiceItemForm.ItemStatus = ItemStatus.Added;
                CurrentInvoiceItemForm.IsSynced   = false;
                if (CurrentInvoice.Vat?.Amount != null)
                {
                    CurrentInvoiceItemForm.PDVPercent = CurrentInvoice.Vat.Amount;
                }
                if (CurrentInvoice.Discount?.Amount != null)
                {
                    CurrentInvoiceItemForm.Discount = CurrentInvoice.Discount.Amount;
                }
                if (CurrentInvoice.CurrencyExchangeRate != null)
                {
                    CurrentInvoiceItemForm.ExchangeRate = CurrentInvoice.CurrencyExchangeRate;
                }

                CurrentInvoiceItemDG = null;

                InvoiceCreatedUpdated();

                Thread displayThread = new Thread(() => DisplayInvoiceItemData());
                displayThread.IsBackground = true;
                displayThread.Start();
            }
            else
            {
                MainWindow.ErrorMessage = response.Message;
            }
        }
        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentInvoice == null)
            {
                MainWindow.WarningMessage = ((string)Application.Current.FindResource("Morate_odabrati_fakturu_za_kopiranjeUzvičnik"));
                return;
            }

            var button = ((Button)sender);

            if (btnSemaphore.Wait(0) && button != null)
            {
                button.IsEnabled = false;
                Thread td = new Thread(() =>
                {
                    if (!CanCopyInvoice)
                    {
                        MainWindow.WarningMessage = ((string)Application.Current.FindResource("Morate_odabrati_fakturu_za_kopiranjeUzvičnik"));
                        return;
                    }

                    bool success = true;

                    var newInvoice = new InvoiceViewModel()
                    {
                        Id         = 0,
                        Identifier = Guid.NewGuid(),
                        Code       = "",
                        Address    = CurrentInvoice.Address,
                        Buyer      = CurrentInvoice.Buyer,
                        BuyerName  = CurrentInvoice.BuyerName,
                        City       = CurrentInvoice.City,
                        Company    = new CompanyViewModel()
                        {
                            Id = MainWindow.CurrentCompanyId
                        },
                        CurrencyCode         = CurrentInvoice.CurrencyCode,
                        CurrencyExchangeRate = CurrentInvoice.CurrencyExchangeRate,
                        CreatedBy            = new UserViewModel()
                        {
                            Id = MainWindow.CurrentUserId
                        },
                        DateOfPayment = CurrentInvoice.DateOfPayment,
                        Description   = CurrentInvoice.Description,
                        Discount      = CurrentInvoice.Discount,
                        InvoiceDate   = CurrentInvoice.InvoiceDate,
                        DueDate       = CurrentInvoice.DueDate,
                        IsSynced      = false,
                        IsActive      = true,
                        Municipality  = CurrentInvoice.Municipality,
                        PdvType       = CurrentInvoice.PdvType,
                        Status        = ItemStatus.Added,
                        StatusDate    = DateTime.Now,
                        TotalPDV      = CurrentInvoice.TotalPDV,
                        TotalPrice    = CurrentInvoice.TotalPrice,
                        TotalRebate   = CurrentInvoice.TotalRebate,
                        Vat           = CurrentInvoice.Vat
                    };

                    var response = new InvoiceSQLiteRepository().Create(newInvoice);
                    if (response.Success)
                    {
                        var itemResponse = new InvoiceItemSQLiteRepository().GetInvoiceItemsByInvoice(MainWindow.CurrentCompanyId, CurrentInvoice.Identifier);
                        if (itemResponse.Success)
                        {
                            var itemsToCopy = itemResponse?.InvoiceItems ?? new List <InvoiceItemViewModel>();
                            foreach (var item in itemsToCopy)
                            {
                                var newItem = new InvoiceItemViewModel()
                                {
                                    Invoice = newInvoice,
                                    Amount  = item.Amount,
                                    Code    = item.Code,
                                    Company = new CompanyViewModel()
                                    {
                                        Id = MainWindow.CurrentCompanyId
                                    },
                                    CreatedBy = new UserViewModel()
                                    {
                                        Id = MainWindow.CurrentUserId
                                    },
                                    CurrencyCode         = item.CurrencyCode,
                                    CurrencyPriceWithPDV = item.CurrencyPriceWithPDV,
                                    Discount             = item.Discount,
                                    ExchangeRate         = item.ExchangeRate,
                                    Id              = 0,
                                    Identifier      = Guid.NewGuid(),
                                    IsActive        = true,
                                    IsSynced        = false,
                                    ItemStatus      = ItemStatus.Submited,
                                    Name            = item.Name,
                                    PDV             = item.PDV,
                                    PDVPercent      = item.PDVPercent,
                                    PriceWithoutPDV = item.PriceWithoutPDV,
                                    PriceWithPDV    = item.PriceWithPDV,
                                    Quantity        = item.Quantity,
                                    UnitOfMeasure   = item.UnitOfMeasure,
                                };
                                var itemCreateResponse = new InvoiceItemSQLiteRepository().Create(newItem);
                                if (!itemCreateResponse.Success)
                                {
                                    MainWindow.ErrorMessage = itemCreateResponse.Message;
                                    success = false;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            MainWindow.ErrorMessage = itemResponse.Message;
                            success = false;
                        }
                    }
                    else
                    {
                        MainWindow.ErrorMessage = response.Message;
                        success = false;
                    }

                    if (success)
                    {
                        MainWindow.SuccessMessage = (string)Application.Current.FindResource("Kopiranje_je_uspešno_izvršenoUzvičnik");
                    }
                    else
                    {
                        MainWindow.WarningMessage = (string)Application.Current.FindResource("Došlo_je_do_greške_pri_kopiranju_proverite_stanje_faktureUzvičnik");
                    }

                    DisplayData();

                    Dispatcher.BeginInvoke((Action)(() =>
                    {
                        btnSemaphore.Release();
                        if (button != null)
                        {
                            button.IsEnabled = true;
                        }
                    }));
                });

                td.IsBackground = true;
                td.Start();
            }
        }
        private async void MetroWindow_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            Thread td = new Thread(() =>
            {
                List <ServiceInterfaces.ViewModels.Common.Invoices.InvoiceItemViewModel> itemsFromDB = new List <ServiceInterfaces.ViewModels.Common.Invoices.InvoiceItemViewModel>();

                var response = new InvoiceItemSQLiteRepository().GetInvoiceItemsByInvoice(MainWindow.CurrentCompanyId, CurrentInvoice.Identifier);

                if (response.Success)
                {
                    itemsFromDB.AddRange(response.InvoiceItems ?? new List <ServiceInterfaces.ViewModels.Common.Invoices.InvoiceItemViewModel>());
                }

                Dispatcher.BeginInvoke(new Action(() =>
                {
                    rdlcInvoiceReport.LocalReport.DataSources.Clear();
                }));



                List <RdlcReports.Invoices.InvoiceItemViewModel> items = new List <RdlcReports.Invoices.InvoiceItemViewModel>();

                int id = 1;
                foreach (var item in itemsFromDB)
                {
                    var quantity = GetFormatted((double)item.Quantity, "00");

                    double?priceWithoutPDVSuffix = null;
                    double?priceWithPDVSuffix    = null;
                    double?amountSuffix          = null;
                    double?pdvValueSuffix        = null;
                    double?rebateSuffix          = null;

                    if (CurrentInvoice.CurrencyExchangeRate != null)
                    {
                        priceWithoutPDVSuffix = (double)((double)item.BaseAfterDiscount / CurrentInvoice.CurrencyExchangeRate.Value);
                        priceWithPDVSuffix    = (double)((double)(item.BaseAfterDiscount + item.PDV) / CurrentInvoice.CurrencyExchangeRate.Value);
                        amountSuffix          = (double)((double)item.Amount / CurrentInvoice.CurrencyExchangeRate.Value);
                        pdvValueSuffix        = (double)((double)item.PDV / CurrentInvoice.CurrencyExchangeRate.Value);
                        rebateSuffix          = (double)((double)item.TotalDiscount / CurrentInvoice.CurrencyExchangeRate.Value);
                    }

                    items.Add(new RdlcReports.Invoices.InvoiceItemViewModel()
                    {
                        Id          = (id++).ToString(),
                        ProductCode = item.Code,
                        ProductName = item.Name + Environment.NewLine
                                      + CurrentInvoice.CurrencyCode,
                        UnitOfMeasurement = item.UnitOfMeasure,
                        Quantity          = quantity + Environment.NewLine + quantity,
                        PDVPercent        = item.PDVPercent + "%",
                        PriceWithoutPDV   = GetFormatted((double)item.BaseAfterDiscount) + Environment.NewLine
                                            + GetFormatted(priceWithoutPDVSuffix),
                        PriceWithPDV = GetFormatted((double)(item.BaseAfterDiscount + item.PDV)) + Environment.NewLine
                                       + GetFormatted(priceWithPDVSuffix),
                        Amount = GetFormatted((double)item.Amount) + Environment.NewLine
                                 + GetFormatted(amountSuffix),
                        PDVValue = GetFormatted((double)item.PDV) + Environment.NewLine
                                   + GetFormatted(pdvValueSuffix),
                        Rebate = GetFormatted((double)item.TotalDiscount) + Environment.NewLine
                                 + GetFormatted(rebateSuffix)
                    });
                }

                var buyerResponse = new BusinessPartnerSQLiteRepository().GetBusinessPartner(CurrentInvoice.Buyer.Identifier);

                BusinessPartnerViewModel buyer = buyerResponse?.BusinessPartner;


                double sumOfAmount           = (double)itemsFromDB.Sum(x => x.Amount);
                double sumOfAmountInCurrency = (double)itemsFromDB.Sum(x => x.CurrencyPriceWithPDV);
                double sumOfBase             = (double)itemsFromDB.Sum(x => x.BaseAfterDiscount); // sum of base
                double sumOfPDV            = (double)itemsFromDB.Sum(x => x.PDV);                 // sum of base
                double?sumOfBaseInCurrency = null;

                if (CurrentInvoice.CurrencyExchangeRate != null)
                {
                    sumOfBaseInCurrency = (double)(sumOfBase / CurrentInvoice.CurrencyExchangeRate);
                }
                WpfAppCommonCode.Helpers.BrojUTekst brText = new WpfAppCommonCode.Helpers.BrojUTekst()
                {
                    Hrvatskezik = false
                };

                string preFormattedText = GetFormatted(sumOfAmount, "00");
                string textFormTotal    = brText.PretvoriBrojUTekst(preFormattedText, ',', "RSD", "");

                List <RdlcReports.Invoices.InvoiceViewModel> invoice = new List <RdlcReports.Invoices.InvoiceViewModel>()
                {
                    new RdlcReports.Invoices.InvoiceViewModel()
                    {
                        InvoiceNumber                  = CurrentInvoice.InvoiceNumber,
                        CityAndInvoiceDate             = CurrentInvoice.City?.Name + ", " + CurrentInvoice.InvoiceDate.ToString("dd.MM.yyyy"),
                        DeliveryDateOfGoodsAndServices = CurrentInvoice.DateOfPayment?.ToString("dd.MM.yyyy"),
                        DueDate = CurrentInvoice.DueDate.ToString("dd.MM.yyyy"),

                        BusinessPartnerCode    = buyer?.InternalCode,
                        BusinessPartnerPIB     = buyer?.PIB,
                        BusinessPartnerMB      = buyer.IdentificationNumber,
                        BusinessPartnerName    = buyer?.Name,
                        BusinessPartnerAddress = CurrentInvoice.Address,
                        BusinessPartnerCity    = CurrentInvoice.City?.ZipCode + " " + CurrentInvoice.City?.Name,

                        Amount           = GetFormatted((double)sumOfBase),
                        AmountInCurrency = (CurrentInvoice?.CurrencyExchangeRate == null ? "" : GetFormatted((double)sumOfBaseInCurrency)),

                        TotalAmount           = GetFormatted((double)sumOfAmount),
                        TotalAmountInCurrency = (CurrentInvoice?.CurrencyExchangeRate == null ? "" : GetFormatted((double)sumOfAmountInCurrency)),
                        TotalBase             = GetFormatted((double)sumOfBase),

                        TotalPDV = GetFormatted((double)sumOfPDV),

                        TotalAmountInText = textFormTotal
                    }
                };


                Dispatcher.BeginInvoke(new Action(() =>
                {
                    var rpdsModel = new ReportDataSource()
                    {
                        Name  = "Invoices",
                        Value = invoice
                    };

                    var rdpsitems = new ReportDataSource()
                    {
                        Name  = "InvoiceItems",
                        Value = items
                    };
                    rdlcInvoiceReport.LocalReport.DataSources.Add(rpdsModel);
                    rdlcInvoiceReport.LocalReport.DataSources.Add(rdpsitems);

                    string exeFolder = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

                    switch (CurrentInvoice.PdvType)
                    {
                    case 1:     // sa pdv
                        {
                            string ContentStart = @"SirmiumERPGFC.RdlcReports.Invoices.Invoice_WithPDV.rdlc";
                            rdlcInvoiceReport.LocalReport.ReportEmbeddedResource = ContentStart;
                            break;
                        }

                    case 2:     // bez pdv
                        {
                            string ContentStart = @"SirmiumERPGFC.RdlcReports.Invoices.Invoice_WithoutPDV.rdlc";
                            rdlcInvoiceReport.LocalReport.ReportEmbeddedResource = ContentStart;
                            break;
                        }

                    case 3:     // nije u sistemu pdv
                        {
                            string ContentStart = @"SirmiumERPGFC.RdlcReports.Invoices.Invoice_NotInPDV.rdlc";
                            rdlcInvoiceReport.LocalReport.ReportEmbeddedResource = ContentStart;
                            break;
                        }
                    }
                    //rdlcInvoiceReport.LocalReport.ReportPath = ContentStart;
                    // rdlcInputInvoiceReport.LocalReport.SetParameters(reportParams);
                    rdlcInvoiceReport.SetDisplayMode(DisplayMode.PrintLayout);
                    rdlcInvoiceReport.Refresh();
                    rdlcInvoiceReport.ZoomMode    = ZoomMode.Percent;
                    rdlcInvoiceReport.ZoomPercent = 100;
                    rdlcInvoiceReport.RefreshReport();
                }));
            });

            td.IsBackground = true;
            td.Start();
        }
        private void BtnSubmit_Click(object sender, RoutedEventArgs e)
        {
            #region Validation

            if (CurrentBusinessPartnerInvoice == null)
            {
                MainWindow.WarningMessage = ((string)Application.Current.FindResource("Obavezno_polje_poslovni_partner"));
                return;
            }

            #endregion

            Thread td = new Thread(() => {
                SubmitButtonContent     = ((string)Application.Current.FindResource("Čuvanje_u_tokuTriTacke"));
                SubmitButtonEnabled     = false;
                CurrentInvoice.Buyer    = CurrentBusinessPartnerInvoice;
                CurrentInvoice.IsSynced = false;
                CurrentInvoice.Company  = new CompanyViewModel()
                {
                    Id = MainWindow.CurrentCompanyId
                };
                CurrentInvoice.CreatedBy = new UserViewModel()
                {
                    Id = MainWindow.CurrentUserId
                };

                var itemsResponse = new InvoiceItemSQLiteRepository().GetInvoiceItemsByInvoice(MainWindow.CurrentCompanyId, CurrentInvoice.Identifier);

                if (itemsResponse.InvoiceItems != null)
                {
                    CurrentInvoice.InvoiceItems = new ObservableCollection <InvoiceItemViewModel>(itemsResponse?.InvoiceItems ?? new List <InvoiceItemViewModel>());
                    foreach (var item in CurrentInvoice.InvoiceItems)
                    {
                        item.PDVPercent = CurrentInvoice.Vat?.Amount ?? 0;
                        item.ItemStatus = ItemStatus.Edited;
                        new InvoiceItemSQLiteRepository().Delete(item.Identifier);
                        new InvoiceItemSQLiteRepository().Create(item);
                    }
                }

                CurrentInvoice.TotalPrice = CurrentInvoice.InvoiceItems.Sum(x => (double)x.PriceWithPDV);

                InvoiceResponse response = new InvoiceSQLiteRepository().Create(CurrentInvoice);
                if (!response.Success)
                {
                    MainWindow.ErrorMessage = ((string)Application.Current.FindResource("Greška_kod_lokalnog_čuvanjaUzvičnik"));
                    SubmitButtonContent     = ((string)Application.Current.FindResource("Proknjiži"));
                    SubmitButtonEnabled     = true;
                }

                response = outputInvoiceService.Create(CurrentInvoice);
                if (!response.Success)
                {
                    MainWindow.ErrorMessage = ((string)Application.Current.FindResource("Podaci_su_sačuvani_u_lokaluUzvičnikTačka_Greška_kod_čuvanja_na_serveruUzvičnik")) + response.Message;
                    SubmitButtonContent     = ((string)Application.Current.FindResource("Proknjiži"));
                    SubmitButtonEnabled     = true;
                }

                if (response.Success)
                {
                    MainWindow.SuccessMessage = ((string)Application.Current.FindResource("Podaci_su_uspešno_sačuvaniUzvičnik"));
                    SubmitButtonContent       = ((string)Application.Current.FindResource("Proknjiži"));
                    SubmitButtonEnabled       = true;

                    new InvoiceSQLiteRepository().Sync(outputInvoiceService);

                    InvoiceCreatedUpdated();

                    Application.Current.Dispatcher.BeginInvoke(
                        System.Windows.Threading.DispatcherPriority.Normal,
                        new Action(() =>
                    {
                        FlyoutHelper.CloseFlyout(this);
                    })
                        );
                }
            });
            td.IsBackground = true;
            td.Start();
        }
        private void btnAddNote_Click(object sender, RoutedEventArgs e)
        {
            #region Validation

            //if (CurrentInvoiceItemForm.Note == null)
            //{
            //    MainWindow.ErrorMessage = ((string)Application.Current.FindResource("Obavezno_poljeDvotačka_Napomena"));
            //    return;
            //}

            #endregion
            Thread th = new Thread(() =>
            {
                SubmitButtonEnabled            = false;
                CurrentInvoiceItemForm.Invoice = CurrentInvoice;

                CurrentInvoiceItemForm.Company = new CompanyViewModel()
                {
                    Id = MainWindow.CurrentCompanyId
                };
                CurrentInvoiceItemForm.CreatedBy = new UserViewModel()
                {
                    Id = MainWindow.CurrentUserId
                };

                new InvoiceItemSQLiteRepository().Delete(CurrentInvoiceItemForm.Identifier);

                var response = new InvoiceItemSQLiteRepository().Create(CurrentInvoiceItemForm);
                if (!response.Success)
                {
                    MainWindow.ErrorMessage = response.Message;

                    CurrentInvoiceItemForm            = new InvoiceItemViewModel();
                    CurrentInvoiceItemForm.Identifier = Guid.NewGuid();
                    CurrentInvoiceItemForm.ItemStatus = ItemStatus.Added;
                    CurrentInvoiceItemForm.IsSynced   = false;
                    if (CurrentInvoice.Vat?.Amount != null)
                    {
                        CurrentInvoiceItemForm.PDVPercent = CurrentInvoice.Vat.Amount;
                    }
                    if (CurrentInvoice.Discount?.Amount != null)
                    {
                        CurrentInvoiceItemForm.Discount = CurrentInvoice.Discount.Amount;
                    }
                    if (CurrentInvoice.CurrencyExchangeRate != null)
                    {
                        CurrentInvoiceItemForm.ExchangeRate = CurrentInvoice.CurrencyExchangeRate;
                    }
                    return;
                }
                CurrentInvoiceItemForm = new InvoiceItemViewModel()
                {
                    Discount = CurrentInvoice?.Discount?.Amount ?? 0
                };
                CurrentInvoiceItemForm.Identifier = Guid.NewGuid();
                CurrentInvoiceItemForm.ItemStatus = ItemStatus.Added;
                CurrentInvoiceItemForm.IsSynced   = false;
                if (CurrentInvoice.Vat?.Amount != null)
                {
                    CurrentInvoiceItemForm.PDVPercent = CurrentInvoice.Vat.Amount;
                }
                if (CurrentInvoice.Discount?.Amount != null)
                {
                    CurrentInvoiceItemForm.Discount = CurrentInvoice.Discount.Amount;
                }
                if (CurrentInvoice.CurrencyExchangeRate != null)
                {
                    CurrentInvoiceItemForm.ExchangeRate = CurrentInvoice.CurrencyExchangeRate;
                }

                //PriceWithPDV * Discount / 100


                InvoiceCreatedUpdated();

                DisplayInvoiceItemData();

                Application.Current.Dispatcher.BeginInvoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(() =>
                {
                    txtName.Focus();
                })
                    );

                SubmitButtonEnabled = true;
            });
            th.IsBackground = true;
            th.Start();
        }