<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\MasterProduct;
use App\Models\WarehouseStock;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class AccurateOnlineController extends Controller
{
    public function sync(Request $request)
    {
        $this->auth($request);
    }

    public function auth(Request $request)
    {
        $client = new \GuzzleHttp\Client();

        $authToken = base64_encode(config('app.aol_client_id') . ':' . config('app.aol_client_secret'));
        // dd($authToken);
        $header = [
            'Authorization' => 'Basic ' . $authToken
        ];

        $body = [
            'code' => $request->code,
            'grant_type' => 'authorization_code',
            'redirect_uri' => config('app.aol_redirect_url')
        ];

        $response = $client->request(
            'POST',
            config('app.aol_auth_url'),
            [
                'headers' => $header,
                'form_params' => $body
                ]
            );

        $response = $response->getBody()->getContents();
        $data = json_decode($response, true);
        
        $accessToken = $data['access_token'];
        // dd($accessToken);
        $this->getDatabase($accessToken);
    }

    public function getDatabase($accessToken)
    {
        $client = new \GuzzleHttp\Client();

        $header = [
            'Authorization' => 'Bearer ' . $accessToken
        ];

        $response = $client->request(
            'POST',
            config('app.aol_get_db_url'),
            [
                'headers' => $header
            ]
        );
        
        $response = $response->getBody()->getContents();
        $data = json_decode($response, true);
        
        $dbId = $data['d'][0]['id'];
        // dd($dbId);
        
        $this->openDatabase($accessToken, $dbId);
    }

    public function openDatabase($accessToken, $id)
    {
        $client = new \GuzzleHttp\Client();

        $header = [
            'Authorization' => 'Bearer ' . $accessToken
        ];

        $body = [
            'id' => $id
        ];

        $response = $client->request(
            'POST',
            config('app.aol_open_db_url'),
            [
                'headers' => $header,
                'form_params' => $body
            ]
        );

        $response = $response->getBody()->getContents();
        $data = json_decode($response, true);
        
        $host = $data['host'];
        $session = $data['session'];
        // dd($session);

        $this->getList($host, $accessToken, $session);
    }

    public function getList($host, $accessToken, $session)
    {
        $client = new \GuzzleHttp\Client();

        $url = $host . '/accurate/api/item/list.do';

        $header = [
            'Authorization' => 'Bearer ' . $accessToken,
            'X-Session-ID' => $session
        ];

        $body = [
            'fields' => 'id,name,no,quantity,balanceUnitCost'
        ];

        $response = $client->request(
            'POST',
            $url,
            [
                'headers' => $header,
                'form_params' => $body
            ]
        );

        $response = $response->getBody()->getContents();
        $data = json_decode($response, true);

        $this->insertToDB($data);
    }

    public function insertToDB($data)
    {
        // dd($data['d']);
        // $item = MasterProduct::findOrFail();
        try {
            for($i=0; $i<count($data['d']); $i++) {
                MasterProduct::updateorcreate([
                    'id' => $data['d'][$i]['id'],
                    'nama' => $data['d'][$i]['name'],
                    'kode' => $data['d'][$i]['no'],
                    'qty' => $data['d'][$i]['quantity'],
                    'harga_beli' => $data['d'][$i]['balanceUnitCost']
                ]);
                WarehouseStock::updateorcreate([
                    'product_id' => $data['d'][$i]['id'],
                    // 'qty' => $data['d'][$i]['quantity'],
                ]);
            }
            return ['result'=>'Berhasil insert'];
        } catch (Exception $err) {
            Log::error($err);
            return ['result'=>$err];
        }
    }
}
