<?php
class DBA {
    private $connection;
    private $statement;
    private $bind_params = array();
    private $param_types = '';

    public function __construct($connection) {
        $this->connection = $connection;
    }

    public function prepare($query) {
        $this->statement = $this->connection->prepare($query);
        if (!$this->statement) {
            throw new Exception("Error preparando consulta: " . $this->connection->error);
        }
        $this->bind_params = array();
        $this->param_types = '';
        return $this;
    }

    public function bind($types, ...$params) {
        $this->param_types .= $types;
        foreach ($params as $param) {
            $this->bind_params[] = $param;
        }
        return $this;
    }

    public function execute() {
        if (!empty($this->bind_params)) {
            $this->statement->bind_param($this->param_types, ...$this->bind_params);
        }

        if (!$this->statement->execute()) {
            throw new Exception("Error ejecutando consulta: " . $this->statement->error);
        }
        return $this;
    }

    public function fetch() {
        $result = $this->statement->get_result();
        if (!$result) {
            return array();
        }

        $data = array();
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
        return $data;
    }

    public function fetchOne() {
        $result = $this->statement->get_result();
        if (!$result) {
            return null;
        }
        return $result->fetch_assoc();
    }

    public function getInsertId() {
        return $this->connection->insert_id;
    }

    public function getAffectedRows() {
        return $this->statement->affected_rows;
    }

    public function close() {
        if ($this->statement) {
            $this->statement->close();
        }
    }

    public function __destruct() {
        $this->close();
    }
}
?>