<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use HubSpot\Factory;
use HubSpot\Client\Crm\Contacts\ApiException;
use HubSpot\Client\Crm\Contacts\Model\SimplePublicObjectInput;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    public function sendcontact(Request $request)
    { 
        $client = Factory::createWithAccessToken('pat-na1-db5246bb-aa91-4736-b674-553f8dc27982');
        $data = $request->json();
        $simplePublicObjectInput = new SimplePublicObjectInput([
            'properties' => $data,
        ]);

        try {
            $client->crm()->contacts()->basicApi()->create($simplePublicObjectInput);
            return response()->json([
                'message' => 'contact added successfully'
            ], 201);
            
        } catch (ApiException $e) {
            if($e->getCode() == 409){
              $message =  $e->getResponseObject();
               $id = (int)filter_var($message['message'], FILTER_SANITIZE_NUMBER_INT);
                try {
                    $client->crm()->contacts()->basicApi()->update($id, $simplePublicObjectInput);
                    return response()->json([
                        'message' => 'contact updated successfully'
                    ], 201);
                   
                } catch (ApiException $e) {
                    return response()->json(["Exception when calling basic_api->update: " => $e->getMessage()
                    ], 201);
                }
            }
        }
    }


    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
