<?php

use Mtc\Cms\Models\Page as CmsPage;
use MtcPharmacy\Multisite\Classes\MultisiteConstants;
use MtcPharmacy\Multisite\Classes\MultisiteSite;
use App\MultisiteHelper;


$cms_root_path = "../../";
require_once $cms_root_path . "includes/compatibility_includer.php";

$page_meta['title'] = 'Import/Export';
$errors = [];


if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'export_cms_pages__multisite') {
    MultisiteHelper::export(
        MultisiteConstants::ENTITY_TYPE_CMS_PAGE,
        $_REQUEST
    );
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'import_cms_pages') {
    $response = MultisiteHelper::import(
        MultisiteConstants::ENTITY_TYPE_CMS_PAGE,
        $_REQUEST
    );
    if (! $response['errors']) {
        $query_params = $_GET;
        $query_params['success'] = 'import_successful';
        $_SESSION['flash_messages']['success'] = $response['success'];
        header('Location: /cms/admin/content_manager/import_export.php?' . http_build_query($query_params));
        exit;
    } else {
        $errors = $response['errors'];
    }
}

require_once $core_root_path . "admin/templates/adminheader.html.php";

?>

<ul class="breadcrumbs el">
    <li><a title="Home" href="/admin/">Home</a>&nbsp;/&nbsp;</li>
    <li title="Content Manager" class="end">Content Manager</li>
</ul>

<h1><?= $page_meta['title'] ?></h1>

<ul class="tabnav el">
    <li class="selected">
        <a href="">
            CMS pages
        </a>
    </li>
</ul>


<?php

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

if ($errors) {
    $error_message = implode('<br />', $errors);
    echo showmsg($error_message, 'error', $path);
}

?>


<form method="post" class="style">
    <h2>Export (multisite)</h2>

    <div class="row">
        <input type="hidden" name="action" value="export_cms_pages__multisite"/>
        <?php foreach (MultisiteSite::all() as $site_data): ?>
            <button
                type="submit"
                name="multisite__site_id"
                value="<?= $site_data->id ?>"
                class="btn"
            >
                <?= $site_data->name ?>
            </button>
        <?php endforeach ?>
    </div>
</form>

<form method="post" enctype="multipart/form-data" class="style">
    <h2>Import</h2>
    <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_cms_pages"/>
            <button
                type="submit"
                class="btn"
            >
                Import
            </button>
        </div>
    </fieldset>
</form>


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