<?php

namespace App\Core;

abstract class Model
{
    protected static string $table = '';

    protected static function db(): \PDO
    {
        return Database::getInstance();
    }

    public static function findAll(string $orderBy = 'id DESC'): array
    {
        $table = static::$table;
        $stmt = static::db()->query("SELECT * FROM {$table} ORDER BY {$orderBy}");
        return $stmt->fetchAll();
    }

    public static function find(int $id): ?array
    {
        $table = static::$table;
        $stmt = static::db()->prepare("SELECT * FROM {$table} WHERE id = :id");
        $stmt->execute(['id' => $id]);
        $result = $stmt->fetch();
        return $result ?: null;
    }

    public static function create(array $data): int
    {
        $table = static::$table;
        $columns = implode(', ', array_keys($data));
        $placeholders = ':' . implode(', :', array_keys($data));

        $stmt = static::db()->prepare("INSERT INTO {$table} ({$columns}) VALUES ({$placeholders})");
        $stmt->execute($data);
        return (int) static::db()->lastInsertId();
    }

    public static function update(int $id, array $data): bool
    {
        $table = static::$table;
        $set = implode(', ', array_map(fn($k) => "{$k} = :{$k}", array_keys($data)));

        $data['id'] = $id;
        $stmt = static::db()->prepare("UPDATE {$table} SET {$set} WHERE id = :id");
        return $stmt->execute($data);
    }

    public static function delete(int $id): bool
    {
        $table = static::$table;
        $stmt = static::db()->prepare("DELETE FROM {$table} WHERE id = :id");
        return $stmt->execute(['id' => $id]);
    }

    public static function count(string $where = '1=1', array $params = []): int
    {
        $table = static::$table;
        $stmt = static::db()->prepare("SELECT COUNT(*) FROM {$table} WHERE {$where}");
        $stmt->execute($params);
        return (int) $stmt->fetchColumn();
    }

    public static function where(string $condition, array $params = [], string $orderBy = 'id DESC'): array
    {
        $table = static::$table;
        $stmt = static::db()->prepare("SELECT * FROM {$table} WHERE {$condition} ORDER BY {$orderBy}");
        $stmt->execute($params);
        return $stmt->fetchAll();
    }
}
