<?php
declare(strict_types=1);

namespace App\Core;

abstract class Repository
{
    protected Database $db;
    protected static string $table = '';

    public function __construct(?Database $db = null)
    {
        $this->db = $db ?? App::getInstance()->db();
    }

    public function find(int $id): ?array
    {
        return $this->db->selectOne(
            "SELECT * FROM `" . static::$table . "` WHERE id = ? AND is_archived = 0",
            [$id]
        );
    }

    public function findOrFail(int $id): array
    {
        $row = $this->find($id);
        if ($row === null) {
            throw new \RuntimeException('Record not found', 404);
        }
        return $row;
    }

    protected function paginate(string $countSql, string $dataSql, array $params, int $page, int $perPage): array
    {
        $total = (int) ($this->db->selectOne($countSql, $params)['cnt'] ?? 0);
        $offset = ($page - 1) * $perPage;
        $data = $this->db->select($dataSql . " LIMIT {$perPage} OFFSET {$offset}", $params);
        return [
            'data' => $data,
            'pagination' => Pagination::paginate($total, $perPage, $page),
        ];
    }
}
