<?php
require_once('resource_base.php');
class lineitems extends resource_base
{

    public function __construct($service)
    {
        parent::__construct($service);
        $this->id = 'LineItem.collection';
        $this->template = '/{offeringid_contentdtlid}/lineitems';
        $this->variables[] = 'LineItems.url';
        $this->formats[] = 'application/vnd.ims.lis.v2.lineitemcontainer+json';
        $this->formats[] = 'application/vnd.ims.lis.v2.lineitem+json';
        $this->methods[] = self::HTTP_GET;
        $this->methods[] = self::HTTP_POST;
    }

    /**
     * Execute the request for this resource.
     *
     * @param response $response  Response object for this request.
     */
    public function execute($response, $date_time)
    {
        global $DB;

        $params = $this->parse_template();
        $contextid = $params['context_id'];
        $isget = $response->get_request_method() === self::HTTP_GET;
        if ($isget) {
            $contenttype = $response->get_accept();
        } else {
            $contenttype = $response->get_content_type();
        }
        $container = empty($contenttype) || ($contenttype === $this->formats[0]);
        // We will receive typeid when working with LTI 1.x, if not then we are in LTI 2.
        $typeid = "1";

        $scopes = array(gradebookservices::SCOPE_GRADEBOOKSERVICES_LINEITEM);
        if ($response->get_request_method() === self::HTTP_GET) {
            $scopes[] = gradebookservices::SCOPE_GRADEBOOKSERVICES_LINEITEM_READ;
        }

        try {
            if (!$this->check_tool($typeid, $response->get_request_data(), $scopes)) {
                throw new \Exception(null, 401);
            }
            $typeid = $this->get_service()->get_type()->id;
            if (
                empty($contextid) || !($container ^ ($response->get_request_method() === self::HTTP_POST)) ||
                (!empty($contenttype) && !in_array($contenttype, $this->formats))
            ) {
                throw new \Exception('No context or unsupported content type', 400);
            }
            if (!($course = $DB->get_record('course', array('id' => $contextid), 'id', 0))) {
                throw new \Exception("Not Found: Course {$contextid} doesn't exist", 404);
            }
            if (!$this->get_service()->is_allowed_in_context($typeid, $course->id)) {
                throw new \Exception('Not allowed in context', 403);
            }
            if ($response->get_request_method() !== self::HTTP_POST) {
                $resourceid = "1";
                $ltilinkid = "1"; //optional_param('resource_link_id', null, PARAM_TEXT);
                if (is_null($ltilinkid)) {
                    //$ltilinkid = optional_param('lti_link_id', null, PARAM_TEXT);
                }
                $tag = ""; // optional_param('tag', null, PARAM_TEXT);
                $limitnum = ""; //optional_param('limit', 0, PARAM_INT);
                $limitfrom = ""; //optional_param('from', 0, PARAM_INT);
                $itemsandcount = $this->get_service()->get_lineitems(
                    $contextid,
                    $resourceid,
                    $ltilinkid,
                    $tag,
                    $limitfrom,
                    $limitnum,
                    $typeid
                );
                $items = $itemsandcount[1];
                $totalcount = $itemsandcount[0];
                $json = $this->get_json_for_get_request(
                    $items,
                    $resourceid,
                    $ltilinkid,
                    $tag,
                    $limitfrom,
                    $limitnum,
                    $totalcount,
                    $typeid,
                    $response
                );
                $response->set_content_type($this->formats[0]);
            } else {
                $json = $this->get_json_for_post_request($response->get_request_data(), $contextid, $typeid);
                $response->set_code(201);
                $response->set_content_type($this->formats[1]);
            }
            $response->set_body($json);

        } catch (\Exception $e) {
            $response->set_code($e->getCode());
            $response->set_reason($e->getMessage());
        }
    }

    /**
     * Parse a value for custom parameter substitution variables.
     *
     * @param string $value String to be parsed
     *
     * @return string
     */
    public function parse_value($value, $offering_id, $contentdtl_id)
    {
        if (strpos($value, '$LineItems.url') !== false) {

            $this->params['offeringid_contentdtlid'] = $offering_id . "_" . $contentdtl_id;
            $query = '';
            if ($tool = $this->get_service()->get_type()) {
                $this->params['tool_code'] = $tool->typeid;
                $query = "?type_id={$tool->typeid}";
            }
            $value = str_replace('$LineItems.url', parent::get_endpoint() . $query, $value);
        }
        return $value;
    }
}