<?php

namespace Model;

use Fuel\Core\Model;
use Fuel\Core\DB;
use Fuel\Core\Config;

class AuthAccess extends Model
{
    private $level_table = 'level';

    private $userId = 1;


    public function __construct()
    {
        Config::load('level');
    }

    /**
     * Update user access right.
     *
     * @param array $authority
     * @return string
     */
    public function newLevel($authority)
    {
        $check = $this->checkCategories(array_keys($authority));
        if (!$check) {
            return "Categories not exist";
        }

        $result = DB::update($this->level_table)
            ->set($authority)
            ->where('UserId', '=', $this->userId)
            ->execute();

        if ($result) {
            return 'success';
        }

        return 'fail';
    }

    /**
     * Fetch all access rights of user.
     *
     * @return array
     */
    public function getAllLevel()
    {
        $result = DB::select('*')
            ->from($this->level_table)
            ->where('UserId', '=', $this->userId)
            ->execute();

        return $this->resultHandler($result);
    }

    private function checkCategories($levelSeted)
    {
        foreach ($levelSeted as $val) {
            if (!array_key_exists($val, Config::get('category'))) {
                return false;
            }
        }

        return true;
    }

    /**
     * Return result pretreated.
     *
     * @param object $query
     * @return array
     */
    private function resultHandler($query)
    {
        $result = array(
            'status' => 'fail',
            'result' => '',
        );

        if ($query) {
            $result['status'] = 'success';
            $result['result'] = $query->as_array();
        }

        return $result;
    }
}