<?php

namespace App\Http\Controllers\User;

use Request;
use Response;
use Validator;
use App\Services\Util;
use App\Models\PromotionUser;
use App\Services\UserService;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Repositories\UserPromotionRepository;

class PromotionController extends Controller
{
    protected $promoRepo;

    public function __construct(UserPromotionRepository $promoRepo)
    {
        $this->middleware('active.account');
        $this->promoRepo = $promoRepo;

    }

    public function index()
    {
        $data = [
            'values' =>  PromotionUser::where('user_id', Auth::user()->id)->whereNull('user_deleted_at')->get(),
        ];
        return view('user.promotion.index', $data);
    }

    public function detail($id){

        $user_promotion = PromotionUser::findOrFail($id);
        if($user_promotion->user_id != Auth::user()->id){
            abort(404);
        }

        $user_promotion->description = $user_promotion->description ? $user_promotion->description : $user_promotion->promotion_admin->user_description;
        $about_you = $user_promotion->user->account->about_you ?$user_promotion->user->account->about_you : $user_promotion->promotion_admin->user_about;
        $user_promotion->about_you = $user_promotion->about_you ? $user_promotion->about_you : $about_you;
        $data = [
            'checkPaymentCredit' => $user_promotion->checkPaymentCredit(),
            'user_promotion_cart' => PromotionUser::preCalculateCart($user_promotion, 'user_promotion'),
            'user_promotion' => $user_promotion,
        ];
        return view('user.promotion.detail', $data);
    }

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

        if(isset($data['action']) && $data['action'] === 'new-user-promotion'){
            $model = $this->promoRepo->create(Request::all());
            \Session()->flash('alert-save', true);
        }

        if(isset($data['action']) && $data['action'] === 'save-user-promotion'){
            $rules = array(
                'name' => 'required',
                'user_promotion_url' => ' required|alpha_dash|'.'unique:promotion_users,url,'.$id.',id'.'|min:4|max:20|full_word_check', 
            );
            Validator::extend('full_word_check', function ($attribute, $value, $parameters, $validator) {
                $profanity = \App\Models\Setting::getContentBySlug('promotion_user_url_profanity');
                $profanity = array_map('trim', explode(',', $profanity));
                if(in_array($value, $profanity)){
                    return false;
                }
                return true;
            });
            $validator = Validator::make(Request::all(), $rules);
            if ($validator->fails()) {
                return redirect(route('user_promotion_detail', [$id]))->withErrors($validator)->withInput(Request::all());
            }
            $model = $this->promoRepo->update($id, Request::all());
        }
        \Session()->flash('alert-save', true);
        return redirect(route('user_promotion_detail', [$model->id]));
    }

    public function delete($id, $del = false)
    {
     
       if($del === 'user_promotion'){
            $PromotionUser = PromotionUser::findOrFail($id);
            if($PromotionUser->canDelete()){
                $PromotionUser->user_deleted_at = now();
                $PromotionUser->save();
                \Session()->flash('alert-success', "Promotion gelöscht");
            }else{
                \Session()->flash('alert-error', "Promotion kann nicht gelöscht werden, schon in Verwendung.");
            }
            return redirect(route('user_promotions'));

       }
    }

    public function load(){
        $data = Request::all();
        if(Request::ajax()) {
            if(isset($data['action']) && $data['action'] === 'validate_url'){
                $unique = 'unique:promotion_users,url';
                if(isset($data['puid'])){
                    $unique .= ','.$data['puid'].',id';
                }
                $rules = array(
                    'user_promotion_url' => ' required|alpha_dash|'.$unique.'|min:4|max:20|full_word_check', 
                );
                Validator::extend('full_word_check', function ($attribute, $value, $parameters, $validator) {
                    $profanity = \App\Models\Setting::getContentBySlug('promotion_user_url_profanity');
                    $profanity = array_map('trim', explode(',', $profanity));
                    if(in_array($value, $profanity)){
                        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_promotion_url'));
                $name = Util::sanitize(Request::get('user_promotion_url'), true, false, true, true);
            
                return Response::json(array(
                    'success' => true,
                    'preview_user_promotion_url' => config('app.promo_url')."/".$name,
                ));
            }
            if(isset($data['action']) && $data['action'] === 'updateCart'){
               
                $fill = [
                    'user_promotion_cart' => ['price' => 0, 'price_net' => 0],
                ];
                
                if(isset($data['products'])){
                    $fill['user_promotion_cart'] = PromotionUser::preCalculateCart($data['products'], 'products');
                    $fill['checkPaymentCredit'] = PromotionUser::preCheckPaymentCredit($fill['user_promotion_cart'], Auth::user());

                }
                /*if(isset($data['user_promotion_id']) && $user_promotion = PromotionUser::find($data['user_promotion_id'])){
                }*/
                $html_cart =  view("user.promotion.cart", $fill)->render();
                return response()->json(['response' =>  true, 'data'=>$data, 'html_cart'=>$html_cart]);
            }
            return response()->json(['success' => false, 'data'=>$data]);
        }   
     }

    

}