<?php
brecho("Import Amazon");
$filePath = "modules/EcmInvoiceOuts/BimIT-eCommerceInvoices/amazonXML/9_2024.csv";

if (!file_exists($filePath)) {
    echo "Error: File not found";
    exit();
}
$file = fopen($filePath, 'r');
if (!$file) {
    echo "Error: Unable to open file";
    exit();
}

$invoices = array();

$lineNumber = -1;
while (($d = fgetcsv($file)) !== false) {
    $lineNumber++;
    if ($lineNumber == 0) {
        continue;
    }

    $documentNo = $d[51];

    $isReturn = false;
    if ($d[3] == 'RETURN') {
        $isReturn = true;
        //brecho("Korekta!");
        //brecho($d);
        continue;
    } else if ($d[4] != 'FALSE' || $d[3] != 'SHIPMENT' || $documentNo == 'N/A') {
        continue;
    }

    if (!isset($invoices[$documentNo])) {
        $invoices[$documentNo] = array();
    }
    $invoices[$documentNo]['items'][] = $d;
    $invoices[$documentNo]['document_no'] = $documentNo;
    $invoices[$documentNo]['id'] = $d[8];
    $invoices[$documentNo]['order_no'] = $d[5];
    $invoices[$documentNo]['register_date'] = new DateTime($d[6]);
    $invoices[$documentNo]['sell_date'] = new DateTime($d[2]);
    $invoices[$documentNo]['parent_nip'] = $d[43];
    $invoices[$documentNo]['total_brutto'] = array_sum(array_column($invoices[$documentNo]['items'], 23));
    $invoices[$documentNo]['total_netto'] = array_sum(array_column($invoices[$documentNo]['items'], 25));
    $invoices[$documentNo]['total_vat'] = array_sum(array_column($invoices[$documentNo]['items'], 24));
    $invoices[$documentNo]['currency'] = $d[15];
    $invoices[$documentNo]['parent_address_city'] = str_replace("'", "",$d[59]);
    $invoices[$documentNo]['parent_address_postalcode'] = str_replace("'", "",$d[62]);
    $invoices[$documentNo]['parent_address_country'] = str_replace("'", "",$d[61]);
    $invoices[$documentNo]['url'] = $d[52];
}
fclose($file);

brecho("Ilość faktur: ".count($invoices));

foreach ($invoices as $documentNo => $invoice) {
    $add = true;
    foreach ($invoice['items'] as $item) {
        if (!checkProduct($item[10])) {
            brecho("Brak produktu: " . $item[10]);
            $add = false;
        }
    }
    if ($add && !checkInvoice($invoice['id'])) {
        addInvoice($invoice);
    }
}


brecho("Koniec. Smutne.");

function addInvoice($i) {
    brecho($i['document_no']);
    $db = $GLOBALS['db'];
    $db->query("SET NAMES utf8mb4");
    $query = sprintf("INSERT INTO ecommerce_invoices VALUES ('%d', '%s', '%s', '%s', '%s', 'amazon', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%f', '%f', '%f', '%s');",
        $i['id'], $i['document_no'], 'normal', $i['register_date']->format("Y-m-d"), $i['sell_date']->format("Y-m-d"),
        $i['order_no'], 'AmazonCustomer', $i['parent_nip'], $i['parent_address_city'], $i['parent_address_postalcode'], '',
        '', $i['parent_address_country'], $i['currency'], $i['total_netto'], $i['total_brutto'], $i['total_vat'], $i['url']);
    $db->query($query);
    brecho($query);
    foreach ($i['items'] as $p) {
        addProduct($i['id'], $p);
    }
}

function addProduct($invoiceId, $p) {
    $db = $GLOBALS['db'];
    $id = $db->fetchByAssoc($db->query(sprintf("SELECT id FROM ecmproducts WHERE code ='%s' OR amazon_code = '%s'", $p[10], $p[10])))['id'];

    $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
    $query = sprintf("INSERT INTO ecommerce_invoices_products VALUES('%s', '%s', '%s', '%d', '%f', '%f', '%f', '%f', '%s')",
        $uuid, $id, $invoiceId, $p[11], $p[25], $p[23], $p[24], $p[13]*100, $p[10]);
    $db->query($query);
}
function checkProduct($code)
{
    $db = $GLOBALS['db'];
    $res = $db->query(sprintf("SELECT id FROM ecmproducts WHERE code='%s' OR amazon_code='%s' AND deleted=0", $code, $code));
    return $res->num_rows > 0;
}
function checkInvoice($id) {
    $db = $GLOBALS['db'];
    $res = $db->query(sprintf("SELECT id FROM ecommerce_invoices WHERE id = '%s'", $id));
    return $res->num_rows > 0;
}
function brecho($msg)
{
    echo "<br><br>";
    var_dump($msg);
    echo "<br><br>";
}