
<?php

require_once __DIR__ . '/../config/database.php';

class Slug
{

    /**
     * Generate SEO friendly slug
     */
    public static function generate($text)
    {
        $text = strtolower($text);

        // remove special characters
        $text = preg_replace('/[^a-z0-9\s-]/', '', $text);

        // replace spaces with hyphens
        $text = preg_replace('/[\s-]+/', '-', $text);

        // trim hyphens
        $text = trim($text, '-');

        return $text;
    }


    /**
     * Generate unique slug for a table
     */
    public static function generateUnique($table, $column, $text, $ignore_id = null)
    {

        $db = new Database();
        $conn = $db->connect();

        $slug = self::generate($text);

        $baseSlug = $slug;

        $i = 1;

        while (true) {

            if ($ignore_id) {

                $query = "
                SELECT id 
                FROM {$table} 
                WHERE {$column} = :slug 
                AND id != :id
                LIMIT 1
                ";

                $stmt = $conn->prepare($query);

                $stmt->execute([
                    ':slug' => $slug,
                    ':id' => $ignore_id
                ]);

            } else {

                $query = "
                SELECT id 
                FROM {$table} 
                WHERE {$column} = :slug 
                LIMIT 1
                ";

                $stmt = $conn->prepare($query);

                $stmt->execute([
                    ':slug' => $slug
                ]);
            }


            if ($stmt->rowCount() == 0) {
                break;
            }

            $slug = $baseSlug . '-' . $i;

            $i++;
        }

        return $slug;
    }

}