<?php
require_once('modules/EcmSales/EcmSale.php');
$path = "/var/edi/e5/orders";
$folders = array('imported', 'temp', 'failed');
$allFiles = scandir($path);


if (is_array($allFiles)) {
    foreach ($allFiles as $file) {
        if (!is_dir($file) && !in_array($file, $folders) && substr($file, -3) == 'xml') {
            try {
                importSale($path . '/' . $file);
                rename($path . '/' . $file, $path . '/imported/' . $file);
                echo 'Import finished: ' . $file . PHP_EOL;
            } catch (Exception $e) {
                echo 'Import error ' . $e->getMessage(), PHP_EOL;
            }
        }
    }
    return;
}


function importSale($file)
{
    $db = $GLOBALS['db'];
    $xml = simplexml_load_file($file);

    if (!$xml) {
        throw new Exception("Can't load (or parse) XML");
    }

    $sale = new EcmSale();

    // AUCHAN
    $buyerILN = $xml->{'Order-Parties'}->Buyer->ILN;
    if ($xml->{'Order-Parties'}->BuyerHeadquaters->ILN == '5900014000001') {
        $buyerILN = $xml->{'Order-Parties'}->BuyerHeadquaters->ILN;
    } 

    $buyer = $db->fetchByAssoc($db->query("
        SELECT to_vatid, register_address_street, register_address_city, register_address_postalcode,
            register_address_country, id, assigned_user_id, name,parent_id, 
            supplier_code, ecmpaymentcondition_id, ecmpaymentcondition_name, payment_date_days,
            assigned_user_id, parent_id, payment_date_days, supplier_code
        FROM accounts where iln like '" . $buyerILN . "' AND deleted=0"));

    $isCarrefour = false;
    if ($xml->{'Order-Parties'}->BuyerHeadquaters->ILN == '5900000930015') {
        $isCarrefour = true;
    }
    $isMM = false;
    if ($buyer['parent_id'] == '1249') {
        $isMM = true;
    }

    $sale->parent_id = $buyer['id'];
    $sale->parent_name = $buyer['name'];
    $sale->parent_iln = $xml->{'Order-Parties'}->Buyer->ILN;
    $sale->parent_nip = $buyer['to_vatid'];
    $sale->parent_address_street = $buyer['register_address_street'];
    $sale->parent_address_city = $buyer['register_address_city'];
    $sale->parent_address_postalcode = $buyer['register_address_postalcode'];
    $sale->parent_address_country = $buyer['register_address_country'];
    $sale->parent_document_no = $xml->{'Order-Header'}->OrderNumber;

    if ($isMM) {
        $address = $db->fetchByAssoc(
            $db->query(
                "SELECT * FROM account_addresses WHERE account_id='$sale->parent_id' AND deleted='0' ORDER BY position LIMIT 1"
            )
        );
        $sale->shipping_address_name = $address['name'];
        $sale->shipping_addresses = $address['name'];
        $sale->shipping_address_street = $address['street'];
        $sale->shipping_address_city = $address['city'];
        $sale->shipping_address_postalcode = $address['postalcode'];
        $sale->shipping_address_country = $address['country'];
        $sale->shipping_iln = $xml->{'Order-Parties'}->DeliveryPoint->ILN;
        $sale->shipping_nip = "";
        if ($buyer['payment_date_days'])
            $sale->payment_date_days = $buyer['payment_date_days'];
        if ($buyer['supplier_code'])
            $sale->supplier_code = $buyer['supplier_code'];
    } else {

        $delivery = $db->fetchByAssoc($db->query("
    SELECT to_vatid, register_address_street, register_address_city, register_address_postalcode,
        register_address_country, id, assigned_user_id, name,parent_id, 
        supplier_code, ecmpaymentcondition_id, ecmpaymentcondition_name, payment_date_days 
    FROM accounts where iln like '" . $xml->{'Order-Parties'}->DeliveryPoint->ILN . "' AND deleted=0"));

        $sale->shipping_address_name = $delivery['name'];
        $sale->shipping_addresses = $delivery['name'];
        $sale->shipping_address_street = $delivery['register_address_street'];
        $sale->shipping_address_city = $delivery['register_address_city'];
        $sale->shipping_address_postalcode = $delivery['register_address_postalcode'];
        $sale->shipping_address_country = $delivery['register_address_country'];
        $sale->shipping_iln = $xml->{'Order-Parties'}->DeliveryPoint->ILN;
        $sale->shipping_nip = $delivery['to_vatid'];
        if ($delivery['payment_date_days'])
            $sale->payment_date_days = $delivery['payment_date_days'];
        if ($delivery['supplier_code'])
            $sale->supplier_code = $delivery['supplier_code'];
    }

    $sale->register_date = date("d.m.Y", strtotime($xml->{'Order-Header'}->OrderDate));
    $sale->delivery_date = date("d.m.Y", strtotime($xml->{'Order-Header'}->ExpectedDeliveryDate));
    $date = new DateTime(date("d.m.Y", strtotime($xml->{'Order-Header'}->OrderDate)));
    if ($sale->payment_date_days != "") {
        $date->modify("+" . $sale->payment_date_days . " day");
    }
    $sale->payment_date = $date->format("d.m.Y");
    $sale->assigned_user_id = $buyer['assigned_user_id'];
    $sale->edi_file = $file;
    $sale->type = 'sales_order';
    $sale->status = 's60';
    $sale->ecmlanguage = 'pl_pl';

    $sale->position_list = loadProducts($xml->{'Order-Lines'}->Line, $isCarrefour);
    $sum_netto = 0;
    $sum_brutto = 0;
    foreach ($sale->position_list as $p) {
        $sum_netto += $p['total_netto'];
        $sum_brutto += $p['total_brutto'];
    }
    $sale->total_netto = $sum_netto;
    $sale->total_brutto = $sum_brutto;

    //$sale->save(false);
}

function loadProducts($products, $isCarrefour = false)
{
    $db = $GLOBALS['db'];
    $counter = 0;
    foreach ($products as $prod) {
        if ($isCarrefour) {
            $pId = $db->fetchByAssoc($db->query("select p.id from ecmproducts as p where TRIM(p.ean2)='" . trim($prod->{'Line-Item'}->EAN) . "' and p.deleted='0'"));
        } else {
            $pId = $db->fetchByAssoc($db->query("select p.id from ecmproducts as p where (TRIM(p.ean)='" . trim($prod->{'Line-Item'}->EAN) . "' OR TRIM(p.ean2)='" . trim($prod->{'Line-Item'}->EAN) . "') and p.deleted='0'"));
        }
        $p = new EcmProduct();
        $p->retrieve($pId['id']);
        $response[$counter]['product_id'] = $p->id;
        $response[$counter]['position'] = (string) $prod->{'Line-Item'}->LineNumber;
        $response[$counter]['product_code'] = $p->code;
        $response[$counter]['name'] = $p->name;
        $response[$counter]['quantity'] = (string) $prod->{'Line-Item'}->OrderedQuantity;
        $response[$counter]['price_start'] = (string) $prod->{'Line-Item'}->OrderedUnitNetPrice;
        $response[$counter]['price_netto'] = (string) $prod->{'Line-Item'}->OrderedUnitNetPrice;
        $response[$counter]['discount'] = 0;
        $response[$counter]['total_netto'] = (string) $prod->{'Line-Item'}->OrderedUnitNetPrice * $prod->{'Line-Item'}->OrderedQuantity;
        $response[$counter]['unit_id'] = 1;
        $response[$counter]['unit_name'] = 'szt.';
        $response[$counter]['ecmvat_id'] = $p->vat_id;
        $response[$counter]['ecmvat_name'] = $p->vat_name;
        $response[$counter]['ecmvat_value'] = $p->vat_value;
        $response[$counter]['recipient_code'] = (string) $prod->{'Line-Item'}->BuyerItemCode;
        $response[$counter]['product_ean'] = (string) trim($prod->{'Line-Item'}->EAN);
        $counter++;
    }
    return $response;
}

function brecho($msg)
{
    echo '<br><br>';
    var_dump($msg);
    echo '<br><br>';
}
