<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Option;
use Illuminate\Support\Facades\Storage;
use Image;

class OptionsController extends Controller
{
    public function index()
    {
        foreach(config('cms.options') as $key => $group) {
            $output[] = (object)[
                'key' => $key,
                'name' => $group,
                'options' => Option::where('group', $key)->orderBy('order')->get()
            ];
        }

        return view('backend.options.index', [
            'output' => $output
        ]);
    }


    public function update(Request $request)
    {
        try {
            foreach($request->except('_token') as $key => $value) {
                Option::where('name', $key)->update(['value' => $value]);
            }

            foreach($request->file() as $key => $file) {
                $path = $file->hashName();
                $image = Image::make($file)->resize(1920, null, function($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                });
                Storage::put($path, $image->encode());

                $url = Storage::url($path);
                Option::where('name', $key)->update(['value' => $url]);
            }

            return back()->with('status', 'Las opciones han sido actualizadas');
        } catch(\Exception $e) {
            return back()->withInput()->withErrors($e->getMessage());
        }
    }

    public function order(Request $request)
    {
        foreach($request->post as $key => $id) {
            Option::where('id', $id)->update([
                'order' => $key
            ]);
        }
    }
}
