<?php
class Database {
    private $pdo;
    
    public function __construct($pdo) {
        $this->pdo = $pdo;
    }
    
    // Select Query
    public function select($query, $params = []) {
        try {
            $stmt = $this->pdo->prepare($query);
            $stmt->execute($params);
            return $stmt->fetchAll();
        } catch(PDOException $e) {
            return [];
        }
    }
    
    // Select Single Row
    public function selectOne($query, $params = []) {
        try {
            $stmt = $this->pdo->prepare($query);
            $stmt->execute($params);
            return $stmt->fetch();
        } catch(PDOException $e) {
            return null;
        }
    }
    
    // Insert Query
    public function insert($table, $data) {
        $columns = implode(',', array_keys($data));
        $placeholders = implode(',', array_fill(0, count($data), '?'));
        $query = "INSERT INTO $table ($columns) VALUES ($placeholders)";
        $stmt = $this->pdo->prepare($query);
        $stmt->execute(array_values($data));
        return $this->pdo->lastInsertId();
    }
    
    // Update Query
    public function update($table, $data, $where = []) {
        try {
            $set = implode(',', array_map(fn($k) => "$k = ?", array_keys($data)));
            $whereClause = implode(' AND ', array_map(fn($k) => "$k = ?", array_keys($where)));
            $query = "UPDATE $table SET $set WHERE $whereClause";
            $params = array_merge(array_values($data), array_values($where));
            $stmt = $this->pdo->prepare($query);
            return $stmt->execute($params);
        } catch(PDOException $e) {
            return false;
        }
    }
    
    // Delete Query
    public function delete($table, $where = []) {
        try {
            $whereClause = implode(' AND ', array_map(fn($k) => "$k = ?", array_keys($where)));
            $query = "DELETE FROM $table WHERE $whereClause";
            $stmt = $this->pdo->prepare($query);
            return $stmt->execute(array_values($where));
        } catch(PDOException $e) {
            return false;
        }
    }
    
    // Count Query
    public function count($table, $where = []) {
        try {
            $whereClause = !empty($where) ? ' WHERE ' . implode(' AND ', array_map(fn($k) => "$k = ?", array_keys($where))) : '';
            $query = "SELECT COUNT(*) as total FROM $table" . $whereClause;
            $stmt = $this->pdo->prepare($query);
            $stmt->execute(array_values($where));
            $result = $stmt->fetch();
            return $result['total'] ?? 0;
        } catch(PDOException $e) {
            return 0;
        }
    }
    
    // Get PDO instance
    public function getPDO() {
        return $this->pdo;
    }
}
