<?php
// preDb_0dcc87940d3655fa574b253df04ca1c3
// %g7!@fG
function createPzFromInvoice($record, $stockId) {
    global $app_list_strings;
    $db = $GLOBALS['db'];

    if ($stockId == null) {
        die('Nie wskazano magazynu');
    } else {
        $stock = $db->fetchByAssoc($db->query("SELECT id, name FROM ecmstocks WHERE id = '".$stockId."'"));
        if ($stock == null) {
            die("Wskazano błedny magazyn");
        }
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET' );
    curl_setopt($curl, CURLOPT_VERBOSE, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_URL, "https://crm.e5.pl/REST/index.php?key=7e50a8a5-f01f-4fbc-8c1b-59f3fc474bb5&action=getInvoice&record=".$record);
    $res = curl_exec($curl);
    $inv = json_decode($res);
    $inv->position_list = json_decode($inv->position_list);
    echo 'Tworzę dokument PZ w Twinpol<br>';
    echo 'Numer faktury: '.$inv->document_no.'<br>';
    echo 'Na magazyn: '.$stock['name'].' (ID: '.$stock['id'].')<br><br>';

    //check if PZ not exists
    $exists = $db->fetchByAssoc($db->query("SELECT id, document_no FROM ecmstockdocins WHERE name='".$inv->document_no."'"));
    if ($exists) {
        echo "Istnieje już dokument PZ przypisany do tej faktury: <a target='new' href='https://crm.twinpol.com/index.php?module=EcmStockDocIns&action=DetailView&record=".$exists['id']."'>".$exists['document_no']."</a>";
        die();
    }

    // Create PZ
    $pz = new EcmStockDocIn();
    $pz->parent_id = 'f084e64a-4e63-a3d1-6417-58cbf730df3f';
    $pz->parent_name = 'E5 Polska Sp. z o.o.';
    $pz->parent_address_street = 'ul. Wąwozowa 11';
    $pz->parent_address_postalcode = '02-796';
    $pz->parent_address_city = 'Warszawa';
    $pz->parent_address_country = 'Polska';
    $pz->parent_nip = '525-21-73-990';
    $pz->name = $inv->document_no;
    $pz->date_entered = date('Y-m-d H:i:s');
    $pz->date_modified = date('Y-m-d H:i:s');
    $pz->modified_user_id = '86e2871a-9d00-f756-6bba-59cce0c5db59'; // magazyn@e5.pl
    $pz->assigned_user_id = '86e2871a-9d00-f756-6bba-59cce0c5db59';
    $pz->created_by = '86e2871a-9d00-f756-6bba-59cce0c5db59';
    $pz->deleted = '0';
    $pz->register_date = date('Y-m-d');
    $pz->stock_id = $stock['id'];
    $pz->total = format_number($inv->total_netto);
    $pz->date_fk = $inv->register_date;
    $pz->status = 'accepted';
    $pz->kind = 'other';
    $pz->total_netto = format_number($inv->total_netto);
    $pz->total_brutto = format_number($inv->total_brutto);
    $pz->canceled = '0';
    $pz->country_transport_val = 0;
    $pz->foreign_transport_val = 0;
    $pz->foreign_transport_cur_id = 'PLN';
    $pz->country_transport_cur_id = 'PLN';
    $pz->addition_cost_val = 0;
    $pz->addition_cost_cur_id = 'PLN';
    $pz->currency_id = 'PLN';
    $pz->currency_value = 0;
    $pz->currency_sad_value = 0;
    $pz->vats_summary = $inv->vats_summary;
    $pz->position_list = array();
    $pz->fromREST = true;

    $gotAllProducts = true; // hope :) 
    foreach ( $inv->position_list as $product ) {
        echo 'Produkt: '.$product->product_code.'<br>';
        $p = getProduct($product->product_code);
        if (!$p) {
            echo '&nbsp;&nbsp;Produkt nie istnieje w bazie TWINPOL<br>';
            $gotAllProducts = false;
            continue;
        } 
        // add to pz
        $prod = array();
        $prod['date_entered'] = date('Y-m-d H:i:s');
        $prod['date_modified'] = date('Y-m-d H:i:s');
        $prod['modified_user_id'] = '86e2871a-9d00-f756-6bba-59cce0c5db59';
        $prod['assigned_user_id'] = '86e2871a-9d00-f756-6bba-59cce0c5db59';
        $prod['created_by'] = '86e2871a-9d00-f756-6bba-59cce0c5db59';
        $prod['deleted'] = '0';
        $prod['ecmstockdocin_id'] = $pz->id;
        $prod['product_id'] = $p->id;
        $prod['position'] = $product->position;
        $prod['product_code'] = $p->code;
        $prod['name'] = $p->name;
        $prod['quantity'] = $product->quantity;
        $prod['price'] = $product->price_netto; 
        $prod['price_fk'] = $product->price_netto; 
        $prod['total'] = $product->total_netto; 
        $prod['unit_id'] = $product->unit_id;
        $prod['unit_name'] = $product->unit_name;
        $prod['ecmproductcategory_id'] = $p->product_category_id;
        $prod['ecmvat_id'] = $p->vat_id;
        $prod['ecmvat_value'] = $p->vat_value;
        $prod['ecmvat_name'] = $p->vat_name;
        $prod['palet'] = 0;
        $prod['clo'] = 0;
        $prod['waga'] = 0;
        array_push($pz->position_list, $prod);
    }
    if (!$gotAllProducts) {
        echo 'Brak produktów w bazie Twinpol. Dokument PZ nie został utworzony';
        die();
    } else {
        $new = $pz->save(true);
        echo '<a target="new" href="https://crm.twinpol.com/index.php?module=EcmStockDocIns&action=DetailView&record='.$new.'">Utworzono PZ.</a>';
        die();
    }
}

function sendStocks()
{
    $db = $GLOBALS['db'];
    $stocks = array();
    $stocksRes = $db->query("SELECT id, name FROM ecmstocks WHERE deleted='0'");
    while ($row = $db->fetchByAssoc($stocksRes)) {
        $tmp = array();
        $tmp['id'] = $row['id'];
        $tmp['name'] = $row['name'];
        $stocks[] = $tmp;
    }
    echo json_encode($stocks);
}
function sendSale($record) {
    require_once('modules/EcmSales/EcmSale.php');
    $sale = new EcmSale();
    $sale->retrieve($record);
    $pl = $sale->getPositionList();
    $response = array (
        'document_no' => $sale->document_no,
        'name' => $sale->name,
        'parent_document_no' => $sale->parent_document_no,
        'register_date' => $sale->register_date,
        'send_date' => $sale->send_date,
        'delivery_date' => $sale->delivery_date,
        'currency_id' => $sale->currency_id,
        'total_netto' => $sale->total_netto,
        'total_brutto' => $sale->total_brutto,
        'discount' => $sale->discount,
        'parent_name' => $sale->parent_name,
        'parent_nip' => $sale->parent_nip,
        'parent_iln' => $sale->parent_iln,
        'parent_address_street' => $sale->parent_address_street,
        'parent_address_city' => $sale->parent_address_city,
        'parent_address_postalcode' => $sale->parent_address_postalcode,
        'parent_address_country' => $sale->parent_address_country,
        'shipping_address_name' => $sale->shipping_address_name,
        'shipping_address_street' => $sale->shipping_address_street,
        'shipping_address_postalcode' => $sale->shipping_address_postalcode,
        'shipping_address_city' => $sale->shipping_address_city,
        'shipping_address_country' => $sale->shipping_address_country,
        'vats_summary' => $sale->vats_summary,
        'position_list' => $pl,
        'id' => $sale->id
    );
    echo json_encode($response);
}

function updateSaleE5Number($record, $e5_record, $e5_document_no) {
    $db = $GLOBALS['db'];
    $db->query("UPDATE ecmsales SET edi_zs_id='$e5_record', edi_zs_document_no='$e5_document_no' WHERE id='$record'");
    die();
}

// local helpers
function getProduct($code) {
    $db = $GLOBALS['db'];
    $res = $db->fetchByAssoc($db->query("SELECT * FROM ecmproducts WHERE code='$code' AND deleted=0"));
    if (!$res) {
        return null;
    } else {
        require_once('modules/EcmProducts/EcmProduct.php');
        $prod = new EcmProduct();
        $prod->retrieve($res['id']);
        return $prod;
    }
}
function createProduct($record) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET' );
    curl_setopt($curl, CURLOPT_VERBOSE, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_URL, "https://crm.e5.pl/REST/index.php?key=7e50a8a5-f01f-4fbc-8c1b-59f3fc474bb5&action=getProduct&record=".$record);
    $res = curl_exec($curl);
    $prod = json_decode($res);
    require_once('modules/EcmProducts/EcmProduct.php');
    $new = new EcmProduct();
    $new->name = $prod->name;
    $new->code = $prod->code;
    $new->ean = $prod->ean;
    $new->unit_id = $prod->unit_id;
    $new->product_category_id = $prod->product_category_id;
    $new->product_category_name = $prod->product_category_name;
    $new->position_list3 = [];
    $db = $GLOBALS['db'];
    $vat = $db->fetchByAssoc($db->query("SELECT * FROM ecmvats WHERE value=$prod->vat"));
    $new->vat_id = $vat['id'];
    $new->vat_name = $vat['name'];
    $new->vat_value = $vat['value'];
    $new->assigned_user_id = '1';
    $new->modified_user_id = '1';
    $new->created_by = '1';
    $new->date_entered = date('Y-m-d H:i:s');
	$new->date_modified = date('Y-m-d H:i:s');
    $new->assigned_user_name = 'Admin System';
    $new->modified_user_name = 'Admin System';
    //$new->save();
    return $new;
}
function brecho($msg) {
    echo '<br><br>';
    var_dump($msg);
    echo '<br><br>';
}

// mysql create table with fields id varchar, created_at datetime, and payload max text
// create table e5_logs (id varchar(255), created_at datetime, payload text);
