<?php

namespace Core;

class Model
{
    protected static $pdo;
    protected static $table;

    public static function setPdo(\PDO $pdo)
    {
        self::$pdo = $pdo;
    }

    public static function all()
    {
        $stmt = self::$pdo->query("SELECT * FROM " . static::$table);
        return $stmt->fetchAll();
    }

    public static function find($id)
    {
        $stmt = self::$pdo->prepare("SELECT * FROM " . static::$table . " WHERE id = ?");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }

    public static function findBySlug($slug)
    {
        $stmt = self::$pdo->prepare("SELECT * FROM " . static::$table . " WHERE slug = ?");
        $stmt->execute([$slug]);
        return $stmt->fetch();
    }

    public static function create(array $data)
    {
        $columns = implode(", ", array_keys($data));
        $placeholders = ":" . implode(", :", array_keys($data));
        $sql = "INSERT INTO " . static::$table . " ({$columns}) VALUES ({$placeholders})";
        $stmt = self::$pdo->prepare($sql);
        $stmt->execute($data);
        return self::$pdo->lastInsertId();
    }

    public static function update($id, array $data)
    {
        $fields = [];
        foreach ($data as $key => $value) {
            $fields[] = "{$key} = :{$key}";
        }
        $fields = implode(", ", $fields);
        $sql = "UPDATE " . static::$table . " SET {$fields}, updated_at = CURRENT_TIMESTAMP WHERE id = :id";
        $data["id"] = $id;
        $stmt = self::$pdo->prepare($sql);
        return $stmt->execute($data);
    }

    public static function delete($id)
    {
        $stmt = self::$pdo->prepare("DELETE FROM " . static::$table . " WHERE id = ?");
        return $stmt->execute([$id]);
    }
}
