<?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;
use CmsHelper;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;

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);

        // IMPORTANT: field name must be "filename" and form must be multipart
        $uploadedFile = $request->file('filename');

        if ($uploadedFile && $uploadedFile->isValid()) {
            $tmpPath      = $uploadedFile->getRealPath();
            $originalName = $uploadedFile->getClientOriginalName();

            if (!CmsHelper::isFileMimeValid('', $tmpPath, $originalName, true)) {
                Session::flash('form_errors', ['type' => 'error', 'content' => 'Invalid file type uploaded.']);
                return back()->withInput();
            }

            $webpFile = webpImage($tmpPath);
            if ($webpFile) {
                $filepath = $icon->storeFile($webpFile);
                $icon->filepath = $filepath;
            } else {
                // Fallback: store original if conversion fails
                $filepath = $icon->storeFile($uploadedFile);
                $icon->filepath = $filepath;
            }
        }

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

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


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

        $fileName = ltrim((string) $icon->filepath, '/'); // e.g. "assetgallery/icons/foo.png"
        $webpFile = pathinfo($fileName, PATHINFO_EXTENSION)
            ? preg_replace('/\.[^.]+$/', '.webp', $fileName)
            : null;

        $disk = Storage::disk('uploads');

        if ($disk->exists($fileName)) {
            $disk->delete(array_values(array_filter([$webpFile, $fileName])));
        }

        $icon->delete();

        return 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;
    }

}
