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

/*
DELETE FROM ecommerce_invoices_products WHERE invoice_id IN (
	SELECT id FROM ecommerce_invoices WHERE origin='amazon vat local' AND register_date LIKE '2025-02-%');
DELETE FROM ecommerce_invoices WHERE origin='amazon vat local' AND register_date LIKE '2025-02-%';
*/

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

$localVat = [];
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
    if ($data[1] == 'VAT - Lokalny' && $data[8] == 'PL' && $data[9] == 'PL') {
        $localVat[] = $data;
        if ($data[20] != 'PLN') {
            echo '~PLN';
        }
    }
}
fclose($handle);

$groupedLocalVat = [];
foreach ($localVat as $vat) {
    if ($vat[6] == 'Sprzedaz - Transport') {
        $vat[10] = '00195';
        $vat[11] = '1';
    }
    $groupedLocalVat[$vat[21]][] = $vat;
}

foreach ($groupedLocalVat as $invoiceNo => $invoice) {
    if (checkInvoice($invoiceNo)) {
        echo 'Invoice already exists' . PHP_EOL;
        continue;
    }

    $totalNetto = 0;
    $totalVat = 0;
    $totalBrutto = 0;
    foreach ($invoice as $item) {
        $totalNetto += str_replace(',', '.', $item[17]);
        $totalVat += str_replace(',', '.', $item[18]);
        $totalBrutto += str_replace(',', '.', $item[19]);
    }

    $db = $GLOBALS['db'];
    $db->query("SET NAMES utf8mb4");
    $i = $invoice[0];
    $type = '';
    foreach ($invoice as $item) {
        if ($item[6] == 'Sprzedaz - Produkt') {
            $type = 'normal';
            break;
        } else if ($item[6] == 'Zwrot - Produkt') {
            $type = 'correcting';
            break;
        }
    }
    $invoiceId = getId();
    $query = sprintf("INSERT INTO ecommerce_invoices VALUES ('%s', '%s', '%s', '%s', '%s', 'amazon vat local', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%f', '%f', '%f', null, null, null, null, null);",
        $invoiceId, $i[21], $type, formatDate($i[5]), formatDate($i[5]),
        null, 'AmazonCustomer', $i[22], null, null, '',
        '', null, 'PLN', $totalNetto, $totalBrutto, $totalVat);
    $res = $db->query($query);
    if (!$res) {
        echo "Query error: ".$query.PHP_EOL;
    }

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

        if (checkProduct($p[10])) {
        echo 'Cannot find product: '. $p[10] . PHP_EOL;
            continue;
        }

        $productId = $db->fetchByAssoc($db->query(sprintf("SELECT id FROM ecmproducts WHERE code='%s' OR amazon_code='%s' AND deleted=0", $p[10], $p[10])))['id'];
        $quantity =  str_replace(',', '.', $p[11]);
        $vatValue =  str_replace(',', '.', $p[12]) * 100;
        $netto = str_replace(',', '.', $p[17]) / $quantity;
        $vat = str_replace(',', '.', $p[18]) / $quantity;
        $brutto = str_replace(',', '.', $p[19]) / $quantity;

        $query = sprintf("INSERT INTO ecommerce_invoices_products VALUES('%s', '%s', '%s', null, '%f', '%f', '%f', '%f', '%f', '%s')",
        getId(), $productId, $invoiceId, $quantity, $netto, $brutto, $vat, $vatValue, $p[10]);
        $res = $db->query($query);
        if (!$res) {
            echo "Query error: ".$query.PHP_EOL;
        }
    }
}

echo 'Koniec. Smutne.';

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 ? false : true;
}
function checkInvoice($number) {
    $db = $GLOBALS['db'];
    $res = $db->query(sprintf("SELECT id FROM ecommerce_invoices WHERE document_no = '%s'", $number));
    return $res->num_rows > 0;
}
function formatDate($date) {
    $dateTime = DateTime::createFromFormat('d-m-Y', $date);
    return $dateTime ? $dateTime->format('Y-m-d') : false;
}
function getId() {
    $db = $GLOBALS['db'];
    $res = $db->fetchByAssoc($db->query("SELECT UUID() as id;"));
    return $res['id'];
}