<?php

class ByCategoryApi extends Api
{
    public $apiName = 'bycategory';

    public function indexAction()
    {
        return $this->response(
            array(
                'error' => 'Data not found'
            ), 404);
    }

    /**
     * Method GET
     * Get single record (by id)
     * http://DOMAIN/trips/1
     * @return string
     */
    public function viewAction()
    {
        //id must be the first parameter after /trips/x
        $id = array_shift($this->requestUri);

        if($id && (int)$id>0){
            $db = new Db();
            $tripOptions = Trips::getOptionsById($db->getConnect(), (int)$id);
            if(is_array($tripOptions) && count($tripOptions)>0){
                return $this->response(
                    array(
                        'id' => $id,
                        'count' => count($tripOptions),
                        'options' => $tripOptions
                    ), 200);
            }
        }
        return $this->response(
            array(
                'error'=> 'Data not found'
            ), 404);
    }

    public function createAction()
    {
        $message = 'Data not found';
        $code = 404;
        $category = strtolower($this->requestParams['category'] ?? '');
        $member_id = $this->requestParams['member_id'] ?? 0;
        try {
            if ($member_id<1) {
                throw new RuntimeException('Invalid member ID',500);
            }
            if ($category=='' || !array_key_exists($category,ByCategory::CATEGORIES)) { 
                throw new RuntimeException('Invalid category',500);
            }
            if (ByCategory::CATEGORIES[$category]!=1) {
                throw new RuntimeException('Data not found',404);
            }
            $db = new Db();
            list($res,$err) = ByCategory::andMemberId($db->getConnect(), $category, $member_id);
            if (!$res) {
                if ($err!="") {
                    throw new RuntimeException($err, 500);
                }
                throw new RuntimeException('Data not found', 404);
            }
            return $this->response(
                array(
                    "trips" => $res
                ), 200);
        } catch (RuntimeException $e) {
            $message = $e->getMessage();
            $code = $e->getCode();
        }
        return $this->response(
            array(
                "error" => $message
            ), $code);
    }

    public function updateAction()
    {
        return $this->response(
            array(
                "error" => "Update error"
            ), 400);
    }

    public function deleteAction()
    {
        return $this->response(
            array(
                "error" => "Delete error"
            ), 500);
    }
}
