<?php

namespace App\Classes\Jobs;

use Carbon\Carbon;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class CurlContainerListJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */

    private $page;

    public function __construct($page = 1)
    {
        $this->page = $page;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle()
    {
        $cookies = $this->getCookie();

        $headers = [
            'Content-Type' => 'application/json',
            'Cookie' => $cookies,
        ];

        $last_two_month = Carbon::now()->subMonth(2)->format('Y-m-d');

        $client = new \GuzzleHttp\Client(['headers' => $headers]);
        $res = $client->post('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', [\GuzzleHttp\RequestOptions::JSON => json_decode('{"controller":"VCustomercontainer","view":"grid1","request":{"PageIndex":' . $this->page . ',"PageSize":10,"PageOffset":0,"SortExpression":"CreatedOn DESC","GroupExpression":"","Filter":["LoadedTime:<=%js%\"' . $last_two_month . 'T00:00:00.000\"\u0000"],"ContextKey":"view1","FilterIsExternal":false,"LookupContextFieldName":null,"LookupContextController":null,"LookupContextView":null,"LookupContext":null,"Inserting":false,"LastCommandName":null,"ExternalFilter":[],"DoesNotRequireData":false,"LastView":"grid1","Tag":null,"RequiresFirstLetters":false,"ViewType":"Grid","SupportsCaching":true,"SystemFilter":null,"RequiresRowCount":true,"QuickFindHint":null,"RequiresPivot":false,"PivotDefinitions":null,"RequiresMetaData":true}}')]);

        $data = json_decode($res->getBody()->getContents());

        if (!empty($data->d->Rows)) {
            // insert data here

            // next page
            $this->page = $this->page > 0 ? $this->page + 1 : 1;
            CurlContainerListJob::dispatch($this->page + 1)
                ->delay(Carbon::now()->addSeconds(10));
        }
    }

    public function getCookie()
    {
        // get latest cookies
        $client = new \GuzzleHttp\Client(['cookies' => true]);
        $r = $client->request('GET', 'http://portal.vtnation.com.my');
        $call_cookie = $client->getConfig('cookies');
        $call_cookie = $call_cookie->toArray();
        $latest_cookie = [];

        foreach ($call_cookie as $key => $row) {
            $latest_cookie[] = $row['Name'] . '=' . $row['Value'];
        }
        $latest_cookie = implode(';', $latest_cookie);

        // get access token
        $headers = [
            'Content-Type' => 'application/json',
            'Cookie' => $latest_cookie,
        ];
        $client = new \GuzzleHttp\Client(['headers' => $headers]);
        $res = $client->post('http://portal.vtnation.com.my/Services/DataControllerService.asmx/Login', [\GuzzleHttp\RequestOptions::JSON => [
            "username" => "CIEF",
            "password" => "0122120880",
            "createPersistentCookie" => true,
        ]]);

        $token = json_decode($res->getBody()->getContents());
        $token = $token->d->AccessToken;

        $latest_cookie = $latest_cookie . ';AppVTCC=' . $token;
        return $latest_cookie;
    }
}
