<?php

include_once(DATEIPFAD . 'includes/classes/PaymentInterface.cls.php');

function paymentInterfaceAutoloader($className) {
    $pathAndFilename = DATEIPFAD . 'plugins/paymentInterfaces/' . $className . '/' . $className . '.cls.php';
    if(file_exists($pathAndFilename))
        include_once($pathAndFilename);
}

spl_autoload_register('paymentInterfaceAutoloader');

/**
 * Scans the plugins/paymentInterfaces Directory for new PlugIns and updates the database accordingly */
function scanPlugins()
{
   $dirHandle = opendir(DATEIPFAD . 'plugins/paymentInterfaces/');
    while($entry = readdir($dirHandle)) {
        if(substr($entry, 0, 1) != '.') { // ignore . .. and hidden dirs like .svn
            if(class_exists($entry)) {
                savePaymentInterface($entry);
            }
        }
    }
}

function savePaymentInterface($className) {
    $SQLString = 'SELECT COUNT(*) FROM ' . TABLE_ZAHLUNGSSCHNITTSTELLEN . ' WHERE classname = \'' . $className . '\'';
    $row = mysql_fetch_row(errorlogged_mysql_query($SQLString));
    if($row[0] == 0) {
        $SQLString = 'INSERT INTO ' . TABLE_ZAHLUNGSSCHNITTSTELLEN . ' SET ';
        $SQLString .= TABLE_ZAHLUNGSSCHNITTSTELLEN . '.classname = \'' . $className . '\'';
        errorlogged_mysql_query($SQLString);
    }
}

function getPaymentInterfacesArray() {
    $SQLString = 'SELECT ';
    $SQLString .= TABLE_ZAHLUNGSSCHNITTSTELLEN . '.id';
    $SQLString .= ', ' . TABLE_ZAHLUNGSSCHNITTSTELLEN . '.classname';
    $SQLString .= ' FROM ' . TABLE_ZAHLUNGSSCHNITTSTELLEN;
    $result = errorlogged_mysql_query($SQLString);

    $paymentInterfacesArray = array();
    while($row = mysql_fetch_row($result)) {
        if(class_exists($row[1])) {
            $paymentInterface = new $row[1]();
            $paymentInterfacesArray[$row[0]] = $paymentInterface;
        }
    }
    return $paymentInterfacesArray;
}

/**
 * @param $paymentInterfaceID
 * @return PaymentInterface
 */
function getPaymentInterface($paymentInterfaceID, $locale = false) {
    $SQLString = 'SELECT ';
    $SQLString .= TABLE_ZAHLUNGSSCHNITTSTELLEN . '.classname';
    $SQLString .= ' FROM ' . TABLE_ZAHLUNGSSCHNITTSTELLEN;
    $SQLString .= ' WHERE id =\'' .$paymentInterfaceID . '\'';
    $result = errorlogged_mysql_query($SQLString);
    $row = mysql_fetch_row($result);
    if(!class_exists($row[0])) {
        return false;
    }
    $paymentInterface = new $row[0];

    // Config Daten für diese Zahlungsschnittstelle gleich mit laden und dem Objekt übergeben
    $paymentInterface->setConfig(getPaymentInterfaceParams($paymentInterfaceID));

    if($locale)
        $paymentInterface->setLocale($locale);

    return $paymentInterface;
}

function savePaymentInterfaceParams($paymentInterfaceID, $paramValues) {
    foreach($paramValues as $paramName => $paramValue) {
        $SQLString = 'INSERT INTO ' . TABLE_ZAHLUNGSSCHNITTSTELLEN_CONFIG . ' SET ';
        $SQLString .= 'zahlungsschnittstelle_id = \'' . $paymentInterfaceID . '\'';
        $SQLString .= ', param_name = \'' . $paramName . '\'';
        $SQLString .= ', param_value = \'' . $paramValue . '\'';
        $SQLString .= ' ON DUPLICATE KEY UPDATE ';
        $SQLString .= 'param_value = \'' . $paramValue . '\'';
        errorlogged_mysql_query($SQLString);
    }
}

function getPaymentInterfaceParams($paymentInterfaceID) {
    $SQLString = 'SELECT param_name, param_value FROM ' . TABLE_ZAHLUNGSSCHNITTSTELLEN_CONFIG . ' WHERE zahlungsschnittstelle_id = \'' . $paymentInterfaceID . '\'';
    $result = errorlogged_mysql_query($SQLString);
    $params = array();
    while($row = mysql_fetch_assoc($result)) {
        $params[$row['param_name']] = $row['param_value'];
    }
    return $params;
}

function createPaymentInterfaceOrderFromBestellObject($BestellObject, $WaehrungObject, $KundenObject) {
    $orderObject = new OrderData();
    $orderObject->orderID = $BestellObject->id;
    $orderObject->orderNumber = $BestellObject->auftragsnummer;
    foreach($BestellObject->warenkorbdataarray["warenkorbarray"] as $warenkorbentry) {
        $cartItem = new CartItem();
        $cartItem->name = $warenkorbentry['artikel_name'];
        $cartItem->number = $warenkorbentry['artikel_nr'];
        $cartItem->quantity = $warenkorbentry['menge'];
        $cartItem->amount = $warenkorbentry['preis'];
        $cartItem->vat = $warenkorbentry['mwst'];
        $orderObject->cartItems[] = $cartItem;
    }
    $currencyObject = new CurrencyData();
    $currencyObject->ISOCode = $WaehrungObject->isocode;
    $currencyObject->symbol = $WaehrungObject->symbol;
    $orderObject->currency = $currencyObject;
    $customerObject = new CustomerData();
    $customerObject->customerID = $KundenObject->id;
    $customerObject->phone = $KundenObject->telefon;
    $customerObject->email = $KundenObject->email;
    $KundenAnredeObject = GetKundenanredeDetail($KundenObject->kundenanredeid);
    $customerObject->gender = ($KundenAnredeObject->geschlecht=='w'?'f':$KundenAnredeObject->geschlecht);
    $invoiceAddress = new AddressData();
    $invoiceAddress->firstName = $KundenObject->vorname;
    $invoiceAddress->lastName = $KundenObject->nachname;
    $invoiceAddress->city = $KundenObject->ort;
    $invoiceCountry = new CountryData();

    $landObject = GetLandDetails($KundenObject->land);
    $invoiceCountry->isocode = $landObject->isocode;
    $invoiceCountry->name = $landObject->name;
    $invoiceAddress->country = $invoiceCountry;
    if($KundenObject->bundesstaat) {
        $invoiceState = new StateData();
        $bundesstaat = GetBundesstaat($KundenObject->bundesstaat);
        $invoiceState->name = $bundesstaat->name;
        $invoiceState->code = $bundesstaat->code;
        $invoiceAddress->state = $invoiceState;
    }
    $invoiceAddress->street = $KundenObject->strasse;
    $invoiceAddress->houseNumber = $KundenObject->hausnummer;
    $invoiceAddress->zipCode = $KundenObject->plz;
    $invoiceAddress->city = $KundenObject->ort;
    $customerObject->invoiceAddress = $invoiceAddress;
    if($KundenObject->lieferung) {
        $deliveryAddress = new AddressData();
        $deliveryAddress->firstName = $KundenObject->la_vorname;
        $deliveryAddress->lastName = $KundenObject->la_nachname;
        $deliveryAddress->city = $KundenObject->la_ort;
        $deliveryCountry = new CountryData();
        $landObject = GetLandDetails($KundenObject->la_land);
        $deliveryCountry->isocode = $landObject->isocode;
        $deliveryCountry->name = $landObject->name;
        $deliveryAddress->country = $deliveryCountry;
        if($KundenObject->la_bundesstaat) {
            $deliveryState = new StateData();
            $bundesstaat = GetBundesstaat($KundenObject->la_bundesstaat);
            $deliveryState->name = $bundesstaat->name;
            $deliveryState->code = $bundesstaat->code;
            $deliveryAddress->state = $deliveryState;
        }
        $deliveryAddress->street = $KundenObject->la_strasse;
        $deliveryAddress->houseNumber = $KundenObject->la_hausnummer;
        $deliveryAddress->zipCode = $KundenObject->la_plz;
        $deliveryAddress->city = $KundenObject->la_ort;
        $customerObject->deliveryAddress = $deliveryAddress;
    }

    switch($BestellObject->kundengruppentype) {
        case 1:
            $customerObject->type = CustomerData::END_CUSTOMER;
            break;
        case 2:
            $customerObject->type = CustomerData::BUSINESS_CUSTOMER;
            break;
        case 3:
            $customerObject->type = CustomerData::FOREIGN_CUSTOMER;
            break;
    }

    $orderObject->customer = $customerObject;
    if(floatval($BestellObject->rabatt_betrag) != 0) {
        $discountObject = new DiscountData();
        $discountObject->amount = -$BestellObject->rabatt_betrag;
        $discountObject->name = $BestellObject->rabatt_name;
        $discountObject->percent = $BestellObject->rabatt_prozent;
        $orderObject->discount = $discountObject;
    }

    if($BestellObject->gutscheincode) {
        $voucherObject = new VoucherData();
        $voucherObject->amount = -$BestellObject->gutschein_betrag;
        $voucherObject->name = $BestellObject->gutscheinaktion_name;
        $voucherObject->code = $BestellObject->gutscheincode;
        $orderObject->voucher = $voucherObject;
    }

    $orderObject->itemAmount = $BestellObject->warenwert;
    if($BestellObject->gesamtsumme_alternativ) {
        $orderObject->totalAmount = $BestellObject->gesamtsumme_alternativ;
    } else {
        $orderObject->totalAmount = $BestellObject->gesamtsumme;
    }

    $orderObject->paymentFeeAmount = $BestellObject->zahlungsart_preis;
    $orderObject->shippingFeeAmount = $BestellObject->versandart_preis + $BestellObject->spedition_preis;
    if($BestellObject->gesamtsumme_alternativ) {
        $orderObject->taxAmount = $BestellObject->gesamtsumme_alternativ - $BestellObject->gesamtsumme_netto;
        $orderObject->amountsAreGross = false;
    } else {
        $orderObject->taxAmount = $BestellObject->gesamtsumme_brutto - $BestellObject->gesamtsumme_netto;
        $orderObject->amountsAreGross = true;
    }
    return $orderObject;
}

function GetPHPSessionIDFromZahlungsschnittstelleBestellID($zahlungsschnittstelleClassname, $zahlungsschnittstelle_bestell_id) {
    $SQLString = 'SELECT phpsessid FROM ' . TABLE_BESTELLEN . ' INNER JOIN ' . TABLE_ZAHLUNGSSCHNITTSTELLEN . ' ON ' . TABLE_BESTELLEN . '.zahlungsschnittstelle_id = ' . TABLE_ZAHLUNGSSCHNITTSTELLEN . '.id WHERE ' . TABLE_ZAHLUNGSSCHNITTSTELLEN . '.classname = \'' . $zahlungsschnittstelleClassname . '\' AND ' . TABLE_BESTELLEN . '.zahlungsschnittstelle_bestell_id = \'' . $zahlungsschnittstelle_bestell_id . '\'';
    $row = mysql_fetch_row(errorlogged_mysql_query($SQLString));
    return $row[0];
}
?>