<?php

namespace App\Models;

use App\Core\Model;

class Redirect extends Model
{
    protected static string $table = 'iw_redirects';

    /**
     * Find an active redirect for the given source path.
     */
    public static function findBySource(string $sourcePath): ?array
    {
        return static::db()->fetch(
            "SELECT * FROM iw_redirects WHERE source_path = :path AND is_active = 1 LIMIT 1",
            ['path' => $sourcePath]
        );
    }

    /**
     * Increment the hit counter for a redirect.
     */
    public static function incrementHits(int $id): void
    {
        static::db()->query(
            "UPDATE iw_redirects SET hit_count = hit_count + 1 WHERE id = :id",
            ['id' => $id]
        );
    }

    /**
     * Paginated list for admin (newest first).
     */
    public static function paginated(int $page = 1, int $perPage = 25): array
    {
        $page    = max(1, $page);
        $perPage = max(1, min(100, $perPage));
        $offset  = ($page - 1) * $perPage;

        $total = (int) static::db()->fetch(
            "SELECT COUNT(*) AS c FROM iw_redirects"
        )['c'];

        $items = static::db()->fetchAll(
            "SELECT * FROM iw_redirects
             ORDER BY created_at DESC
             LIMIT " . (int) $perPage . " OFFSET " . (int) $offset
        );

        return [
            'items'   => $items,
            'total'   => $total,
            'page'    => $page,
            'perPage' => $perPage,
            'pages'   => (int) ceil($total / $perPage),
        ];
    }

    /**
     * Create an auto-redirect when a slug changes.
     * Silently skips if the source path already has a redirect.
     */
    public static function createAutoRedirect(string $oldPath, string $newPath): void
    {
        $existing = static::findBySource($oldPath);
        if ($existing) {
            // Update existing redirect to point to new target
            static::updateById((int) $existing['id'], [
                'target_url'  => $newPath,
                'updated_at'  => date('Y-m-d H:i:s'),
            ]);
            return;
        }

        static::create([
            'source_path' => $oldPath,
            'target_url'  => $newPath,
            'status_code' => 301,
            'is_active'   => 1,
            'created_at'  => date('Y-m-d H:i:s'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ]);
    }
}
