<?php

class UserManager
{
    protected $couchbase;

    public function __construct(\Couchbase $couchbase)
    {
        $this->couchbase = $couchbase;
    }

    public function create(array $data)
    {
        try {
            $id = $this->makeId();

            $this->couchbase->add("users::$id", json_encode($data));

            return $id;
        } catch (\CouchbaseException $e) {
            die('Unable to create user. The error is:' . $e->getMessage());
        }
    }

    public function read($id)
    {
        try {
            return json_decode($this->couchbase->get("users::$id"));
        } catch (\CouchbaseException $e) {
            die('Unable to read user. The error is:' . $e->getMessage());
        }
    }

    public function update($id, array $data)
    {
        try {
            return $this->couchbase->set("users::$id", json_encode($data));
        } catch (\CouchbaseException $e) {
            die('Unable to update user. The error is:' . $e->getMessage());
        }
    }

    public function delete($id)
    {
        try {
            return $this->couchbase->delete("users::$id");
        } catch (\CouchbaseException $e) {
            die('Unable to delete user. The error is:' . $e->getMessage());
        }
    }

    protected function makeId()
    {
        return $this->couchbase->increment('counter::users', 1, true);
    }
}