// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
/**
 * Availability password - Ajax file
 *
 * @package    availability_password
 * @copyright  2016 Davo Smith, Synergy Learning UK on behalf of Alexander Bias, University of Ulm <*****@*****.**>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
define('AJAX_SCRIPT', true);
require_once dirname(__FILE__) . '/../../../config.php';
global $PAGE;
$cmid = required_param('id', PARAM_INT);
$password = required_param('password', PARAM_RAW);
/** @var cm_info $cm */
list($course, $cm) = get_course_and_cm_from_cmid($cmid);
$url = new moodle_url('/availability/condition/password/ajax.php', array('id' => $cm->id));
$PAGE->set_url($url);
require_login($course, false);
require_sesskey();
$ret = (object) ['error' => 0, 'success' => 0];
if (\availability_password\condition::submit_password_for_cm($cm, $password)) {
    $ret->success = 1;
    // Check if the activity can now be accessed.
    $modinfo = get_fast_modinfo($course);
    $cminfo = $modinfo->get_cm($cm->id);
    if ($cminfo->available) {
        $ret->redirect = $cm->url->out(false);
    }
}
echo json_encode($ret);
die;
$cmid = required_param('id', PARAM_INT);
/** @var cm_info $cm */
list($course, $cm) = get_course_and_cm_from_cmid($cmid);
$url = new moodle_url('/availability/condition/password/index.php', array('id' => $cm->id));
$PAGE->set_url($url);
require_login($course, false);
$custom = array('cm' => $cm);
$form = new \availability_password\password_form(null, $custom);
$error = '';
$format = course_get_format($course);
$courseredir = $format->get_view_url(null);
if ($form->is_cancelled()) {
    redirect($courseredir);
}
if ($data = $form->get_data()) {
    if (\availability_password\condition::submit_password_for_cm($cm, $data->activitypassword)) {
        redirect($courseredir);
    } else {
        $error = get_string('wrongpassword', 'availability_password');
    }
}
$title = get_string('enterpasswordfor', 'availability_password', $cm->get_formatted_name());
$PAGE->set_pagelayout('incourse');
$PAGE->set_title($title);
$PAGE->set_heading($title);
echo $OUTPUT->header();
if ($error) {
    echo html_writer::div($error, 'error');
}
$form->display();
echo $OUTPUT->footer();