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

    /**
     * Class constructor.
     *
     * @param gradebookservices $service Service instance
     */
    public function __construct($service) {
        parent::__construct($service);
        $this->id = 'Result.collection';
        $this->template = '/{offeringid_contentdtlid}/lineitems/{item_id}/lineitem/results';
        $this->variables[] = 'Results.url';
        $this->formats[] = 'application/vnd.ims.lis.v2.resultcontainer+json';
        $this->methods[] = 'GET';
    }

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

        $params = $this->parse_template();
        $contextid = $params['context_id'];
        $itemid = $params['item_id'];

        $isget = $response->get_request_method() === self::HTTP_GET;
        // We will receive typeid when working with LTI 1.x, if not the we are in LTI 2.
        $typeid = "1";

        $scope = gradebookservices::SCOPE_GRADEBOOKSERVICES_RESULT_READ;

        try {
            if (!$this->check_tool($typeid, $response->get_request_data(), array($scope))) {
                throw new \Exception(null, 401);
            }
            $typeid = $this->get_service()->get_type()->id;
            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 (!$DB->record_exists('grade_items', array('id' => $itemid))) {
                throw new \Exception("Not Found: Grade item {$itemid} doesn't exist", 404);
            }
            $item = $this->get_service()->get_lineitem($contextid, $itemid, $typeid);
            if ($item === false) {
                throw new \Exception('Line item does not exist', 404);
            }
            $gbs = gradebookservices::find_ltiservice_gradebookservice_for_lineitem($itemid);
            $ltilinkid = null;
            if (isset($item->iteminstance)) {
                $ltilinkid = $item->iteminstance;
            } else if ($gbs && isset($gbs->ltilinkid)) {
                $ltilinkid = $gbs->ltilinkid;
            }
            if ($ltilinkid != null) {
                if (is_null($typeid)) {
                    if (isset($item->iteminstance) && (!gradebookservices::check_lti_id($ltilinkid, $item->courseid,
                            $this->get_service()->get_tool_proxy()->id))) {
                        $response->set_code(403);
                        $response->set_reason("Invalid LTI id supplied.");
                        return;
                    }
                } else {
                    if (isset($item->iteminstance) && (!gradebookservices::check_lti_1x_id($ltilinkid, $item->courseid,
                            $typeid))) {
                        $response->set_code(403);
                        $response->set_reason("Invalid LTI id supplied.");
                        return;
                    }
                }
            }
            require_once($CFG->libdir.'/gradelib.php');
            switch ($response->get_request_method()) {
                case 'GET':
                    $useridfilter = "1"; //optional_param('user_id', 0, PARAM_INT);
                    $limitnum = ""; //optional_param('limit', 0, PARAM_INT);
                    $limitfrom = ""; //optional_param('from', 0, PARAM_INT);
                    $typeid = "1"; //optional_param('type_id', null, PARAM_TEXT);
                    $json = $this->get_json_for_get_request($item->id, $limitfrom, $limitnum,
                            $useridfilter, $typeid, $response);
                    $response->set_content_type($this->formats[0]);
                    $response->set_body($json);
                    break;
                default:  // Should not be possible.
                    $response->set_code(405);
                    $response->set_reason("Invalid request method specified.");
                    return;
            }
            $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) {
        $lti = new LTI();
        if (strpos($value, '$Results.url') !== false) {

            $this->params['offeringid_contentdtlid'] = $offering_id . "_" . $contentdtl_id;
            $resolved = '';
            if (!empty($contentdtl_id)) {
                $lti_id = "";
                $grade_items_id = "";
                $lti_class_record = $lti->get_lti($contentdtl_id);
                if ($result = $lti_class_record->fetch(PDO::FETCH_ASSOC)) {
                    $lti_id = $result['lti_id'];
                }
                $grade_items_record = $lti->get_grade_items($contentdtl_id, $lti_id);
                if ($result = $grade_items_record->fetch(PDO::FETCH_ASSOC)) {
                    $grade_items_id = $result['grade_items_id'];
                }
                $this->params['item_id'] = $grade_items_id;
                $resolved = parent::get_endpoint();
            }
            $value = str_replace('$Results.url', $resolved, $value);
        }
        return $value;
    }
}