<?php

use Mtc\Shop\Assessment\Form;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$page_meta['title'] = 'Manage Assessment Forms';

$errors = [];

if ($_REQUEST['action'] === 'delete' && is_numeric($_REQUEST['delete_id'])) {
    $form = (new Form())->find($_REQUEST['delete_id']);
    if ($form->answers()->count() > 0) {
        $errors[] = 'The assessment form cannot deleted as it has answers attached to it';
    } else {
        // Delete the questions
        $form->questions()->delete();
        // Delete the form
        $form->delete();
        header('location: manage.forms.php');
        exit;
    }
}

$forms = Form::query()->orderBy('name')->get();

require_once $path . 'core/admin/templates/adminheader.html.php';

?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>

    <li class="end">Assessment Forms</li>
</ul>

<h1>Assessment Forms</h1>
<?php

include __DIR__ . '/tabnav.php';

if (count($errors)>0) { showerrors($errors); }

if (!$forms->isEmpty()) {
    ?>
    <form method="post">
        <table class="manage-items">
            <tr>
                <th>Name</th>
                <th>Number of questions</th>
                <th class="center">Copy</th>
                <th class="center">Edit</th>
                <th class="center">Delete</th>
            </tr>
            <tbody class="tabular">
            <?php
            foreach ($forms as $form) {
                ?>
                <tr>
                    <td><?= $form->name; ?></td>
                    <td><?= $form->questions->count(); ?></td>
                    <td class="center"><a href="/shop/admin/assessment/copy.form.php?id=<?= $form->id; ?>" title="Make a copy of this form"><i class="fa fa-copy"></i></a></td>
                    <td class="center"><a href="manage.form.php?id=<?=$form->id; ?>" class="edit" title="Edit this form"><i class="fa fa-pencil"></i></a></td>
                    <td class="center"><a href="manage.forms.php?action=delete&delete_id=<?=$form->id; ?>" class="alert picto error" title="Are you sure you want to delete the Assessment Form?"><i class="fa fa-times-circle"></i></a></td>
                </tr>
                <?php
            }
            ?>
            </tbody>
        </table>
        <input type="hidden" name="action" value="update">
    </form>
    <?php
} else {
    ?>
    <p>No Assessment Forms have been created</p>
    <?php
}

require_once $path . 'core/admin/templates/adminfooter.html.php';
