<?php
/**
 * Static Block Edit page
 *
 * @category Plugins
 * @package  Mtc_Static_Blocks
 * @author   mtc. Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
 */
namespace Mtc\Plugins\StaticBlocks\Classes;

use Util;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
$page['title'] = 'Edit Static Block';
$allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];


init_request_values([
    'url' => [],
    'tinymce' => [],
]);


if (!empty($_REQUEST['id']) && $_REQUEST['id'] > 0) {
    $add_edit = 'Edit';
    $block = StaticBlocks::find($_REQUEST['id']);
    $block_id = (int) $_REQUEST['id'];
} else {
    $add_edit = 'Add';
    $block = new StaticBlocks();
    $block_id = '';
}

$errors = [];

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'update') {
    if (empty(trim($_REQUEST['name']))) {
        $errors['name'] = 'Block name is required';
    }
    foreach ($_REQUEST['url'] as $url) {
        if (!empty($url)) {
            //Isn't a local url that starts with slash or domain independent url
            if (strpos($url, '/') === false
                && strpos($url, 'http') !== 0
            ) {
                $errors['url'] = 'Not a valid URL';
            }
        }
    }

    if (empty($errors)) {
        if (!empty($_REQUEST['name'])) {
            $block->name = trim($_REQUEST['name']);
        }
        if (!empty($_REQUEST['type'])) {
            $block->type = trim($_REQUEST['type']);
        }
        if (isset($_REQUEST['published']) && $_REQUEST['published'] == 1) {
            $block->published = 1;
        } else {
            $block->published = 0;
        }
        $block->save();

        $file_keys = array_keys($_FILES);

        foreach ($_REQUEST['tinymce'] as $instance_id => $instance) {
            $exists = StaticBlocksInstances::where('id', $instance_id)
                ->where('static_block_id', $block->id)
                ->first();

            // Remove instance if it is defined
            if (!empty($_REQUEST['remove'][$instance_id])) {
                if ($exists) {
                    $exists->delete();
                }
                continue;
            }

            if ($block->type == 'tinymce' && !empty($_REQUEST['tinymce'])) {
                if ($exists) {
                    $exists->content = trim($instance);
                    $exists->save();
                } else {
                    StaticBlocksInstances::create([
                        'content' => trim($instance),
                        'static_block_id' => $block->id
                    ]);
                }

            } elseif ($block->type == 'text' && !empty($_REQUEST['content'])) {
                if ($exists) {
                    $exists->content = trim($_REQUEST['content'][$instance_id]);
                    $exists->save();
                } else {
                    StaticBlocksInstances::create([
                        'content' => trim($_REQUEST['content'][$instance_id]),
                        'static_block_id' => $block->id
                    ]);
                }

            } elseif ($block->type == 'image') {
                $data = [];
                if (!empty($_REQUEST['url'][$instance_id])) {
                    $data['url'] = trim($_REQUEST['url'][$instance_id]);
                }
                if (!empty($_REQUEST['size'][$instance_id])) {
                    $data['size'] = trim($_REQUEST['size'][$instance_id]);
                }
                if (!empty($_REQUEST['alt_text'][$instance_id])) {
                    $data['alt_text'] = trim($_REQUEST['alt_text'][$instance_id]);
                }

                if (!empty($file_keys)) {
                    $file = array_shift($file_keys);
                    if (!empty($_FILES[$file]) && $_FILES[$file]['size'] > 0) {
                        $ext = pathinfo($_FILES[$file]['name'], PATHINFO_EXTENSION);

                        if (!in_array(strtolower($ext), $allowed_ext)) {
                            $errors['userfile'] = 'Only ' . implode(', ', $allowed_ext) . ' file types are allowed';
                        } else {
                            if ($file_data = upload_image($file, StaticBlockSizes::uploadSizes())) {
                                if (!empty($file_data['error'])) {
                                    $errors[] = $file_data['error'];
                                } else {
                                    $data['image'] = $file_data['name'];
                                }
                            }
                        }
                    }
                }

                if ($exists) {
                    $exists->fill($data);
                    $exists->save();
                } else {
                    $data['static_block_id'] = $block->id;
                    StaticBlocksInstances::create($data);
                }

                if (!empty($_REQUEST['delete_image'][$instance_id])) {
                    if ($exists && !empty($exists->image)) {
                        foreach (StaticBlockSizes::uploadSizes() as $folder) {
                            unlink(SITE_PATH . '/'.$folder['path'].'/' . $exists->image);
                        }
                        $exists->image = '';
                        $exists->save();
                    }
                }
            }
        }
        if ($add_edit == "Add") {
            header('Location: /plugins/StaticBlocks/admin/edit.php?id=' . $block->id);
            exit;
        }
    }
}

$block_sizes = StaticBlockSizes::all();

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="/plugins/StaticBlocks/admin">Manage Blocks</a> /</li>
    <li class="end"><?= clean_page($add_edit) ?> Block</li>
</ul>

<h1><?= clean_page($add_edit) ?> Block</h1>

<?php
$is_admin = true;
require 'tabnav.php';

if (sizeof($errors) > 0) {
    showerrors($errors);
}
if ((sizeof($errors) == 0 && isset($_REQUEST['action'])) ||
    (!empty($_REQUEST['confirm']) && $_REQUEST['confirm'] == 'added')) {
    echo showmsg("Block updated", "success", $path);
}

$form_action = '';
if (isset($_REQUEST['id'])) {
    $form_action .= Util::add_query_arg(['id' => $_REQUEST['id']]);
}

?>
    <form action="<?= $form_action ?>"
          method="post"
          class="style manageStaticBlock"
          enctype="multipart/form-data">
        <fieldset class="show">
            <h1>
                <a class="show el">
                    Block Information
                    <i class="icon-caret-right"></i>
                </a>
            </h1>
            <div class="row">
                <label for="name">Name</label>
                <input type="text" name="name" id="name" value="<?= clean_page($block->name);?>">
            </div>
            <div class="row checkboxes">
                <label class="master">Published</label>
                <?php
                $checked = '';
                if ($block->published==1) {
                    $checked = "checked='checked'";
                }
                ?>
                <input type="radio" name="published" id="published_yes" value="1" <?= clean_page($checked) ?>/>
                <label for="published_yes">Yes</label>
                <?php
                $checked = '';
                if ($block->published==0) {
                    $checked = "checked='checked'";
                }
                ?>
                <input type="radio" name="published" id="published_no" value="0" <?= clean_page($checked) ?>/>
                <label for="published_no">No</label>
            </div>
                <div class="row">
                    <label for="type">Type</label>
                    <select name="type" id="type">
                        <?php
                        $selected = '';
                        if ($block->type == 'tinymce') {
                            $selected = 'selected="selected"';
                        }
                        ?>
                        <option value="tinymce" <?= clean_page($selected) ?>>Text Area</option>
                        <?php
                        $selected = '';
                        if ($block->type == 'text') {
                            $selected = 'selected="selected"';
                        }
                        ?>
                        <option value="text" <?= clean_page($selected) ?>>Script Area</option>
                        <?php if ($block->type == 'image') {
                            $selected = 'selected="selected"';
                        } else {
                            $selected = '';
                        } ?>
                        <option value="image" <?= clean_page($selected) ?>>Image</option>
                    </select>
                </div>
            <div class="dynamic_content">
                <?php
                $instances = $block->content()->get();
                foreach ($instances as $instance) {
                    include 'templates/content.php';
                }
                if (count($instances) == 0) {
                    $instance = $block;
                    include 'templates/content.php';
                }
                ?>
            </div>
            <?php
            if (STATIC_BLOCKS_INSTANCE_COUNT > 1) {
                ?>
                <div class="row">
                    <a class="js_addNewInstance btn">
                        Add Another One
                    </a>
                </div>
                <?php
            }
            ?>
         </fieldset>

        <div class="row">
            <input type="hidden" id="js_max_block_count" value="<?= STATIC_BLOCKS_INSTANCE_COUNT ?>"/>
            <input type="hidden" name="action" value="update"/>
            <input type="hidden" name="id" value="<?= clean_page($block_id); ?>"/>
            <input type="submit" value="Save"/>
        </div>
    </form>
<?php require_once $path . 'core/admin/templates/adminfooter.html.php';
