<?PHP
/**
 * Helper for noda hierarchies.
 *
 * @author Joshua Ramon Enslin <joshua@jrenslin.de>
 */
declare(strict_types = 1);

/**
 * Class for splitting times.
 */
final class NodaHierarchyHelper {
    /**
     * Finds highest related tag.
     *
     * @param MDMysqli          $mysqli_noda DB connection.
     * @param integer           $tag_id      Tag ID to find in hierarchy.
     * @param MDMysqliStmt|null $higherStmt  Statement for getting higher IDs from
     *                                       the hierarchy.
     *
     * @return integer
     */
    public static function findHighestRelatedTag(MDMysqli $mysqli_noda, int $tag_id, $higherStmt = null):int {

        $builtHigherStmt = false;
        if (!$higherStmt instanceof MDMysqliStmt) {
            $higherStmt = $mysqli_noda->do_prepare("SELECT `tag_mayor_id`
                FROM `tag_relation`
                WHERE `tag_relation`.`tag_relation` != 2
                    AND `tag_menor_id` = ?
                LIMIT 1");
            $builtHigherStmt = true;
        }

        $higherStmt->bind_param("i", $tag_id);
        $higherStmt->execute();

        $result = $higherStmt->do_get_result();
        if ($cur = $result->fetch_row()) {
            $curID = (int)$cur[0];
            $output = self::findHighestRelatedTag($mysqli_noda, $curID, $higherStmt);
        }
        else {
            $output = $tag_id;
        }

        if ($builtHigherStmt === true) {
            $higherStmt->close();
        }

        return $output;

    }
}
