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

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

    /**
     * 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 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 (!($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);
            }
            // require_once($CFG->libdir.'/gradelib.php');
            switch ($response->get_request_method()) {
                case self::HTTP_GET:
                    $this->get_request($response, $item, $typeid);
                    break;
                case self::HTTP_PUT:
                    $json = $this->process_put_request($response->get_request_data(), $item, $typeid);
                    $response->set_body($json);
                    $response->set_code(200);
                    break;
                case self::HTTP_DELETE:
                    $this->process_delete_request($item);
                    $response->set_code(204);
                    break;
            }
        } 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, '$LineItem.url') !== false) {
            $resolved = '';

            $this->params['offeringid_contentdtlid'] = $offering_id . "_" . $contentdtl_id;
            if ($tool = $this->get_service()->get_type()) {
                $this->params['tool_code'] = $tool->typeid;
            }
            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();
                $resolved .= "?type_id={$tool->typeid}";
            }
            $value = str_replace('$LineItem.url', $resolved, $value);
        }
        return $value;
    }
}