<?php
// show all php errors
error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED);
ini_set('display_errors', 1);

// read csv file tab separated
$filename = getcwd() . '/modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonWDT/files/04-2025.csv';
$handle = fopen($filename, 'r');
if ($handle === false) {
    die('Cannot open file: ' . $filename);
}

$de = [];
$cz = [];
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
    if (count($data) == 1 && $data[0] == null) {
        continue;
    }
    if ($data[1] != 'Przemieszczenie - WDT') {
        continue;
    }
    if ($data[8] == 'PL' && $data[9] == 'DE') {
        $de[] = $data;
    }
    if ($data[8] == 'PL' && $data[9] == 'CZ') {
        $cz[] = $data;
    }
}
fclose($handle);

//if (count($de) == 0) {
//    die('No data for DE');
//}
//createInvoice('DE', $de);

if (count($cz) == 0) {
    die('No data for CZ');
}
createInvoice('CZ', $cz, true);

function createInvoice($type, $products, $DO_REAL_SAVE = false)
{
    $db = $GLOBALS['db'];
    $invoice = new EcmInvoiceOut();
    if ($type == 'DE') {
        $invoice->parent_id = 'a711623a-0217-41bd-ecf6-664c84553473';
        $invoice->parent_name = 'Twinpol DE';
        $invoice->parent_nip = '367123377';
    }
    if ($type == 'CZ') {
        $invoice->parent_id = 'bf60a128-0b62-4154-c21f-6797718a6354';
        $invoice->parent_name = 'Twinpol CZ';
        $invoice->parent_nip = 'CZ687253791';
    }
    $invoice->parent_address_street = 'Aleja Lipowa 48';
    $invoice->parent_address_postalcode = '87-126';
    $invoice->parent_address_city = 'Obrowo';

    $invoice->type = 'normal';
    $date = '30.04.2025';
    $invoice->register_date = $date;
    $invoice->sell_date = $date;
    $invoice->validtill_date = $date;

    $invoice->payment_date = $invoice->register_date;
    $invoice->payment_date_days = 0;
    $invoice->payment_method = '1568e47e-1732-e0ad-0000-67b6377f26df';

    $invoice->pdf_type = "K";
    $invoice->currency_id = 'PLN';
    global $current_user;
    $invoice->created_by = $current_user->id;
    $invoice->assigned_user_id = $current_user->id;

    $invoice->wz_id = '';
    $invoice->wz_name = '';

    $invoice->position_list = [];

    foreach ($products as $p) {
        // if last character is dot, remove it
        if (substr($p[10], -1) == '.') {
            $p[10] = substr($p[10], 0, -1);
        }

        $fromDb = $db->fetchByAssoc($db->query("SELECT id, name, code, product_category_id, unit_id FROM ecmproducts WHERE code = '$p[10]' OR amazon_code = '$p[10]'"));
        if ($fromDb == false) {
            var_dump($p);
            die('Product not found in DB');
        }
        $prod = searchProduct($fromDb['id'], $invoice->position_list);
        if ($prod) {
            $prod['quantity'] += intval($p[11]);
            $prod['total_netto'] += floatval(str_replace(",", ".", $p[17]));
            $prod['total_brutto'] += floatval(str_replace(",", ".", $p[17]));

            $prod['price_start'] = round($prod['total_netto'] / $prod['quantity'], 2);
            $prod['price_netto'] = $prod['price_start'];
            $prod['price_brutto'] = $prod['price_netto'];

            foreach ($invoice->position_list as $key => $value) {
                if ($value['product_id'] == $prod['product_id']) {
                    $invoice->position_list[$key] = $prod;
                }
            }
        } else {
            $prod['product_id'] = $fromDb['id'];
            $prod['name'] = $fromDb['name'];
            $prod['product_code'] = $fromDb['code'];
            $prod['quantity'] = intval($p[11]);
            $prod['total_netto'] = floatval(str_replace(",", ".", $p[17]));
            $prod['total_brutto'] = floatval(str_replace(",", ".", $p[17]));
            $prod['total_vat'] = 0;

            $prod['price_start'] = round($prod['total_netto'] / $prod['quantity'], 2);
            $prod['price_netto'] = $prod['price_start'];
            $prod['price_brutto'] = $prod['price_netto'];

            $prod['ecmvat_id'] = '9b783d21-5548-6653-e1d6-49610eb3f9dd';
            $prod['ecmvat_name'] = '0%';
            $prod['ecmvat_value'] = 0;

            $prod['ecmproductcategory_id'] = $fromDb['product_category_id'];

            $prod['dd_unit_id'] = $fromDb['unit_id'];
            global $app_list_strings;
            $prod['dd_unit_name'] = $app_list_strings['ecmproducts_unit_dom'][$fromDb['unit_id']];

            $invoice->position_list[] = $prod;
        }
    }
    if ($DO_REAL_SAVE) {
        $id = $invoice->save();
        echo $id;
    } else {
        var_dump($invoice->position_list);
    }
}

function searchProduct($productId, $products)
{
    foreach ($products as $p) {
        if ($p['product_id'] == $productId) {
            return $p;
        }
    }
    return false;
}