<?php

namespace Mtc\Cms\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mtc\Cms\Models\AssetGalleryIcon;
use Illuminate\Support\Facades\Session;


class AssetGalleryController extends \App\Http\Controllers\Controller
{

    public function icons_manage()
    {
        $icons = AssetGalleryIcon::query()
            ->get()
        ;

        return template('admin/asset_gallery/icons_manage.twig', [
            'selected_tab' => 'manage',
            'title' => 'Icons',
            'icons' => $icons,
        ]);
    }


    public function icon_edit(Request $request, $icon_id)
    {
        $icon = AssetGalleryIcon::findOrFail($icon_id);

        $messages = $this->getFormMessages();

        return template('admin/asset_gallery/icon_edit.twig', [
            'selected_tab' => 'edit',
            'title' => 'Edit',
            'icon' => $icon,
            'messages' => $messages,
        ]);
    }


    public function icon_upsert(Request $request, $icon_id = null)
    {
        if (! $icon_id) {
            $new_icon = AssetGalleryIcon::create();

            return redirect()->route('admin-assetgallery-icons-edit', [ $new_icon->id ]);
        }

        $icon = AssetGalleryIcon::findOrFail($icon_id);

        $filepath = $icon->storeFile($request->file('filename'));

        $icon->label = $request->input('label');
        $icon->filepath = $filepath;
        $icon->save();

        Session::flash('success_message', [ 'type' => 'success', 'content' => 'Saved.' ]);

        return redirect()->back();
    }


    public function icon_delete(Request $request, $icon_id)
    {
        $icon = AssetGalleryIcon::findOrFail($icon_id);
        $icon->delete();

        return redirect()->back();
    }


    private function getFormMessages()
    {
        $messages = [];

        if ($success_message = Session::pull('success_message')) {
            $messages[] = $success_message;
        }

        if ($form_errors = Session::pull('form_errors')) {
            $messages[] = ['type' => 'error', 'content' => 'Something went wrong!'];
        }

        return $messages;
    }

}
