<?php
class Database {
    private $pdo;
    private $stmt;

    public function __construct($host, $dbname, $username, $password) {
        $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8";
        $this->pdo = new PDO($dsn, $username, $password);
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function query($sql, $params = []) {
        $this->stmt = $this->pdo->prepare($sql);
        $this->stmt->execute($params);
    }

    public function fetch($sql, $params = []) {
        $this->query($sql, $params);
        return $this->stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function fetchAll($sql, $params = []) {
        $this->query($sql, $params);
        return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function execute($sql, $params = []) {
        $this->query($sql, $params);
        return $this->stmt->rowCount();
    }

    public function insert($table, $data) {
        $fields = implode(", ", array_keys($data));
        $placeholders = ":" . implode(", :", array_keys($data));
        $sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
        $this->execute($sql, $data);
        return $this->pdo->lastInsertId();
    }

    public function update($table, $data, $where = []) {
        $fields = "";
        foreach ($data as $key => $value) {
            $fields .= "$key = :$key, ";
        }
        $fields = rtrim($fields, ", ");
        if (count($where) > 0) {
        $whereClause = "";
        foreach ($where as $key => $value) {
            $whereClause .= "$key = :$key AND ";
        }
        $whereClause = rtrim($whereClause, " AND ");
        $sql = "UPDATE $table SET $fields WHERE $whereClause";
        } else {
            $sql = "UPDATE $table SET $fields";
        }
        $params = array_merge($data, $where);
        return $this->execute($sql, $params);
    }

    public function delete($table, $where) {
        $whereClause = "";
        foreach ($where as $key => $value) {
            $whereClause .= "$key = :$key AND ";
        }
        $whereClause = rtrim($whereClause, " AND ");
        $sql = "DELETE FROM $table WHERE $whereClause";
        return $this->execute($sql, $where);
    }
}

// $db = new Database('localhost', 'dbname', 'username', 'password');

// // Tekli getirme
// $user = $db->fetch("SELECT * FROM users WHERE id = ?", [1]);
// print_r($user);

// // Çoklu getirme
// $users = $db->fetchAll("SELECT * FROM users");
// print_r($users);

// // Ekleme
// $newUserId = $db->insert('users', [
//     'name' => 'John Doe',
//     'email' => 'john@example.com'
// ]);
// echo "Yeni kullanıcı ID: " . $newUserId;

// // Güncelleme
// $updateCount = $db->update('users', ['name' => 'Jane Doe'], ['id' => $newUserId]);
// echo "Güncellenen satır sayısı: " . $updateCount;

// // Silme
// $deleteCount = $db->delete('users', ['id' => $newUserId]);
// echo "Silinen satır sayısı: " . $deleteCount;
?>
