<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\IqImage;
use App\Models\ProductCategory;
use\Request;


class CategoryController extends Controller
{


    public function __construct()
    {
        $this->middleware('admin');
    }

    public function index()
    {

        $data = [
            'values' => Category::all(),
        ];
        return view('admin.category.index', $data);
    }

    public function edit($id)
    {
        if($id == "new"){
            $model = new Category();
            $model->active = true;
        }else{
            $model = Category::findOrFail($id);
        }
        $data = [
            'category' => $model,
            'trans' => array_keys(config('localization.supportedLocales')),

        ];
        return view('admin.category.edit', $data);
    }

    public function store()
    {

        $data = Request::all();
        $data['active'] = isset($data['active']) ? true : false;
        $data['parent_id'] = isset($data['parent_id']) ? $data['parent_id'] : null;
        if($data['id'] == "new"){
            $model = Category::create($data);
        }else{
            $model = Category::find($data['id']);
            $model->fill($data)->save();
        }

        $trans = [];
        if(!empty($data['trans_name'])){

            foreach ($data['trans_name'] as $lang => $value){
                if($value && $value != null){
                    $trans[$lang] = $value;
                }
            }
        }
        $model->trans_name = $trans;
        $model->save();

        $trans = [];
        if(!empty($data['trans_headline'])){
            foreach ($data['trans_headline'] as $lang => $value){
                if($value && $value != null){
                    $trans[$lang] = $value;
                }
            }
        }
        $model->trans_headline = $trans;
        $model->save();

        \Session()->flash('alert-save', '1');
        return redirect(route('admin_product_categories'));


    }


    public function delete($id){

        if(ProductCategory::where('category_id', $id)->count()){
            \Session()->flash('alert-error', 'Eintrag wird als Produkt-Kategorie verwendet');
            return redirect(route('admin_product_categories'));
        }
        if(Category::where('parent_id', $id)->count()){
            \Session()->flash('alert-error', 'Eintrag wird als Haup-Kategorie  verwendet');
            return redirect(route('admin_product_categories'));
        }
        $model = Category::findOrFail($id);
        $model->delete();
        \Session()->flash('alert-success', 'Eintrag gelöscht');
        return redirect(route('admin_product_categories'));
    }

    // Upload FILE  -----------------------------------------------------------------------------------------------------------------------

    public function imageUpload(){

        $category_id = Request::get('category_id');
        $category = Category::findOrFail($category_id);

        try {
            $image = \App\Services\Slim::getImages('images')[0];

            if ( isset($image['output']['data']) )
            {

                // Base64 of the image
                $data = $image['output']['data'];
                $file_ex = array( 'image/jpeg' => 'jpg', 'image/png' => 'png');

                if (!isset($file_ex[$image['output']['type']])) {
                    \Session()->flash('alert-danger', 'File is not jpg or png!');
                    return redirect(route('admin_product_edit', [$category->id]));
                }

                $ext = $file_ex[$image['output']['type']];
                // Original file name
                $name = $image['output']['name'];
                $name = \App\Services\Slim::sanitizeFileName($name);
                $path = 'images/iq_images/';

                $image_name = "";
                do {
                    $image_name = uniqid('', false) . '_' . $name;
                } while (\Storage::disk('public')->exists($path.$image_name));

                $data = \Storage::disk('public')->put(
                    $path.$image_name,
                    $data
                );

                $iq_image = IqImage::create([
                    'filename' => $image_name,
                    'original_name' => $image['output']['name'],
                    'ext' => $ext,
                    'mine' => $image['output']['type'],
                    'size' => $image['input']['size']
                ]);

                $category->headline_image_id = $iq_image->id;
                $category->save();

                \Session()->flash('alert-success', "Datei hochgeladen");
                return redirect(route('admin_product_category_edit', [$category->id]));
            }
            \Session()->flash('alert-danger', "Datei leer");
            return redirect(route('admin_product_category_edit', [$category->id]));

        }
        catch (Exception $e) {
            \Session()->flash('alert-danger', "Fehler".$e);
            return redirect(route('admin_product_category_edit', [$category->id]));
        }
    }

    public function imageDelete($image_id, $category_id){

        $category = Category::findOrFail($category_id);
        $iq_image = IqImage::findOrFail($image_id);

        if($iq_image->id == $category->iq_image->id){
            $file =  'images/iq_images/'.$iq_image->filename;
            \Storage::disk('public')->delete($file);
            $category->headline_image_id = NULL;
            $category->save();
            $iq_image->delete();


            \Session()->flash('alert-success', "Datei gelöscht");
            return redirect(route('admin_product_category_edit', [$category->id]));

        }
        \Session()->flash('alert-danger', "Datei nicht gefunden");
        return redirect(route('admin_product_category_edit', [$category->id]));

    }

    public function imageAttribute($image_id, $attr, $val = false){

        $iq_image = IqImage::findOrFail($image_id);

        $iq_image->{$attr} = $val;
        $iq_image->save();

        \Session()->flash('alert-success', "Wert gespeichert");
        return redirect()->back();

    }

}