<?php

namespace App\Services;

use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;

class CookieService
{
    const COOKIE_NAME = 'FRONT_END_REST';
    const PUBLIC_KEY = 'PUBLIC_00001';
    const TIME_OUT_HOURS = 1; // 60 minutes

    public function setCookie(array $params, string $name = self::COOKIE_NAME): bool
    {
        try {
            if (!is_array($params)) {
                throw new \TypeError('setCookie params should be an array.', 'CookieService.php', 20);
            }

            $expiration = now()->addHours(self::TIME_OUT_HOURS);
            $encryptedValue = Crypt::encryptString(json_encode($params));

            Cookie::queue($name, $encryptedValue, $expiration->diffInMinutes(), '/', null, false, true);

            return true;
        } catch (\Exception $e) {
            Log::error('Cookie Set Error: ' . $e->getMessage());
            return false;
        }
    }

    public function getCookie(string $name = self::COOKIE_NAME)
    {
        $cookie = Cookie::get($name);

        if (!$cookie) {
            return null;
        }

        try {
            return json_decode(Crypt::decryptString($cookie), true);
        } catch (\Exception $e) {
            Log::error('Cookie Get Error: ' . $e->getMessage());
            return null;
        }
    }

    public function removeCookie(string $name = self::COOKIE_NAME): bool
    {
        Cookie::queue(Cookie::forget($name));
        return true;
    }
}