<?php
namespace App\Repositories;

use App\Database\Database;

abstract class BaseRepository
{
    public Database $db;
    protected string $table;
    protected string $primaryKey = 'id';

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

    public function all(): array
    {
        return $this->db->select("SELECT * FROM `{$this->table}` ORDER BY `{$this->primaryKey}` DESC");
    }

    public function findById(int $id): ?array
    {
        $rows = $this->db->select(
            "SELECT * FROM `{$this->table}` WHERE `{$this->primaryKey}` = :id",
            ['id' => $id]
        );
        return $rows[0] ?? null;
    }

    public function create(array $data): int
    {
        return $this->db->insert($this->table, $data);
    }

    public function update(int $id, array $data): void
    {
        $this->db->update(
            $this->table,
            $data,
            "`{$this->primaryKey}` = {$id}"
        );
    }

    public function updateBySql(string $sql, array $data): void
    {
        $this->db->update(
            $this->table,
            $data,
            $sql
        );
    }

    public function delete(int $id): void
    {
        $this->db->delete(
            $this->table,
            "`{$this->primaryKey}` = {$id}"
        );
    }
}
