//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop

#include "Unit4.h"
#include "Paketi\Helper\THelper.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "cxContainer"
#pragma link "cxControls"
#pragma link "cxEdit"
#pragma link "cxGraphics"
#pragma link "cxLabel"
#pragma link "cxLookAndFeelPainters"
#pragma link "cxLookAndFeels"
#pragma link "cxButtons"
#pragma link "cxDBLookupComboBox"
#pragma link "cxDBLookupEdit"
#pragma link "cxDropDownEdit"
#pragma link "cxLookupEdit"
#pragma link "cxMaskEdit"
#pragma link "cxTextEdit"
#pragma link "cxClasses"
#pragma link "cxCustomData"
#pragma link "cxData"
#pragma link "cxDataStorage"
#pragma link "cxDBData"
#pragma link "cxFilter"
#pragma link "cxGrid"
#pragma link "cxGridCustomTableView"
#pragma link "cxGridCustomView"
#pragma link "cxGridDBTableView"
#pragma link "cxGridLevel"
#pragma link "cxGridTableView"
#pragma link "cxNavigator"
#pragma link "cxStyles"
#pragma link "dxDateRanges"
#pragma link "dxScrollbarAnnotations"
#pragma resource "*.dfm"
TForm4 *Form4;
int magacin;
int mnozi_odnos_pjm;
//---------------------------------------------------------------------------
__fastcall TForm4::TForm4(TComponent* Owner)
	: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TForm4::FormCreate(TObject *Sender)
{
	// create
	this->WindowState = wsMaximized;

//	Position = poScreenCenter;

	cdsPricer2->Close();
	cdsPricer2->Open();

	cdsMagacin->Close();
	cdsMagacin->Open();

	magacin = PodrazumevaniMagacin();

    cdsMagacin->Locate("SIFRA_MAGACINA", magacin, TLocateOptions());

}
//---------------------------------------------------------------------------
void __fastcall TForm4::sveClick(TObject *Sender)
{
	// izvezi
	TcxButton *btn = dynamic_cast<TcxButton*>(Sender);
	if(btn->Name == "sve"){
		Export(cdsMagacin->FieldByName("SIFRA_MAGACINA")->AsInteger, 1);
	}else{
		Export(cdsMagacin->FieldByName("SIFRA_MAGACINA")->AsInteger, 0);
	}
}

void __fastcall TForm4::Export(int mg, int sve){

    SIFRA_MAGACINA = mg;
	cdsPricer2->Active = false;
	sdsPricer2->ParamByName("MAG")->AsInteger = mg;
	sdsPricer2->ParamByName("datum")->AsDate = Date();
	 if(sve == 0){
		sdsPricer2->ParamByName("datum_promene")->AsDate = VratiVremeZadnjegUpisa(mg);
	 }else{
		sdsPricer2->ParamByName("datum_promene")->Clear();
	 }
	 cdsPricer2->Active = true;
}

void __fastcall TForm4::IzveziClick(TObject *Sender)
{
	 //
	delimiter = EditDelimiter2->Text.Trim();
	TStringList* fajl = new TStringList();
    WideString naredba;
//    WideString naredba = "001|Barcode | Code | Name | Local name | Sales price | List price | Unit | Cenovnik | Weight | Weight unit | Price unit | Vazi_od | Vazi_do";
//    fajl->Append(naredba);

    SaveDialog1->Title = "Izvoz podataka za Pricer";
    SaveDialog1->DefaultExt = "csv";
    SaveDialog1->Filter = "Text|*.csv|All files|*.*";
    SaveDialog1->InitialDir = "C:\\Price\\upload";
    SaveDialog1->FileName = "item_";

    AnsiString cena, unit_price;
    Currency cena_zs_stampu;
    int mnozi_cenu = mnozi_odnos_pjm;
    char lOldDecimalSeparator = FormatSettings.DecimalSeparator;
    FormatSettings.DecimalSeparator = '.';

    if (SaveDialog1->Execute()) {
        if (!gridView) {
            ShowMessage("Greška: TcxGridDBTableView nije pronađen!");
            delete fajl;
            return;
        }
        cdsPricer2->First();
        while (!cdsPricer2->Eof) {
            try {
                if (cdsPricer2->RecordCount > 0) {
					naredba = "001" + delimiter;

                    for (int i = 0; i < gridView->ColumnCount; i++) {
						TcxGridDBColumn* column = gridView->Columns[i];

						if (!column->Visible) {
							continue;
						}
						String columnName = column->DataBinding->FieldName;
						if (columnName == "cena" || columnName == "unit_price") {
                            if (mnozi_cenu == 0 && cdsPricer2->FieldByName("ODNOSJMNALEPNICE")->AsCurrency > 0) {
                                cena_zs_stampu = cdsPricer2->FieldByName("cena")->AsCurrency / cdsPricer2->FieldByName("ODNOSJMNALEPNICE")->AsCurrency;
								cena = FormatCurr("0.00", cdsPricer2->FieldByName("cena")->AsCurrency) + delimiter;
								unit_price = FormatCurr("0.00", cena_zs_stampu) + delimiter;
							}
							else if (mnozi_cenu == 1 && cdsPricer2->FieldByName("ODNOSJMNALEPNICE")->AsCurrency > 0) {
                                cena_zs_stampu = cdsPricer2->FieldByName("cena")->AsCurrency * cdsPricer2->FieldByName("ODNOSJMNALEPNICE")->AsCurrency;
								cena = FormatCurr("0.00", cena_zs_stampu) + delimiter;
								unit_price = FormatCurr("0.00", cdsPricer2->FieldByName("cena")->AsCurrency) + delimiter;
                            }
                            else {
								cena = FormatCurr("0.00", cdsPricer2->FieldByName("cena")->AsCurrency) + delimiter;
                                unit_price = cena;
                            }

                            if (columnName == "cena") {
                                naredba += cena;
                            } else if (columnName == "unit_price") {
                                naredba += unit_price;
                            }
						}
                        else if (cdsPricer2->FindField(columnName) != NULL) {
							naredba += cdsPricer2->FieldByName(columnName)->AsString + delimiter;
						}  else {
							naredba += delimiter;
						}

                    }
//					ShowMessage(naredba[naredba.Length()]);
//					ShowMessage(delimiter);
//					if (!naredba.IsEmpty() && naredba[naredba.Length()] == delimiter) {
//						naredba = naredba.SubString(1, naredba.Length() - 1);
//					}


                    fajl->Append(naredba);
                }
            }
            catch (Exception &e) {
                ShowMessage(e.Message);
            }
            cdsPricer2->Next();
        }
    }

    FormatSettings.DecimalSeparator = lOldDecimalSeparator;
    fajl->SaveToFile(SaveDialog1->FileName, TEncoding::UTF8);
    delete fajl;

    if (sve == 0) {
        UpisiUPricerLog(SIFRA_MAGACINA);
    }
	ShowMessage("Izvoz zavrsen!!!");

}
String __fastcall TForm4::IzbaciNavodnike(String tekst){
	for (int i = 1; i <= tekst.Length(); i++) {
		if (tekst[i] == '"') {
			tekst[i] = ' ';
		}
    }
	return tekst;
}
TDateTime __fastcall TForm4::VratiVremeZadnjegUpisa(int magacin){

	THelper* helper = new THelper();

	TFDConnection* konekcija = new TFDConnection(nullptr);

	TRezultatOperacije<TFDConnection*>* rezultat = helper->NapraviKonekciju(false); // ako je true onda je udaljeni

	if(rezultat->OperacijaUspela()){
			konekcija = rezultat->DohvatiRezultat();
	}   else{
			AnsiString greska = rezultat->DohvatiGresku();
	}

	TFDQuery *query = new TFDQuery(nullptr);


	query->Connection = konekcija;

	query->SQL->Text = "select first 1 p.datum_promene from pricer_log p "
                  "where p.sifra_magacina = :magacin "
				  "order by 1 desc";
	query->ParamByName("magacin")->AsInteger = magacin;
	query->Open();

	TDateTime vreme = query->FieldByName("datum_promene")->AsDateTime;

    delete rezultat;
	delete konekcija;
	delete helper;
	delete query;
    return vreme;
}
void __fastcall TForm4::UpisiUPricerLog(int mg){

	THelper* helper = new THelper();

	TFDConnection* konekcija = new TFDConnection(nullptr);

	TRezultatOperacije<TFDConnection*>* rezultat = helper->NapraviKonekciju(false); // ako je true onda je udaljeni

	if(rezultat->OperacijaUspela()){
			konekcija = rezultat->DohvatiRezultat();
	}   else{
			AnsiString greska = rezultat->DohvatiGresku();
	}

	TFDQuery *query = new TFDQuery(nullptr);


	query->Connection = konekcija;

	query->SQL->Text =
    "INSERT INTO PRICER_LOG (SIFRA_MAGACINA, DATUM_PROMENE) "
	"VALUES (:SIFRA_MAGACINA, :DATUM_PROMENE)";


	query->ParamByName("SIFRA_MAGACINA")->AsInteger = magacin;
	query->ParamByName("DATUM_PROMENE")->AsDateTime = Now();
	query->ExecSQL();

    delete rezultat;
	delete konekcija;
	delete helper;
	delete query;
}
int __fastcall TForm4::PodrazumevaniMagacin(){
	THelper* helper = new THelper();

	TFDConnection* konekcija = new TFDConnection(nullptr);

	TRezultatOperacije<TFDConnection*>* rezultat = helper->NapraviKonekciju(false); // ako je true onda je udaljeni

	if(rezultat->OperacijaUspela()){
			konekcija = rezultat->DohvatiRezultat();
	}   else{
			AnsiString greska = rezultat->DohvatiGresku();
	}

	TFDQuery *query = new TFDQuery(nullptr);


	query->Connection = konekcija;

	query->SQL->Text =
	"SELECT M.sifra_magacina, F.MNOZI_ODNOS_PJM "
	"FROM HP_FISKAL F "
    "LEFT JOIN TBLKOMITENTI K ON F.SIFRA_DEFAULT_KUPCA = K.SIFRA_KOMITENTA "
	"LEFT JOIN TBLMAGACIN M ON F.DEF_MP_MG = M.SIFRA_MAGACINA";

	query->Open();

	int sifra_magacina = query->FieldByName("sifra_magacina")->AsInteger;
	mnozi_odnos_pjm =  query->FieldByName("MNOZI_ODNOS_PJM")->AsInteger;

	delete rezultat;
	delete konekcija;
	delete helper;
	delete query;

    return sifra_magacina;
}
//---------------------------------------------------------------------------


void __fastcall TForm4::FormResize(TObject *Sender)
{
	  double sirina_dugmeta = Panel2->Width / 3;
	  sve->Width = sirina_dugmeta;
	  promene->Width = sirina_dugmeta;
      Izvezi->Width = sirina_dugmeta;
}
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------

