<?php

use Mtc\Cms\Models\Page as CmsPage;


$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') {
    $rows = CmsPage::query()
        ->addSelect(CmsPage::getExportableFields())
        ->get()
        ->toArray();
    $csv = array_to_csv($rows);
    \Util::force_download('cms_pages__' . date('Ymd_His') . '.csv', $csv);
    exit;
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'import_cms_pages') {
    $result = validate_csv_upload('import');
    $update_log = ['updated' => [], 'failed' => [], 'not_found' => [], 'skipped' => []];
    $response = ['errors' => $result['errors'], 'success' => ''];

    if (! $result['errors']) {
        $first = true;
        $columns = [];
        while (($csv_data = fgetcsv($result['handle'], null, ',')) !== false) {
            if ($first) {
                $columns = $csv_data;
                $first = false;
                continue;
            }
            if (count($columns) !== count($csv_data)) {
                $update_log['skipped'][] = $csv_data[0] ?? '(empty row)';
                continue;
            }
            $data = array_combine($columns, $csv_data);
            if (empty($data['id'])) {
                $update_log['skipped'][] = '(missing id)';
                continue;
            }
            $page = CmsPage::find($data['id']);
            if ($page) {
                $page->fill($data);
                if ($page->save()) {
                    $update_log['updated'][] = $page->id;
                } else {
                    $update_log['failed'][] = $page->id;
                }
            } else {
                $update_log['not_found'][] = $data['id'];
            }
        }

        $msg = 'Updated ' . count($update_log['updated']) . ' records.<br />';
        if ($update_log['failed']) {
            $msg .= 'Could not update the following records: ' . implode(', ', $update_log['failed']) . '.<br />';
        }
        if ($update_log['not_found']) {
            $msg .= 'Could not find the following records: ' . implode(', ', $update_log['not_found']) . '.<br />';
        }
        if ($update_log['skipped']) {
            $msg .= 'Skipped ' . count($update_log['skipped']) . ' malformed rows.<br />';
        }
        $response['success'] = $msg;
    }

    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</h2>

    <div class="row">
        <input type="hidden" name="action" value="export_cms_pages"/>
        <button type="submit" class="btn">Export</button>
    </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'; ?>
