<?php

define('AJAX_SCRIPT', true);
require '../../config.php';
require_once "lib/panopto_data.php";
try {
    require_login();
    require_sesskey();
    header('Content-Type: text/html; charset=utf-8');
    global $CFG;
    $courseid = $_POST["courseid"];
    // Sync role mapping. In case this is the first time block is running we need to load old settings from db.
    // They will be the default values if this is the first time running.
    $mapping = panopto_data::get_course_role_mappings($courseid);
    panopto_data::set_course_role_permissions($courseid, $mapping['publisher'], $mapping['creator']);
    $content = new stdClass();
    //Initialize $content->text to an empty string here to avoid trying to append to it before
    //it has been initialized and throwing a warning. Bug 33163
    $content->text = "";
    // Construct the Panopto data proxy object.
    $panoptodata = new panopto_data($courseid);
    if (empty($panoptodata->servername) || empty($panoptodata->instancename) || empty($panoptodata->applicationkey)) {
        $content->text = get_string('unprovisioned', 'block_panopto') . "\n            <br/><br/>\n            <a href='{$CFG->wwwroot}/blocks/panopto/provision_course_internal.php?id={$courseid}'>" . get_string('provision_course_link_text', 'block_panopto') . "</a>";
        $content->footer = "";
        return $content;
    }
    try {
        if (!$panoptodata->sessiongroupid) {
            $content->text = get_string('no_course_selected', 'block_panopto');
        } else {
            // Get course info from SOAP service.