<?php namespace Tps\Birzha\Components;

use Cms\Classes\ComponentBase;
use Input;
use October\Rain\Support\Facades\Event;
use Validator;
use Tps\Birzha\Models\Measure;
use Tps\Birzha\Models\Term;
use Tps\Birzha\Models\Currency;
use Tps\Birzha\Models\Product;
use Tps\Birzha\Models\Category;
use Tps\Birzha\Models\Country;
use Tps\Birzha\Models\City;
use TPS\Birzha\Models\Settings;
use Flash;
use Str;
use ValidationException;
use Carbon\Carbon;
use RainLab\User\Facades\Auth;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;


class OfferForm extends ComponentBase
{
    /**
     * @var string A collection of categories in dropdown
     */
    public $categories;
    public $subcategories;

    /**
     * @var string A collection of countries in dropdown
     */
    public $states;
    public $cities;

    /**
     * @var string A string with product id
     */
    public $productIdOption;

    /**
     * @var string A product which is being edited
     */
    public $productForEditing;

    public function componentDetails() {
        return [
            'name' => 'Offer Form',
            'description' => 'Add offer'
        ];
    }

    public function defineProperties() {
        return [
            'productId' => [
                'title' => 'Edit post :id',
                'description' => 'Edit post :id',
                'type' => 'string',
                'default' => ''
            ],
        ];
    }

    
    public function onSave(){
        $data = post();
        $rules = [
            'name' => 'required',
            'price' => 'required|numeric',
            'state_id' => 'required',
            'stock' => 'required|numeric|min:0|max:1',
            'description' => 'required',
            'new_img' => 'array|required',
            // 'is_file' => 'required',
            'new_img.*' => 'mimes:jpg,png',
            'category_id' => [
                'required',
                'exists:tps_birzha_categories,id',
                function ($attribute, $value, $fail) {
                    $c = Category::find($value);
                    if($c) {
                        if($c->status != 1) $fail(":attribute is non-active!");
                    }
                }
            ],
        ];

        $this->validateForm($data, $rules);
        
        
        if(!$data['new_img']) {
            Flash::error('Required at least one new');
        }

        $category = null;
        $keyword = $data['name'];
        if(isset($data["subcategory_id"]) && $data["subcategory_id"] != 'null'){
            $category = Category::find($data['subcategory_id']);
        }else{
            $category = Category::find($data['category_id']);
        }
        
        $keyword = $keyword.' '.$category->name.' '.$category->slug;
        if($category->primary_key > 0){
          $keyword = $keyword.' '.$category->parent->name.' '.$category->parent->slug;
              if($category->parent->primary_key > 0){
                  $keyword = $keyword.' '.$category->parent->parent->name.' '.$category->parent->parent->slug;
              }
        }

        
        $place = null;
        if(isset($data["city_id"]) && $data["city_id"] != 'null'){
            $place = $data['city_id'];
        }else{
            $place = $data['state_id'];
        }
        
        $product = new Product;
        $product->name = $data['name'];
        $product->description = $data['description'];
        $product->short_description = $data['short_description'];
        $product->slug = \Str::slug($data['name'],'-');
        $product->status = 'new';
        $product->place_id = $place;
        $product->price = $data['price'];
        $product->phone = $data['phone'];
        $product->is_file_product = $data['is_file'];
        $product->stock = $data['stock'];
        $product->keyword = $keyword;
        $product->created_at = Carbon::now();
        $product->updated_at = Carbon::now();
        
        if($data['is_file'] == 1){
            if(!$data['new_file']) {
                return Flash::error('Required at least one new');
            }
            if($data['new_file']) {
                $rules = [
                    'new_file' => 'required'
                ];
            }
            try {
            
                foreach($data['new_file'] ?? [] as $key => $fileq) {
                   $product->files = $fileq;
                   $product->save();
                }
            } catch(\Throwable $e) {
                return Flash::error('Something went');
            }
            
        }

        $user = Auth::user();
        $product->vendor_id = $user->id;
        $product->ends_at = null;
         try {
            foreach($data['new_img'] ?? [] as $key => $img) {
               $product->images = $img;
               $product->save();
            }
        } catch(\Throwable $e) {
            Flash::error('something went wrong');
        }
        if(!isset($data['productForEditing'])) {
            $category->products()->save($product);
        } else {
            $product->categories()->detach();
            $category->products()->save($product);
        }
        $product->save();
        Flash::success('Haryt goşuldy');
        return [
            '#mainDiv' => $this->renderPartial('@success')
        ];
    }


    public function onUpdate(){
        $data = post();
        $rules = [
            'name' => 'required',
            'price' => 'required|numeric',
            'state_id' => 'required',
            'stock' => 'required|numeric|min:0|max:1',
            'description' => 'required',
            'new_img' => 'array',
            // 'is_file' => 'required',
            'new_img.*' => 'mimes:jpg,png',
            'category_id' => [
                'required',
                'exists:tps_birzha_categories,id',
                function ($attribute, $value, $fail) {
                    $c = Category::find($value);
                    if($c) {
                        if($c->status != 1) $fail(":attribute is non-active!");
                    }
                }
            ],
        ];

        $this->validateForm($data, $rules);
        
        $category = null;
        if($data["subcategory_id"] != 'null'){
            $category = Category::find($data['subcategory_id']);
        }else{
            $category = Category::find($data['category_id']);
        }

        $product = Product::where("vendor_id", \Auth::user()->id)->where("id", $data['product_id'])->first();
        if(!$product){
            Flash::error('Haryt tapylmady');
        }
        
        $keyword = $data["name"];
        
        $keyword = $keyword.' '.$category->name.' '.$category->slug;
        if($category->primary_key > 0){
          $keyword = $keyword.' '.$category->parent->name.' '.$category->parent->slug;
              if($category->parent->primary_key > 0){
                  $keyword = $keyword.' '.$category->parent->parent->name.' '.$category->parent->parent->slug;
              }
        }
        
        
        $product->name = $data['name'];
        $product->description = $data['description'];
        $product->short_description = $data['short_description'];
        $product->slug = \Str::slug($data['name'],'-');
        $product->status = 'new';
        $product->place_id = $data['city_id'] == 'null' ? $data['state_id'] : $data['city_id'];
        $product->price = $data['price'];
        $product->phone = $data['phone'];
        $product->is_file_product = $data['is_file'];
        $product->stock = $data['stock'];
        $product->keyword = $keyword;
        $product->updated_at = Carbon::now();

        if(isset($data['new_file'])){
            foreach($product->files as $file){
                $file->delete();
            }
            foreach($data['new_file'] ?? [] as $key => $fileq) {
                $product->files = $fileq;
                $product->save();
            }
        }

        if(isset($data['new_img'])){
            //foreach($product->images as $image){
            //    $image->delete();
            //}
            foreach($data['new_img'] ?? [] as $key => $img) {
                $product->images = $img;
                $product->save();
             }
        }
        
        $user = Auth::user();
        $product->vendor_id = $user->id;
        $product->ends_at = null;

        if(!isset($data['product_id'])) {
            $category->products()->save($product);
        } else {
            $product->categories()->detach();
            $category->products()->save($product);
        }
        $product->save();
        Flash::success('Haryt maglumaty üýtgedildi. Tassyklanýança garaşmagyňyzy haýyş edýäris.');
        return [
            '#mainDiv' => $this->renderPartial('@editSuccess')
        ];
    }

    // step 2
    public function onOfferFill() {
        $data = input();

        $rules = [
            'quantity' => 'required|numeric',
            'price' => 'required|numeric|max:9999999',
            'place' => 'required',
            'description_tm' => 'required',
            'description_en' => 'required',
            'description_ru' => 'required',
            // 'ends_at' => 'required|date',
            'payment_term_id' => 'required',
            'packaging' => 'required',
            'delivery_term_id' => 'required',
            'currency_id' => 'required',
            'measure_id' => 'required',
            // 'new_img' => 'required'
        ];
        $this->validateForm($data, $rules);

        // validate if no old images and new images
        if(!isset($data['new_img']) && !isset($data['old_img'])) {
            throw new ValidationException(['no_images' => trans('validation.atleast_1_image')]);
        }

        // seaparate validation for file type
        $rules = [
            'new_img.*' => 'mimes:jpg,png'
        ];
        $this->validateFileType($data, $rules);

        // separate validation for image size
        $rules = [
            'new_img.*' => 'max:1024'
        ];
        $this->validateImageSize($data, $rules);

        $attachedProduct = Product::find($data['product_id']);

        $attachedProduct = $this->fillProduct($data,$attachedProduct);

        if(isset($data['new_img'])) {
            foreach($data['new_img'] as $key => $img) {
                $attachedProduct->images = $img;
                $attachedProduct->save();
            }
        }

        $this->page['fee'] = Settings::getValue('fee');
        $this->page['product'] = $attachedProduct;

        return [
            '#form-steps' => $this->renderPartial('@third_step_form')
        ];
    }

    // step3
    public function onPublish() {

        $product = Product::find(Input::get('product_id'));

        $balance = \Auth::user()->getBalance();

        if($balance - Settings::getValue('fee') < 0) {
            // ... message about not enough money
            Flash::error(trans('validation.low_balance'));

            $this->page['fee'] = Settings::getValue('fee');
            $this->page['product'] = $product;

            // redirect back to the third step
            return [
                '#form-steps' => $this->renderPartial('@third_step_form')
            ];

        } else {

            //save how much user payed because fee can be changed by admin tomorrow
            // if post is denied we get back payed fee, not admin's set fee
            $product->payed_fee_for_publ = Settings::getValue('fee');
            $product->status = 'new';

            if($product->save()){
                Event::fire('tps.product.received',[$product]);
                // Sets a successful message
                Flash::success(trans('validation.thanks_for_posting'));

                return \Redirect::to('my-posts');
            }
            else{
                Flash::error(trans('Product publish unsuccessfull'));
            }

        }
    }


    // after deleting a photo go the second form_step
    public function onImageDelete() {
        $product = Product::find(Input::get('product_id'));
        $product->images()->find(Input::get('product_image_id'))->delete();
        Flash::success('Surat üstünlikli pozuldy');
        return \Redirect::back();
    }

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

        if($validator->fails()) {
            throw new ValidationException(['new_img_type_error' => trans('validation.image_type', ['image_type' => 'jpg,png'])]);
        }
    }

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

        if($validator->fails()) {
            throw new ValidationException(['new_img_size_error' => trans('validation.image_size', ['size'=> 1])]);
        }
    }

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

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

    protected function fillProduct($data,$attachedProduct) {
        $attachedProduct->translateContext('tm');
        $attachedProduct->description = $data['description_tm'];
        // Sets a single translated attribute for a language
        $attachedProduct->setAttributeTranslated('description', $data['description_ru'], 'ru');
        $attachedProduct->setAttributeTranslated('description', $data['description_en'], 'en');
        $attachedProduct->quantity = $data['quantity'];
        $attachedProduct->price = $data['price'];
        $attachedProduct->measure_id = $data['measure_id'];
        $attachedProduct->payment_term_id = $data['payment_term_id'];
        $attachedProduct->delivery_term_id = $data['delivery_term_id'];
        $attachedProduct->packaging = $data['packaging'];
        $attachedProduct->place = $data['place'];
        $attachedProduct->currency_id = $data['currency_id'];
        // $attachedProduct->ends_at = $data['ends_at'];
        $attachedProduct->save();
        return $attachedProduct;
    }

    public function onRun() {
        $this->categories = Category::where('status',1)->where('primary_key', 0)->get();
        $this->subcategories = Category::where('primary_key','>', 0)->get();
        $this->states = City::where('primary_key','=', 0)->get();
        $this->cities = City::where('primary_key','>', 0)->get();
        $this->productIdOption = $this->property('productId');

        
        if($this->productIdOption) {
            $this->productForEditing = Product::where("vendor_id", \Auth::user()->id)->where("id", $this->productIdOption)->first();
            if(!$this->productForEditing){
                return \Redirect::to('/');
            }
        } else {
            $this->productForEditing = null;
        }
    }
    
    
    public function onGetCategorySubs(){
        
        $data = post();
        
        $subs = $this->getSubCatsq($data["mainCat"]);               
        
        $checkSubs = $this->checkSubs($subs);
        
           if($checkSubs == ''){
              $checkSubs = [];
           }
        
        $allCats = $subs + $checkSubs;
        
        
        $subCatsAll = Category::whereIn("id", $allCats)->orderBy("primary_key", "ASC")->get();
        
        return $subCatsAll;
        
    }
    
    
   protected function checkSubs($catIds){
        $data = '';
        $subCats = [];
        foreach ($catIds as $id){
            $subs = $this->getSubCatsq($id);
            if(count($subs) > 0){
                foreach($subs as $subId){
                    array_unshift($subCats, $subId);
                }
                array_unshift($subCats, $id);
                $data = $subCats;
            }
        }  
        return $data;
        
    }
    
    protected function getSubCatsq($catId){
        
        $categoriesCustoms = Category::where("primary_key", $catId)->select("id", "primary_key")->get()->pluck("id")->toArray();
        return $categoriesCustoms;
        
    }
    
    
//----------
    
    protected function checking($catIds){
        $data=[];
        foreach ($catIds as $id){
            
            $subs = $this->getSubCatsq($id);
                $data[] = $id;
            if(count($subs) > 0){
                $data[] = $subs;
            }
          
        }    
    }
    
  
    
    
    
    
}
