<?php

namespace CouponsPlus\App\Handlers;

use CouponsPlus\Original\Events\Handler\EventHandler;
use WP_Post;
use WP_Query;

Class AutoGenerateCodeWhenEmptyHandler extends EventHandler
{
    protected $numberOfArguments = 2;
    protected $priority = 10;

    public function execute(int $postId, WP_Post $post)
    {
        if ($post->post_type !== 'shop_coupon') {
            return;
        }


        (string) $code = trim($post->post_title);

        if (!$code) {
            do {
                $code = strtoupper(bin2hex(random_bytes(4)));
            } while ($this->codeExistsInDatabase($code));

            wp_update_post([
                'ID' => $postId,
                'post_title' => $code
            ]);
        }
    }

    protected function codeExistsInDatabase(string $code) : bool
    {
        if (!trim($code)) {
            return true;
        }

        (object) $byCodeQuery = new WP_Query([
            'title' => $code,
            'post_type' => 'shop_coupon'
        ]);


        return (boolean) $byCodeQuery->posts;
    }
    
}