<?php
$IMPORT_START_DATE = date('Y-m-dTH:i:s', strtotime("-20 days"));
$LIST_FILTER_DATE = date('Y-m-d H:i:s', strtotime("-7 days"));

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

global $sugar_config;

$allegro_config = loadConfiguration();

if (!isset($_GET['ajaxAction'])) {
    // load last event_it from allegro_orders table
    global $db;
    $dbRes = $db->query("SELECT event_id FROM allegro_orders ORDER BY date_entered DESC LIMIT 1");
    $lastEventId = $db->fetchByAssoc($dbRes)['event_id'];
    $events = loadOrderEvents($allegro_config['token'], $lastEventId);
    if (isset($events->error)) {
        if (refreshToken($allegro_config['refreshToken'], $allegro_config['basicAuth']) == true) {
            $allegro_config = loadConfiguration();
            $events = loadOrderEvents($allegro_config['token'], $lastEventId);
        } else {
            die('Nie udało się odświeżyć tokena');
        }
    }
    $orders = array();
    usort($events->events, function ($a, $b) {
        return strtotime($b->occurredAt) - strtotime($a->occurredAt);
    });
    if (count($events->events) > 0) {
        global $db;
        foreach ($events->events as $event) {
            if (date('Y-m-dTH:i:s', strtotime($event->occurredAt)) > $IMPORT_START_DATE) {
                $order = loadOrder($event->order->checkoutForm->id, $allegro_config['token']);
                $parsedOrder = json_decode($order);
                $date = date("Y-m-d H:i:s", strtotime($parsedOrder->updatedAt));
                $db->query("INSERT INTO allegro_orders VALUES ('".$event->order->checkoutForm->id."', '".$event->id."', '".$date."', '".base64_encode($order)."')");
            }
        }
        header('Location: index.php?module=EcmSales&action=bimit_importAllegroOrders');
    } else {
        $dbRes = $db->query("SELECT * FROM allegro_orders WHERE date_entered > '$LIST_FILTER_DATE' ORDER BY date_entered DESC");
        $orders = array();
        while ($row = $db->fetchByAssoc($dbRes)) {
            $order = json_decode(base64_decode(($row['payload'])));
            $order->buyer->exists = isAccountExists($order->buyer->email);
            $order->exists = isOrderExists($order->id);
            if ($order->exists) {
                $e5Order = getOrder($order->id);
                $order->e5Id = $e5Order['id'];
                $order->e5Number = $e5Order['document_no'];
                $inv = getInvoice($e5Order['id']);
                $order->e5InvoiceId = $inv['id'];
                $order->e5InvoiceNumber = $inv['document_no'];
            }
            if ($order->buyer->exists) {
                $client = getClient($order->buyer->email);
                $order->buyer->e5Id = $client['id'];
                $order->buyer->e5Name = $client['name'];
            }
            $orders[] = $order;
        }
        $smarty = new Sugar_Smarty();
        $smarty->assign('orders', $orders);
        $smarty->display(getcwd() . '/modules/EcmSales/tpls/bimit_importAllegroOrders.tpl');
        return;
    }
} else {
    if ($_GET['ajaxAction'] == 'createOrder') {
        $order = loadOrder($_GET['orderId'], $allegro_config['token']);
        brecho($order);
        $respone = addOrder(json_decode($order));
        brecho($respone);
        return;
    }
    if ($_GET['ajaxAction'] == 'sendInvoice') {
        die('createInvoice');
    }
}
function addOrder($order)
{
    $sale = new EcmSale();
    $clientId = null;
    if (!isAccountExists($order->buyer->email)) {
        $clientId = createAccount($order);
    } else {
        $clientId = getClient($order->buyer->email)['id'];
    }
    $client = new Account();
    $client->retrieve($clientId);
    $sale->parent_id = $client->id;
    $sale->parent_name = $client->name;
    $sale->parent_name_copy = $client->name;
    $sale->parent_nip = $client->to_vatid;
    $sale->parent_address_street = $client->register_address_street;
    $sale->parent_address_city = $client->register_address_city;
    $sale->parent_address_postalcode = $client->register_address_postalcode;
    $sale->parent_address_country = $client->register_address_country;

    $sale->type = 'sales_order';
    if (
        $order->payment->paidAmount->amount != $order->summary->totalToPay->amount
        && $order->payment->type == 'ONLINE'
    ) {
        $sale->status = 's20';
    } else {
        $sale->status = 's30';
    }
    $sale->ecmlanguage = 'pl_pl';
    $sale->currency_id = 'PLN';
    $sale->pdf_type = 'K';

    $sale->order_source = 'allegro';
    $sale->order_source_id = $order->id;

    global $current_user;
    $sale->assigned_user_id = $current_user->id;

    $sale->register_date = date("d.m.Y", strtotime($order->updatedAt));
    $sale->delivery_date = date("d.m.Y", strtotime($order->delivery->time->to));
    $sale->send_date = date("d.m.Y", strtotime($order->delivery->time->dispatch->from));

    if ($order->payment->type == 'ONLINE') {
        $sale->payment_method = 'PRZEDPLATA';
        $sale->payment_date = date("d.m.Y", strtotime($order->payment->finishedAt));
    } else {
        $sale->payment_method = 'ZA POBRANIEM';
    }

    if (isset($order->delivery->pickupPoint)) {
        $sale->shipping_address_name = $order->delivery->pickupPoint->name . ' (' . $order->delivery->pickupPoint->description . ')';
        $sale->shipping_address_street = $order->delivery->pickupPoint->address->street;
        $sale->shipping_address_city = $order->delivery->pickupPoint->address->city;
        $sale->shipping_address_postalcode = $order->delivery->pickupPoint->address->zipCode;
        $sale->shipping_address_country = $order->delivery->pickupPoint->address->countryCode;
        $sale->shipping_phone = $sale->shipping_phone = $order->delivery->address->phoneNumber;
    } else {
        if ($order->delivery->address->companyName) {
            $sale->shipping_address_name = $order->delivery->address->companyName . ' ';
        }

        $sale->shipping_address_name .= $order->delivery->address->firstName . ' ' . $order->delivery->address->lastName;
        $sale->shipping_address_street = $order->delivery->address->street;
        $sale->shipping_address_city = $order->delivery->address->city;
        $sale->shipping_address_postalcode = $order->delivery->address->zipCode;
        $sale->shipping_address_country = $order->delivery->address->countryCode;
        $sale->shipping_phone = $order->delivery->address->phoneNumber;
    }

    $sale->pdf_text =
        $order->buyer->login
        . PHP_EOL
        . $order->delivery->method->name
        . PHP_EOL
        . $order->buyer->email;

    $sale->position_list = array();
    $counter = 0;
    $sumNetto = 0;
    foreach ($order->lineItems as $line) {
        $productId = getProduct($line->offer->external->id);
        $p = new EcmProduct();
        $p->retrieve($productId);


        $sale->position_list[$counter]['product_id'] = $p->id;
        $sale->position_list[$counter]['position'] = $counter;
        $sale->position_list[$counter]['product_code'] = $p->code;
        $sale->position_list[$counter]['name'] = $p->name;
        $sale->position_list[$counter]['discount'] = 0;
        $sale->position_list[$counter]['unit_id'] = 1;
        $sale->position_list[$counter]['unit_name'] = 'szt.';
        $sale->position_list[$counter]['ecmvat_id'] = $p->vat_id;
        $sale->position_list[$counter]['ecmvat_name'] = $p->vat_name;
        $sale->position_list[$counter]['ecmvat_value'] = $p->vat_value;
        $sale->position_list[$counter]['product_ean'] = $p->ean;

        $sale->position_list[$counter]['quantity'] = $line->quantity;
        $priceBrutto = $line->price->amount;
        $priceNetto = round($priceBrutto / (1 + ($p->vat_value / 100)), 2);

        $sale->position_list[$counter]['price_start'] = $priceNetto;
        $sale->position_list[$counter]['price_netto'] = $priceNetto;
        $sale->position_list[$counter]['total_netto'] = $priceNetto * $line->quantity;

        $sumNetto += $sale->position_list[$counter]['total_netto'];

        $counter++;
    }
    // delivery
    if (floatval($order->delivery->cost->amount) > 0) {
        $p = new EcmProduct();
        $p->retrieve('165f364e-9301-25ac-5906-58e38f1de4ca');

        $sale->position_list[$counter]['product_id'] = $p->id;
        $sale->position_list[$counter]['position'] = $counter;
        $sale->position_list[$counter]['product_code'] = $p->code;
        $sale->position_list[$counter]['name'] = $p->name;
        $sale->position_list[$counter]['discount'] = 0;
        $sale->position_list[$counter]['unit_id'] = 1;
        $sale->position_list[$counter]['unit_name'] = 'szt.';
        $sale->position_list[$counter]['ecmvat_id'] = $p->vat_id;
        $sale->position_list[$counter]['ecmvat_name'] = $p->vat_name;
        $sale->position_list[$counter]['ecmvat_value'] = $p->vat_value;
        $sale->position_list[$counter]['product_ean'] = $p->ean;

        $sale->position_list[$counter]['quantity'] = 1;
        $priceBrutto = $order->delivery->cost->amount;
        $priceNetto = round($priceBrutto / (1 + ($p->vat_value / 100)), 2);

        $sale->position_list[$counter]['price_start'] = $priceNetto;
        $sale->position_list[$counter]['price_netto'] = $priceNetto;
        $sale->position_list[$counter]['total_netto'] = $priceNetto;

        $sumNetto += $sale->position_list[$counter]['total_netto'];
    }
    $sale->total_netto = $sumNetto;
    $sale->save();
}
function createAccount($order)
{
    require_once(getcwd() . "/include/SugarEmailAddress/SugarEmailAddress.php");
    global $current_user;
    $account = new Account();
    $name = '';
    if ($order->invoice->required) {
        if ($order->invoice->address->company) {
            $name = $order->invoice->address->company->name;
        } else {
            $name = $order->invoice->address->naturalPerson->firstName . ' ' . $order->invoice->address->naturalPerson->lastName;
        }
        $account->to_vatid = $order->invoice->address->company->taxId;
    } else if ($order->buyer->firstName || $order->buyer->lastName) {
        $name = $order->buyer->firstName . ' ' . $order->buyer->lastName;
    } else {
        $name = $order->buyer->email;
    }

    $account->name = $name;
    $account->index_dbf = $name;
    $account->description = $order->buyer->login;
    $account->phone_office = $order->buyer->phoneNumber;
    $account->assigned_user_id = $current_user->id;
    $account->isAllegroUser = true;
    $account->account_type = 'rec';

    if ($order->invoice->required) {
        $account->shop_user = 'b2b';
        $account->register_address_street = $order->invoice->address->street;
        $account->register_address_city = $order->invoice->address->city;
        $account->register_address_postalcode = $order->invoice->address->postCode;
        $account->register_address_country = $order->invoice->address->countryCode;

        $account->billing_address_street = $order->buyer->address->street;
        $account->billing_address_city = $order->buyer->address->city;
        $account->billing_address_postalcode = $order->buyer->address->postCode;
        $account->billing_address_country = $order->buyer->address->countryCode;
    } else {
        $account->shop_user = 'b2c';
        $account->register_address_street = $order->buyer->address->street;
        $account->register_address_city = $order->buyer->address->city;
        $account->register_address_postalcode = $order->buyer->address->postCode;
        $account->register_address_country = $order->buyer->address->countryCode;
    }
    $account->save();
    $email = new SugarEmailAddress();
    $email->addAddress($order->buyer->email, true);
    $email->save($account->id, "Accounts");
    return $account->id;
}
function isOrderExists($allegroOrderId)
{
    global $db;
    $dbRes = $db->query("SELECT id FROM ecmsales WHERE deleted = 0 AND order_source = 'allegro' AND order_source_id = '" . $allegroOrderId . "'");
    if ($db->getRowCount($dbRes) > 0) {
        return true;
    } else {
        return false;
    }
}
function getOrder($allegroOrderId)
{
    global $db;
    $dbRes = $db->query("SELECT id, document_no FROM ecmsales WHERE deleted = 0 AND order_source = 'allegro' AND order_source_id = '" . $allegroOrderId . "'");
    return $db->fetchByAssoc($dbRes);
}
function getInvoice($orderId)
{
    global $db;
    $dbRes = $db->query("SELECT id, document_no FROM ecminvoiceouts WHERE deleted = 0 AND canceled = 0 AND so_id = '" . $orderId . "'");
    return $db->fetchByAssoc($dbRes);
}
function getProduct($code)
{
    global $db;
    $dbRes = $db->query("SELECT id FROM ecmproducts WHERE deleted = 0 AND code = '" . $code . "'");
    return $db->fetchByAssoc($dbRes)['id'];
}
function isAccountExists($email)
{
    global $db;
    $dbRes = $db->query("
        SELECT a.id FROM email_addr_bean_rel AS rel
        INNER JOIN email_addresses AS e ON e.id = rel.email_address_id
        INNER JOIN accounts AS a ON a.id = rel.bean_id
        WHERE e.email_address = '" . $email . "' AND a.deleted = 0;
    ");
    if ($db->getRowCount($dbRes) > 0) {
        return true;
    } else {
        return false;
    }
}
function getClient($email)
{
    global $db;
    $dbRes = $db->query("
        SELECT a.id, a.name FROM email_addr_bean_rel AS rel
        INNER JOIN email_addresses AS e ON e.id = rel.email_address_id
        INNER JOIN accounts AS a ON a.id = rel.bean_id
        WHERE e.email_address = '" . $email . "' AND a.deleted = 0;
    ");
    return $db->fetchByAssoc($dbRes);
}
function loadOrder($orderId, $token)
{
    $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_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json',
    ]);
    curl_setopt($curl, CURLOPT_URL, "https://api.allegro.pl/order/checkout-forms/" . $orderId);
    return curl_exec($curl);
}
function loadOrderEvents($token, $lastEventId)
{
    $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_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json',
    ]);
    curl_setopt($curl, CURLOPT_URL, "https://api.allegro.pl/order/events?type=READY_FOR_PROCESSING&limit=500&from=".$lastEventId);
    return json_decode(curl_exec($curl));
}
function refreshToken($refreshToken, $baseCredentials)
{
    $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_HTTPHEADER, [
        'Authorization: Basic ' . $baseCredentials,
        'Accept: application/vnd.allegro.public.v1+json',
    ]);
    curl_setopt($curl, CURLOPT_URL, "https://allegro.pl/auth/oauth/token?grant_type=refresh_token&refresh_token=" . $refreshToken);
    $res =  json_decode(curl_exec($curl));
    if (isset($res->error)) {
        return false;
    } else {
        global $db;
        $db->query("UPDATE config SET value='" . $res->access_token . "' WHERE category='allegro' AND name='token'");
        $db->query("UPDATE config SET value='" . $res->refresh_token . "' WHERE category='allegro' AND name='refreshToken'");
        return true;
    }
}
function getToken()
{
}
function registerDevice()
{
}
function loadConfiguration()
{
    global $db;
    $dbRes = $db->query("SELECT * FROM config WHERE category='allegro'");
    $config = [];
    while ($row = $db->fetchByAssoc($dbRes)) {
        $config[$row['name']] = $row['value'];
    }
    $config['basicAuth'] = base64_encode($config['clientId'] . ':' . $config['clientSecret']);
    return $config;
}
function brecho()
{
    $args = func_get_args();
    echo '<pre>';
    foreach ($args as $arg) {
        var_dump($arg);
    }
    echo '</pre>';
}
function sendInvoiceToAllegro($invoiceId) {
    global $db;
    $dbRes = $db->query("SELECT * FROM ecminvoiceouts WHERE id='$invoiceId'");
    // TODO Create invoice object in allegro

    // TODO create iunvoice pdf

    // TODO send invoice to allegro
}
function createInvoice($orderId, $document_no, $token) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($curl, CURLOPT_VERBOSE, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Accept: application/vnd.allegro.public.v1+json',
    ]);
    curl_setopt($curl, CURLOPT_URL, "https://api.{environment}/order/checkout-forms/".$orderId."/invoices");
    // remove from document_no characters not allowed in filename
    $name = preg_replace('/[^A-Za-z0-9\-]/', '', $document_no);
    $body = array(
        'file' => array(
            'name' => $name.'.pdf',
        ),
        'invoiceNumber' => $document_no
    ); 
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body));
    //return curl_exec($curl);
}

function getInvoicePdf($invoiceId) {

}

function sendInvoice($orderId, $allegroInvoiceId, $data, $token) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($curl, CURLOPT_VERBOSE, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $token,
        'Accept: application/pdf',
    ]);
    curl_setopt($curl, CURLOPT_URL, "https://api.{environment}/order/checkout-forms/".$orderId."/invoices//".$allegroInvoiceId."/file");
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}



//$baseCredentials = base64_encode($sugar_config['allegro_client_id'].':'.$sugar_config['allegro_client_secret']);
/*
$deviceCode = 'nFSFN4KzFGkS8FTLp570WrznYkWTc6Ja';
$userCode = 'dvil0sfl9';

$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_HTTPHEADER, [
    'Authorization: Bearer '.$token,
    'Accept: application/vnd.allegro.public.v1+json',
]);
curl_setopt($curl, CURLOPT_URL, "https://api.allegro.pl/order/events");
$res = curl_exec($curl);
$ordersRes = json_decode($res);

echo '<pre>';
var_dump($ordersRes);
echo '</pre>';


/*
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Content-Type: application/x-www-form-urlencoded',
    'Authorization: Basic '.$baseCredentials,
]);
curl_setopt($curl, CURLOPT_URL, "https://allegro.pl/auth/oauth/device?client_id=".$sugar_config['allegro_client_id']);
$res = curl_exec($curl);
$authRes = json_decode($res);


var_dump($authRes);
*/

/*
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, [
    'Authorization: Basic '.$baseCredentials
]);
curl_setopt($curl, CURLOPT_URL, "https://allegro.pl/auth/oauth/token?grant_type=urn:ietf:params:oauth:grant-type:device_code&device_code=".$deviceCode);
$res = curl_exec($curl);

var_dump($res);

*/