<?php

namespace App\Repositories\Shop;

use App\Repositories\Core\File;
use Laravolt\Avatar\Avatar;

class CustomerAvatars
{
    public static function getImg($id = false)
    {
        $avatar = self::getAvatar($id);
        $name = Customers::getName($id);

        return "<img src='{$avatar}' class='img-fluid' title='{$name}'>";
    }

    public static function getAvatar($id = false)
    {
        $customer = $id ? Customers::get($id) : Customers::getAuth();
        $file = self::makeAvatarFilename($customer);
        if (!File::checkFile($file)) {
            self::createAvatar($customer);
        }

        return self::getPublic(self::getAvatarFilename($customer));
    }

    public static function createAvatar($customer)
    {
        $filename = self::makeAvatarFilename($customer);
        $name = $customer->first_name . ' ' . $customer->last_name;
        $avatar = new Avatar();

        return $avatar->create($name)
            ->setBackground('#F2B90F')
            ->setForeground('#335012')
            ->setBorder(1, '#28a745')
            ->setFontFamily('Roboto Condensed')
            ->setDimension(36)
            ->setFontSize(16)
            ->save($filename);
    }

    public static function makeAvatarFilename($customer)
    {
        $path = storage_path(self::getStorage());
        if (File::checkDirOrCreate($path)) {
            $filename = $path . self::getAvatarFilename($customer);
        }

        return $filename ?? false;
    }

    public static function getAvatarFilename($customer)
    {
        return 'user-' . $customer->uuid . '.png';
    }

    public static function getStorage($filename = false)
    {
        $path = '/app/public/Customers/';

        return $filename ? $path . $filename : $path;
    }

    public static function getPublic($filename = false)
    {
        $path = '/storage/Customers/';

        return $filename ? $path . $filename : $path;
    }
}
