<?php

use Mtc\Shop\Medication;

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

$page_meta['title'] = 'Manage Medications';


if (filter_input(INPUT_POST, 'action') === 'import_medications') {
    $response = \Mtc\Shop\Medication::importMedications();
    $errors = $response['errors'];
    if (empty($errors)) {
        $query_params = $_GET;
        $query_params['success'] = 'import_successful';
        $_SESSION['flash_messages']['success'] = $response['success'];
        header('location: manage.medications.php?' . http_build_query($query_params));
        exit;
    }
}

$totalnumrows = Medication::query()->count();

$rowsPerPage = 100;
$pageNum = $_GET['page'] ?? 1;
$offset = ($pageNum - 1) * $rowsPerPage;
$pagestoshow = 10;

$medications = Medication::query()->orderBy('name')->take($rowsPerPage)->skip($offset)->get();

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end"><?= clean_page($page_meta['title']) ?></li>
</ul>

<h1>Manage Medications</h1>

<?php
include __DIR__ . '/tabnav.php';

if (empty($errors) && isset($GLOBALS['flash_messages']) && !empty($GLOBALS['flash_messages']['success'])) {
    echo showmsg($GLOBALS['flash_messages']['success'], 'success', $path);
}
?>

    <form method="post" enctype="multipart/form-data" class="style" id="productImportForm">
        <h2>Import Medications</h2>
        <p>One Medications per line in first column. No need for column titles</p>
        <fieldset>
            <div class="row">
                <label for="select_file">File selection</label>
                <input type="file" name="import" />
            </div>
            <div class="row">
                <input type="hidden" name="action" value="import_medications"/>
                <input type="submit" value="Import"/>
            </div>
        </fieldset>
    </form>

<?php
if ($totalnumrows > 0) {

    require $path . 'core/admin/templates/pagination.php';
    ?>
    <table class="manage-items">
        <tr>
            <th>Medication name</th>
        </tr>
        <tbody class="tabular">
        <?php
        foreach ($medications as $medication) {
            ?>
            <tr>
                <td><?= clean_page($medication->name); ?></td>
            </tr>
            <?php
        }
        ?>
        </tbody>
    </table>
    <?php
    require $path . 'core/admin/templates/pagination.php';
} else {
?>
    <p>There are no Medications added</p>
<?php
}
?>
<?php

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