<?php namespace TPS\Birzha\Components;

use Cms\Classes\ComponentBase;
use TPS\Birzha\Models\Product;
use RainLab\User\Models\User;
use Flash;
use ValidationException;
use Validator;

class ShopSettings extends ComponentBase
{

    public $user;


    public function componentDetails()
    {
        return [
            'name'        => 'Shop settings',
            'description' => 'Shop settings'
        ];
    }



    public function onRun() {
        //$this->user = $this->loadShopSettings(); 
    }


    protected function loadShopSettings() {
        $user = User::find(\Auth::user()->id);
        return $user;
    }
    
    public function onDelete(){
        $user = User::find(\Auth::user()->id);
        $user->delete();
        Flash::success('Hasabyňyz pozuldy');
        return \Redirect::back();
    }


    public function onSave(){
        $data = post();
        $rules = [
            'vendorName' => 'required',
            'slogan' => 'required',
            'description' => 'required',
            'workTime' => 'required',
            'discount' => 'numeric'
        ];

        $this->validateForm($data, $rules);
        

        $user = User::find(\Auth::user()->id);
        $user->instagram = $data['instagram'];
        $user->tiktok = $data['tiktok'];
        $user->site = $data['website'];
        $user->shop_title = $data['vendorName'];
        $user->slogan = $data['slogan'];
        $user->short_description = $data['short_description'];
        $user->description = $data['description'];
        $user->work_time = $data['workTime'];
        $user->web2 = $data['discount'] ? number_format($data['discount'], 2, '.', '') : null;
        $user->save();

        Flash::success('Maglumatlar üýtgedildi');
        return \Redirect::back();
    }

    protected function validateForm($data, $rules) {
        $validator = Validator::make($data, $rules);

        if($validator->fails()) {
            throw new ValidationException($validator);
        }
    }

}