<?php
require_once("../config/database.php");
require_once("response.php");
require_once("gradebookservices.php");
$response = new response();

$isget = $response->get_request_method() === resource_base::HTTP_GET;//GET Method
$isdelete = $response->get_request_method() === resource_base::HTTP_DELETE;//DELETE Method

if ($isget) {
    $response->set_accept(isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : '');
} else {
    $response->set_content_type(isset($_SERVER['CONTENT_TYPE']) ? explode(';', $_SERVER['CONTENT_TYPE'], 2)[0] : '');
}

$ok = false;
$path = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : ''; //PATH_INFO = The url after services.php. Example:/offeringid_contentdtlid/lineitems/gradeitemid/lineitem/scores

$accept = $response->get_accept();
$contenttype = $response->get_content_type();

$service = new gradebookservices();
//Get all resources lineitem,lineitems,results,scores
$resources = $service->get_resources();

foreach ($resources as $resource) {
    //Compare resource format with content type
    if (
        ($isget && !empty($accept) && (strpos($accept, '*/*') === false) &&
            !in_array($accept, $resource->get_formats())) ||
        ((!$isget && !$isdelete) && !in_array($contenttype, $resource->get_formats()))
    ) {
        continue;
    }
    $template = $resource->get_template();
    $template = preg_replace('/{config_type}/', '(toolproxy|tool)', $template);
    $template = preg_replace('/\{[a-zA-Z_]+\}/', '[^/]+', $template);
    $template = preg_replace('/\(([0-9a-zA-Z_\-,\/]+)\)/', '(\\1|)', $template);
    $template = str_replace('/', '\/', $template);
    if (preg_match("/^{$template}$/", $path) === 1) {
        //If resource template matches PATH_INFO then return that resource
        $ok = true;
        break 1;
    }
}

if (!$ok) {
    $response->set_code(400);
    $response->set_reason("No handler found for {$path} {$accept} {$contenttype}");
} else {
    //Get JSON data
    $body = file_get_contents('php://input');
    $response->set_request_data($body);
    if (in_array($response->get_request_method(), $resource->get_methods())) {
        //Execute resource
        $resource->execute($response,$date_time);
    } else {
        $response->set_code(405);
    }
}
//Send response to provider
$response->send();