<?php


namespace App\Http\Controllers;
use App\Http\Controllers\Api\KasController;
use App\Http\Controllers\Api\KasSLLController;
use App\Models\UserShop;
use App\Models\UserShopOnSite;
use App\Repositories\UserRepository;
use Auth;
use Cviebrock\EloquentSluggable\Services\SlugService;
use Request;
use Response;
use Validator;


class UserShopController extends Controller
{
    protected $db;
    protected $userRepo;

    public function __construct(UserRepository $userRepo)
    {
        $this->middleware('active.shop');
        $this->userRepo = $userRepo;
    }

    public function index()
    {
        $user = Auth::user();
        if ($user->shop && !$user->shop->set_defaults) {
            if ($user->account) {
                $user->shop->title = $user->account->first_name . " " . $user->account->last_name;
            }
            if ($user->account) {
                $user->shop->contact = $this->generate_contact($user);
            } else {
                $user->shop->contact = "Deine Straße/Nr • Dein PLZ Ort\nFestnetz: Deine Festnetz-Nummer\nMobil: Deine Mobil-Nummer\nDeine E-Mail-Adresse";
            }

            $user->shop->accessibility = "Mo-Fr: 9.00 - 19.00 Uhr\nSa-So: 11.00 - 18.00 Uhr";

        }
        $data = [
            'user' => $user,
        ];
        return view('user.shop', $data);

    }

    public function store()
    {
        $user = Auth::user();
        $data = Request::all();

        if (!$user->shop) {
            abort(404);
        }
        $user->shop->title = $data['title'];
        $user->shop->contact = trim(preg_replace('/\s*\n+/',"\n", $data['contact']));
        $user->shop->accessibility = trim(preg_replace('/\s*\n+/',"\n", $data['accessibility']));
        $user->shop->about = trim(preg_replace('/\s+/', ' ',$data['about']));
        $user->shop->active = isset($data['active']) ? true : false;
        $user->shop->set_defaults = true;
        $user->shop->save();
        \Session()->flash('alert-save', true);

        return redirect(route('user_shop'));

    }

    private function generate_contact($user)
    {
        $ret = "";
        $sep = "\n";

        $ret = $user->account->street != "" ? $user->account->street : "Deine Straße/Nr";
        $ret .= " • ";
        $ret.= $user->account->postal_code != "" ? $user->account->postal_code." " : "Dein PLZ ";
        $ret.= $user->account->city != "" ? $user->account->city : "Dein Ort";
        $ret.= $sep;

        $pre = $user->account->pre_phone_id != "" ? $user->account->pre_phone->phone." " : "";
        $ret.= "Festnetz: ".($user->account->phone != "" ? $pre.$user->account->phone : "Deine Festnetz-Nummer");
        $ret.= $sep;

        $pre = $user->account->pre_mobil_id != "" ? $user->account->pre_mobil->phone." " : "";
        $ret.= "Mobil: ".($user->account->mobil != "" ? $pre.$user->account->mobil : "Deine Mobil-Nummer");
        $ret.= $sep;

        $ret.= $user->email;

        return $ret;

    }

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

    public function uploadImage(){

        $user = Auth::user();

        if(!$user->shop){
            abort(404);
        }

        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('user_shop'));
                }

                $ext = $file_ex[$image['output']['type']];
                // Original file name
                $name = $image['output']['name'];
                $name = \App\Services\Slim::sanitizeFileName($name);
                $name = uniqid() . '_' . $name;

                $data = \Storage::disk('public')->put(
                    'images/shop/'.$name,
                    $data
                );

                $user->shop->filename = $name;
                $user->shop->originalname = $image['output']['name'];
                $user->shop->ext = $ext;
                $user->shop->mine = $image['output']['type'];
                $user->shop->size = $image['input']['size'];
                $user->shop->save();



                \Session()->flash('alert-success', "Datei hochgeladen");
                return redirect(route('user_shop'));
            }
            \Session()->flash('alert-danger', "Datei leer");
            return redirect(route('user_shop'));

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

    public function deleteImage(){

        $user = Auth::user();

        if(!$user->shop){
            abort(404);
        }

        if($user->shop->filename){
            $file =  'images/shop/'.$user->shop->filename;
            \Storage::disk('public')->delete($file);

            $user->shop->filename = null;
            $user->shop->originalname = null;
            $user->shop->ext = null;
            $user->shop->mine = null;
            $user->shop->size = null;
            $user->shop->save();

            \Session()->flash('alert-success', "Datei gelöscht");
            return redirect(route('user_shop'));

        }
        \Session()->flash('alert-danger', "Datei nicht gefunden");
        return redirect(route('user_shop'));

    }

    public function uploadOnSiteImage(){

        $user = Auth::user();
        $user_shop_id = Request::get('user_shop_id');

        if(!$user->shop || $user->shop->id != $user_shop_id){
            abort(404);
        }

        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('user_shop'));
                }

                $ext = $file_ex[$image['output']['type']];
                // Original file name
                $name = $image['output']['name'];
                $name = \App\Services\Slim::sanitizeFileName($name);
                $name = uniqid() . '_' . $name;

                $data = \Storage::disk('public')->put(
                    'images/user_shop/'.$user->shop->id.'/'.$name,
                    $data
                );

                UserShopOnSite::create([
                    'user_shop_id' => $user->shop->id,
                    'filename' => $name,
                    'original_name' => $image['output']['name'],
                    'ext' => $ext,
                    'mine' => $image['output']['type'],
                    'size' => $image['input']['size']
                ]);

                \Session()->flash('alert-success', "Datei hochgeladen");
                return redirect(route('user_shop'));
            }
            \Session()->flash('alert-danger', "Datei leer");
            return redirect(route('user_shop'));

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

    public function deleteOnSiteImage($image_id, $user_shop_id){

        $user = Auth::user();
        if(!$user->shop || $user->shop->id != $user_shop_id){
            abort(404);
        }
        $image = UserShopOnSite::findOrFail($image_id);

        if($image->user_shop_id == $user_shop_id){
            $file =  'images/user_shop/'.$user_shop_id.'/'.$image->filename;
            \Storage::disk('public')->delete($file);

            $image->delete();

            \Session()->flash('alert-success', "Datei gelöscht");
            return redirect(route('user_shop'));

        }
        \Session()->flash('alert-danger', "Datei nicht gefunden");
        return redirect(route('user_shop'));

    }




    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function userShopRegisterForm(){


       if(Request::get('shop_submit') == 'check'){
           $rules = array(
               'user_shop_name' => ' required|alpha_dash|profanity|unique:user_shops,name|min:4|max:20|full_word_check',
           );
           Validator::extend('full_word_check', function ($attribute, $value, $parameters, $validator) {
               if(in_array($value, config('profanity.full_word_check'))){
                   return false;
               }
               return true;
           });
           $validator = Validator::make(Request::all(), $rules);

           if ($validator->fails()) {
               \Session()->flash('shop-name-error', 'error');
               return redirect()->back()->withErrors($validator)->withRequest();
           }
           \Session()->flash('shop-name-error', 'check');
           return redirect(route('user_shop'))->withRequest();
       }

       if(Request::get('shop_submit') == 'action') {

           $rules = array(
               'user_shop_name' => ' required|alpha_dash|profanity|unique:user_shops,name|min:4|max:20|full_word_check',
           );
           Validator::extend('full_word_check', function ($attribute, $value, $parameters, $validator) {
               if(in_array($value, config('profanity.full_word_check'))){
                   return false;
               }
               return true;
           });
           $validator = Validator::make(Request::all(), $rules);

           if ($validator->fails()) {
               \Session()->flash('shop-name-error', 'error');
           }else{
               \Session()->flash('shop-name-error', 'check');

           }

           $rules = array(
               'user_shop_active' => 'accepted',
           );
           $validator = Validator::make(Request::all(), $rules);
           if ($validator->fails()) {
               return redirect()->back()->withErrors($validator)->withRequest();
           }

           //all is right - save
           $user = Auth::user();
           $data = Request::all();

           $user_shop = UserShop::create([
                'user_id' => $user->id,
                'name' => $data['user_shop_name'],
                'active' => true,
                'active_date' => now(),
               ]
           );

           $ret = $this->userShopRegisterSubDomain($user_shop->slug);
           if($ret['success'] === true){
               \Session()->flash('alert-save', true);
           }else{
               $user_shop->forceDelete();
               \Session()->flash('alert-error', $ret['error']);
           }
           return redirect(route('user_shop'));
       }

    }


    public function userShopRegisterSubDomain($slug){

        $kas = new KasController();
        $domain = 'mivita.care';


        //check if exisist
        $subdomains = $kas->action('get_subdomains');
        foreach ($subdomains as $subdomain){
            $sub = str_replace(".".$domain, '', $subdomain['subdomain_name']);
            if($sub == $slug){
                 return ['success' => false, 'error' => 'Fehler: Subdomain existierts bereits, bitte einen neues Namen wählen'];
            }
        }
        //add
        $full_subdomain_name = $slug.".".$domain;
        $pra = array(
            'subdomain_name' => $slug,
            'domain_name' => $domain,
            'subdomain_path' => '/mein.mivita.care/public/',
            'php_version' => '7.3',
            //'ssl_proxy' => 'Y',
            //'redirect_status' => 0
        );
        $add_subdomain = $kas->action('add_subdomain', $pra);
        if($add_subdomain == $full_subdomain_name){
            return ['success' => true];
        }
        return ['success' => false, 'error' => $add_subdomain];
    }

        /**
     * @return string to ajax
     */
    public function checkUserShopName(){

            $rules = array(
                'user_shop_name' => ' required|alpha_dash|profanity|unique:user_shops,name|min:4|max:20|full_word_check',
            );
            Validator::extend('full_word_check', function ($attribute, $value, $parameters, $validator) {
                if(in_array($value, config('profanity.full_word_check'))){
                    return false;
                }
                return true;
            });

            $validator = Validator::make(Request::all(), $rules);

            if ($validator->fails()) {
                //$messages = $validator->messages();
                return Response::json(array(
                    'success' => false,
                    'errors' => $validator->getMessageBag()->toArray()

                ));
            }
        $slug = SlugService::createSlug(UserShop::class, 'slug', Request::get('user_shop_name'));

         return Response::json(array(
                'success' => true,
                'preview_user_shop_name' => "https://".$slug.".".config('app.domain').config('app.tld_care'),
            ));
    }

}