<?php

declare(strict_types=1);

namespace App\Models;

class Backup extends BaseModel
{
    protected string $table = 'backups';

    public function createBackupRecord(array $data): int
    {
        return $this->create($data);
    }

    public function getBackups(int $page = 1, int $perPage = 20): array
    {
        $perPage = max(1, $perPage);
        $offset = ($page - 1) * $perPage;

        $total = (int) $this->queryOne("SELECT COUNT(*) as cnt FROM {$this->table}")['cnt'];

        $items = $this->query(
            "SELECT b.*, u.name as created_by_name
             FROM {$this->table} b
             LEFT JOIN users u ON b.created_by = u.id
             ORDER BY b.created_at DESC
             LIMIT {$perPage} OFFSET {$offset}"
        );

        return ['items' => $items, 'total' => $total, 'page' => $page, 'per_page' => $perPage, 'total_pages' => (int) ceil($total / max(1, $perPage))];
    }
}
