<?php

namespace App\Repositories;

use App\User;
use App\Services\Util;
use App\Models\UserShop;
use App\Models\PromotionUserProduct;
use Illuminate\Support\Facades\Auth;
use App\Models\PromotionAdminProduct;

class UserShopRepository extends BaseRepository {


    public function __construct(UserShop $model){

        $this->model = $model;
    }

    public function update($id, $data)
    {

        $data['active'] = isset($data['active']) ? 1 : 0;
        $data['pick_up'] = isset($data['pick_up']) ? 1 : 0;
        $data['url'] = Util::sanitize($data['user_shop_url'], true, false, true, true);
        
        $this->model = $this->getById($id);
        $this->model->fill($data);
        $this->model->save();

        return $this->model;
    }
    
    public function create(User $user){

        $user_name = $user->getFullName(false);
        $url = Util::sanitize($user_name, true, false, true, true);
        $url = $this->makeUniqueURL($url);
        UserShop::create([
            'user_id' => $user->id,
            'url' => $url,
            'name' => __('shop.greetings')." ".$user_name,
            'description' => __('shop.default_description'),
            'about_you' => $user->account->about_you,
            'user_address' => Auth::user()->getFullAddress()."\n".__('shop.default_user_open'),
            'pick_up' => false,
            'active' => true,
            'active_date' => now(),
              
        ]);
        return User::find($user->id);
    }

    public function makeUniqueURL($url){

        $bool = true;
        $count = 1;
        $unique_url = $url;
        while($bool){
            if(UserShop::where('url', $unique_url)->count()){
                $unique_url = $url."_".$count;
                $count ++;
            }else{
                $bool = false;
            }
        }
        return $unique_url;
    }


}