<?php

namespace App\Http\Controllers;

use Image;
use OneSignal;
use Storage;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\User;
use App\iChambaParameter;
use App\Models\Suppliers;
use App\Models\Banks;
use App\Models\Categories;
use App\Models\Postulations;
use App\Models\CurrentContracts;
use Grimzy\LaravelMysqlSpatial\Types\Point;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;

class SupplierController extends Controller
{
    //
    public function index(Request $request)
    {
        //
        $request->session()->put('search', $request
              ->has('search') ? strip_tags($request->get('search')) : ($request->session()
              ->has('search') ? strip_tags($request->session()->get('search')) : ''));

        $request->session()->put('field', $request
                ->has('field') ? strip_tags($request->get('field')) : ($request->session()
                ->has('field') ? strip_tags($request->session()->get('field')) : 'id'));

        $request->session()->put('sort', $request
                ->has('sort') ? strip_tags($request->get('sort')) : ($request->session()
                ->has('sort') ? strip_tags($request->session()->get('sort')) : 'asc'));

        //$headers = $request->get('header') != '' ? $request->get('header') : -1;

        $suppliers = new Suppliers();
        $suppliers = $suppliers->where('id', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                              ->orwhere('user_id', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                              ->orwhere('company_name', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                              ->orwhere('tags', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                              ->orwhere('RFC', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                              ->orwhere('CURP', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                              ->orwhere('regimen', 'LIKE', '%' . strip_tags($request->session()->get('search')) . '%')
                        ->orderBy(strip_tags($request->session()->get('field')), strip_tags($request->session()->get('sort')))
                        ->paginate(10);

        if ($request->ajax()) {
            return view('supplier.index', compact('suppliers'));
          } else {
            return view('supplier.ajax', compact('suppliers'));
          }

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request, $id)
    {
        //
        $user = Auth::user();
        $banks = Banks::pluck('name', 'id');
        $disk = Storage::disk('gcs');
        $categories_check =  Suppliers::where('user_id', $id)->first();
        if (isset($categories_check)) {
          $categories_names = $categories_check->categories->pluck('name');
        }
        else {
          $categories_names = null;
        }

        if ($request->isMethod('get'))
        return view('supplier.form', ['supplier' => Suppliers::where('user_id', $id)->first()], compact('banks','categories_names'));


        $supplier = Suppliers::where('user_id', $id)->first();
        if ($supplier) {
          if ($supplier->location !=null) {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'nullable|string',
              'minimun_fee' => 'required|numeric',
              'address' => 'string',
              'lat' => 'numeric|nullable',
              'lng' => 'numeric|nullable',
              'references_options' => 'required|numeric',
              'references' => 'nullable|string',
            ];
            if (empty($request->RFC)) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'required|string',
                'CURP' => 'unique:suppliers|nullable|string|size:18',
                'RFC' => 'string|size:14|nullable',
                'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
                'bank' => 'required|numeric',
                'minimun_fee' => 'required|numeric',
                'taxes_id' => 'required|numeric',
                'address' => 'string',
                'lat' => 'numeric|nullable',
                'lng' => 'numeric|nullable',
              ];
            } else if (empty($request->CURP)) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'required|string',
                'CURP' => 'string|size:18|nullable',
                'RFC' => 'unique:suppliers|nullable|string|size:13',
                'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
                'bank' => 'required|numeric',
                'minimun_fee' => 'required|numeric',
                'taxes_id' => 'required|numeric',
                'address' => 'string',
                'lat' => 'numeric|nullable',
                'lng' => 'numeric|nullable',
              ];
            }
          }
        } else {
          $rules = [
            'company_name' => 'required|string',
            'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
            'categories' => 'required|string',
            'tags' => 'nullable|string',
            'minimun_fee' => 'required|numeric',
            'address' => 'required|string',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
            'references_options' => 'required|numeric',
            'references' => 'nullable|string',
          ];
          if (empty($request->RFC)) {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'required|mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'required|string',
              'CURP' => 'unique:suppliers|nullable|string|size:18',
              'RFC' => 'string|size:14|nullable',
              'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
              'bank' => 'required|numeric',
              'minimun_fee' => 'required|numeric',
              'taxes_id' => 'required|numeric',
              'address' => 'required|string',
              'lat' => 'required|numeric',
              'lng' => 'required|numeric',
            ];
          } else if (empty($request->CURP)) {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'required|mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'required|string',
              'CURP' => 'string|size:18|nullable',
              'RFC' => 'unique:suppliers|nullable|string|size:13',
              'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
              'bank' => 'required|numeric',
              'minimun_fee' => 'required|numeric',
              'taxes_id' => 'required|numeric',
              'address' => 'required|string',
              'lat' => 'required|numeric',
              'lng' => 'required|numeric',
            ];
          }
        }

        $messages = [
          'company_name.required' => 'Se requiere el nombre de la empresa',
          'cover_photo.required' => 'Se requiere una foto de portada',
          'categories.required' => 'Se requiere una categoría',
          'tags.required' => 'Se requiere un tag',
          'RFC.required' => 'Se requiere un RFC',
          'CURP.required' => 'Se requiere un CURP',
          'RFC.unique' => 'RFC ya registrado',
          'CURP.unique' => 'CURP ya registrado',
          'RFC.size' => 'RFC no valido',
          'CURP.size' => 'CURP no valido',
          'taxes_id.required' => 'Se requiere un regimen fiscal',
          'clabe.required' => 'Se requiere una CLABE interbancaria',
          'minimun_fee.required' => 'Se requiere un monto mínimo a cobrar',
          'address.required' => 'Se requiere una dirección',
          'lat.required' => 'Se requiere una dirección válida, si ya hay una dirección escrita, favor de volverla a escribir',
          'lng.required' => 'Se requiere una dirección válida, si ya hay una dirección escrita, favor de volverla a escribir',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
          return redirect()->back()->withInput($request->all())->withErrors($validator);
        }

        $supplier = Suppliers::where('user_id', $id)->first();

        if ($supplier) {
          $supplier->user_id = $id;
          $supplier->company_name = strip_tags($request->company_name);
          if ($request->hasFile('cover_photo')){
            $image = $request->file('cover_photo');
            $filepath = public_path('img/users/'.  $id);
            /*if (!File::exists($filepath)) {
              File::makeDirectory($filepath, 0775, true);
            }*/
            $filename = time() . '.' . $image->getClientOriginalExtension();
            //Image::make($image)->resize(720, 480)->save( public_path('img/users/' . $id . '/' . $filename ) );
            if ($supplier->cover_photo) {
              $disk->delete(str_replace('https://storage.googleapis.com/ichamba-1562349005909.appspot.com/', '', $supplier->cover_photo));
            }
            $disk->putFileAs('img/users/'.  $id . '/', $image, $filename, 'public');
            $supplier->cover_photo = $disk->url('img/users/'.  $id . '/' . $filename);
            $supplier->save();
          } else if(!$supplier->cover_photo) {
            $supplier->cover_photo = asset('img/users/banner.png');
          }
          $supplier->save();

          $supplier->tags = str_replace(",", ", ", strip_tags($request->tags));
          $categories = explode(",", strip_tags($request->categories));
          $supplier->categories()->sync(null);
          foreach ($categories as $category) {
            $dbcategory = Categories::where('name', $category)->first();
            if(isset($dbcategory)){
              $supplier->categories()->attach($dbcategory);
              $supplier->save();
            }
          }
           if ($request->RFC && $request->CURP) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          } else if ($request->CURP) {
            $supplier->CURP = strip_tags($request->CURP);
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          } else if ($request->RFC) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          }
          $supplier->clabe = strip_tags($request->clabe);
          $supplier->bank_id = $request->bank;
          $supplier->regimen = $request->taxes_id;

          $supplier->minimun_fee = 150;
          $supplier->address = strip_tags($request->address);
          if ($request->lat != null && $request->lng != null) {
            $point = new Point($request->lat, $request->lng);
            $supplier->location = $point;
          }
          $supplier->save();
        } else {
          $supplier = new Suppliers();
          $supplier->user_id = $id;
          $supplier->company_name = strip_tags($request->company_name);
          if ($request->hasFile('cover_photo')){
            $image = $request->file('cover_photo');
            $filepath = public_path('img/users/'.  $id);
            /*if (!File::exists($filepath)) {
              File::makeDirectory($filepath, 0775, true);
            }*/
            $filename = time() . '.' . $image->getClientOriginalExtension();
            //Image::make($image)->resize(720, 480)->save( public_path('img/users/' . $id . '/' . $filename ) );
            $disk->putFileAs('img/users/'.  $id . '/', $image, $filename, 'public');
            $supplier->cover_photo = $disk->url('img/users/'.  $id . '/' . $filename);
            $supplier->save();
          } else if(!$supplier->cover_photo) {
            $supplier->cover_photo = asset('img/users/banner.png');
          }
          $supplier->save();

          $supplier->tags = str_replace(",", ", ", strip_tags($request->tags));
          $categories = explode(",", strip_tags($request->categories));
          foreach ($categories as $category) {
            $dbcategory = Categories::where('name', $category)->first();
            $supplier->categories()->attach($dbcategory);
            $supplier->save();
          }
          if ($request->RFC && $request->CURP) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          } else if ($request->CURP) {
            $supplier->CURP = strip_tags($request->CURP);
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          } else if ($request->RFC) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          }

          if (!$request->RFC && !$request->CURP) {
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          }

          $supplier->clabe = $request->clabe;
          $supplier->bank_id = $request->bank;
          $supplier->regimen = $request->taxes_id;


          $supplier->minimun_fee = 150;
          $supplier->address = strip_tags($request->address);
          if($request->references_options != 5) {
            $supplier->references = strip_tags($request->references_options);
          } else {
            $supplier->references = strip_tags($request->references);
          }
          if ($request->lat != null && $request->lng != null) {
            $point = new Point($request->lat, $request->lng);
            $supplier->location = $point;
          }
          $supplier->save();
        }


        return redirect('supplier');
    }

    public function hero(Request $request)
    {
        //
        $user = Auth::user();
        $banks = Banks::pluck('name', 'id');
        $categories_check =  Suppliers::where('user_id', $user->id)->first();
        if (isset($categories_check)) {
          $categories_names = $categories_check->categories->pluck('name');
        }
        else {
          $categories_names = null;
        }

        $supplier = Suppliers::where('user_id', $user->id)->first();
        if ($supplier) {
          if ($supplier->location) {
            $rules = [
              'name' => 'required|string',
              'categories' => 'required|string',
              'tags' => 'nullable|string',
              'address' => 'string',
              'lat' => 'numeric|nullable',
              'lng' => 'numeric|nullable',
              'reference_options' => 'required|numeric',
              'reference' => 'nullable|string',
            ];
            /* if (empty($request->RFC)) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'required|string',
                //'CURP' => 'required|unique:suppliers|string|size:18',
                //'RFC' => 'string|size:14|nullable',
                //'clabe' => 'string|regex:/(^[0-9 ]+$)+/',
                'bank' => 'required|numeric',
                'minimun_fee' => 'required|numeric',
                //'taxes_id' => 'required|numeric',
                'address' => 'string',
                'lat' => 'numeric|nullable',
                'lng' => 'numeric|nullable',
              ];
            } else if (empty($request->CURP)) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'required|string',
                //'CURP' => 'string|size:18|nullable',
                //'RFC' => 'required|unique:suppliers|string|size:13',
                //'clabe' => 'string|regex:/(^[0-9 ]+$)+/',
                'bank' => 'required|numeric',
                'minimun_fee' => 'required|numeric',
                //'taxes_id' => 'required|numeric',
                'address' => 'string',
                'lat' => 'numeric|nullable',
                'lng' => 'numeric|nullable',
              ];
            } */
          } else {
            $rules = [
              'name' => 'required|string',
              'categories' => 'required|string',
              'tags' => 'nullable|string',
              'address' => 'required|string',
              'lat' => 'required|numeric',
              'lng' => 'required|numeric',
              'reference_options' => 'required|numeric',
              'reference' => 'nullable|string',
            ];
          }
        } else {
          $rules = [
            'name' => 'required|string',
            'categories' => 'required|string',
            'tags' => 'nullable|string',
            'address' => 'required|string',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
            'reference_options' => 'required|numeric',
            'reference' => 'nullable|string',
          ];
          /* if (empty($request->RFC)) {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'required|mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'required|string',
              //'CURP' => 'required|unique:suppliers|string|size:18',
              //'RFC' => 'string|size:14|nullable',
              //'clabe' => 'string|regex:/(^[0-9 ]+$)+/',
              'bank' => 'required|numeric',
              'minimun_fee' => 'required|numeric',
              //'taxes_id' => 'required|numeric',
              'address' => 'required|string',
              'lat' => 'required|numeric',
              'lng' => 'required|numeric',
            ];
          } else if (empty($request->CURP)) {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'required|mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'required|string',
              //'CURP' => 'string|size:18|nullable',
              //'RFC' => 'required|unique:suppliers|string|size:13',
              //'clabe' => 'string|regex:/(^[0-9 ]+$)+/',
              'bank' => 'required|numeric',
              'minimun_fee' => 'required|numeric',
              //'taxes_id' => 'required|numeric',
              'address' => 'required|string',
              'lat' => 'required|numeric',
              'lng' => 'required|numeric',
            ];
          } */

        }

        $messages = [
          'name.required' => 'Se requiere el nombre de la empresa',
          'categories.required' => 'Se requiere una categoría',
          'tags.required' => 'Se requiere un tag',
          //'RFC.required' => 'Se requiere un RFC',
          //'CURP.required' => 'Se requiere un CURP',
          //'RFC.unique' => 'RFC ya registrado',
          //'CURP.unique' => 'CURP ya registrado',
          //'RFC.size' => 'RFC no valido',
          //'CURP.size' => 'CURP no valido',
          //'taxes_id.required' => 'Se requiere un regimen fiscal',
          //'clabe.required' => 'Se requiere una CLABE interbancaria',
          //'minimun_fee.required' => 'Se requiere un monto mínimo a cobrar',
          'address.required' => 'Se requiere una dirección',
          'lat.required' => 'Se requiere una dirección válida, si ya hay una dirección escrita, favor de volverla a escribir',
          'lng.required' => 'Se requiere una dirección válida, si ya hay una dirección escrita, favor de volverla a escribir',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
          return response()->json($validator);
        }

        $supplier = Suppliers::where('user_id', $user->id)->first();

        if ($supplier) {
          $supplier->user_id = $user->id;
          $supplier->company_name = strip_tags($request->name);
          $supplier->cover_photo = asset('img/users/banner.png');
          $supplier->save();

          $supplier->tags = strip_tags($request->tags);
          $categories = explode(",", strip_tags($request->categories));

          $supplier->categories()->sync(null);
          foreach ($categories as $category) {
            $dbcategory = Categories::where('name', $category)->first();
            if(isset($dbcategory)){
              $supplier->categories()->attach($dbcategory);
              $supplier->save();
            }
          }
          /* if ($request->RFC && $request->CURP) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          } else if ($request->CURP) {
            $supplier->CURP = strip_tags($request->CURP);*/
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          /*} else if ($request->RFC) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          }
          $supplier->clabe = $request->clabe;
          $supplier->bank_id = $request->bank;
          $supplier->regimen = $request->taxes_id;
          */

          $supplier->minimun_fee = 150;
          $supplier->address = strip_tags($request->address);
          if($request->reference_options != 5) {
            $supplier->references = strip_tags($request->reference_options);
          } else {
            $supplier->references = strip_tags($request->reference);
          }
          if ($request->lat != null && $request->lng != null) {
            $point = new Point($request->lat, $request->lng);
            $supplier->location = $point;
          }
          $supplier->save();

        } else {
          $supplier = new Suppliers();
          $supplier->user_id = $user->id;
          $supplier->company_name = strip_tags($request->name);
          $supplier->cover_photo = asset('img/users/banner.png');
          $supplier->save();

          $supplier->tags = strip_tags($request->tags);
          $categories = explode(",", strip_tags($request->categories));

          foreach ($categories as $category) {
            $dbcategory = Categories::where('name', $category)->first();
            if(isset($dbcategory)){
              $supplier->categories()->attach($dbcategory);
              $supplier->save();
            }
          }
          /* if ($request->RFC && $request->CURP) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          } else if ($request->CURP) {
            $supplier->CURP = strip_tags($request->CURP);
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          } else if ($request->RFC) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          }
          $supplier->clabe = $request->clabe;
          $supplier->bank_id = $request->bank;
          $supplier->regimen = $request->taxes_id;
          */

          $supplier->minimun_fee = 150;
          $supplier->address = strip_tags($request->address);
          if($request->reference_options != 5) {
            $supplier->references = strip_tags($request->reference_options);
          } else {
            $supplier->references = strip_tags($request->reference);
          }
          if ($request->lat != null && $request->lng != null) {
            $point = new Point($request->lat, $request->lng);
            $supplier->location = $point;
          }
          $supplier->save();

          $user->role_id = 2;
          $user->save();
        }


        return response()->json([
            'message' => 'Listo, ¡ya eres un Héroe! Mantente al tanto al llamado de tus clientes'
        ]);
    }

    public function edit(Request $request)
    {
        //
        $user = Auth::user();
        $banks = Banks::pluck('name', 'id');
        $disk = Storage::disk('gcs');
        $categories_check =  Suppliers::where('user_id', $user->id)->first();
        if (isset($categories_check)) {
          $categories_names = $categories_check->categories->pluck('name');
        }
        else {
          $categories_names = null;
        }

        if ($request->isMethod('get'))
        return view('supplier.form', ['supplier' => Suppliers::where('user_id', $user->id)->first()], compact('banks','categories_names'));


        $supplier = Suppliers::where('user_id', $user->id)->first();
        if ($supplier) {
          if ($supplier->location !=null) {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'nullable|string',
              'minimun_fee' => 'required|numeric',
              'address' => 'string',
              'lat' => 'numeric|nullable',
              'lng' => 'numeric|nullable',
              'references_options' => 'required|numeric',
              'references' => 'nullable|string',
            ];
            if (empty($request->RFC)) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'required|string',
                'CURP' => 'unique:suppliers|nullable|string|size:18',
                'RFC' => 'string|size:14|nullable',
                'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
                'bank' => 'required|numeric',
                'minimun_fee' => 'required|numeric',
                'taxes_id' => 'required|numeric',
                'address' => 'string',
                'lat' => 'numeric|nullable',
                'lng' => 'numeric|nullable',
              ];
            } else if (empty($request->CURP)) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'required|string',
                'CURP' => 'string|size:18|nullable',
                'RFC' => 'unique:suppliers|nullable|string|size:13',
                'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
                'bank' => 'required|numeric',
                'minimun_fee' => 'required|numeric',
                'taxes_id' => 'required|numeric',
                'address' => 'string',
                'lat' => 'numeric|nullable',
                'lng' => 'numeric|nullable',
              ];
            }
          }
        } else {
          $rules = [
            'company_name' => 'required|string',
            'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
            'categories' => 'required|string',
            'tags' => 'nullable|string',
            'minimun_fee' => 'required|numeric',
            'address' => 'required|string',
            'lat' => 'required|numeric',
            'lng' => 'required|numeric',
            'references_options' => 'required|numeric',
            'references' => 'nullable|string',
          ];
          if (empty($request->RFC)) {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'required|mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'required|string',
              'CURP' => 'unique:suppliers|nullable|string|size:18',
              'RFC' => 'string|size:14|nullable',
              'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
              'bank' => 'required|numeric',
              'minimun_fee' => 'required|numeric',
              'taxes_id' => 'required|numeric',
              'address' => 'required|string',
              'lat' => 'required|numeric',
              'lng' => 'required|numeric',
            ];
          } else if (empty($request->CURP)) {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'required|mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'required|string',
              'CURP' => 'string|size:18|nullable',
              'RFC' => 'unique:suppliers|nullable|string|size:13',
              'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
              'bank' => 'required|numeric',
              'minimun_fee' => 'required|numeric',
              'taxes_id' => 'required|numeric',
              'address' => 'required|string',
              'lat' => 'required|numeric',
              'lng' => 'required|numeric',
            ];
          }
        }

        $messages = [
          'company_name.required' => 'Se requiere el nombre de la empresa',
          'cover_photo.required' => 'Se requiere una foto de portada',
          'categories.required' => 'Se requiere una categoría',
          'tags.required' => 'Se requiere un tag',
          'RFC.required' => 'Se requiere un RFC',
          'CURP.required' => 'Se requiere un CURP',
          'RFC.unique' => 'RFC ya registrado',
          'CURP.unique' => 'CURP ya registrado',
          'RFC.size' => 'RFC no valido',
          'CURP.size' => 'CURP no valido',
          'taxes_id.required' => 'Se requiere un regimen fiscal',
          'clabe.required' => 'Se requiere una CLABE interbancaria',
          'minimun_fee.required' => 'Se requiere un monto mínimo a cobrar',
          'address.required' => 'Se requiere una dirección',
          'lat.required' => 'Se requiere una dirección válida, si ya hay una dirección escrita, favor de volverla a escribir',
          'lng.required' => 'Se requiere una dirección válida, si ya hay una dirección escrita, favor de volverla a escribir',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
          return redirect()->back()->withInput($request->all())->withErrors($validator);
        }

        $supplier = Suppliers::where('user_id', $user->id)->first();

        if ($supplier) {
          $supplier->user_id = $user->id;
          $supplier->company_name = strip_tags($request->company_name);
          if ($request->hasFile('cover_photo')){
            $image = $request->file('cover_photo');
            $filepath = public_path('img/users/'. $user->id);
            /*if (!File::exists($filepath)) {
              File::makeDirectory($filepath, 0775, true);
            }*/
            $filename = time() . '.' . $image->getClientOriginalExtension();
            //Image::make($image)->resize(720, 480)->save( public_path('img/users/' . $id . '/' . $filename ) );
            if ($supplier->cover_photo) {
              $disk->delete(str_replace('https://storage.googleapis.com/ichamba-1562349005909.appspot.com/', '', $supplier->cover_photo));
            }
            $disk->putFileAs('img/users/'.  $user->id . '/', $image, $filename, 'public');
            $supplier->cover_photo = $disk->url('img/users/'.  $user->id . '/' . $filename);
            $supplier->save();
          } else if(!$supplier->cover_photo) {
            $supplier->cover_photo = asset('img/users/banner.png');
          }
          $supplier->save();

          $supplier->tags = str_replace(",", ", ", strip_tags($request->tags));
          $categories = explode(",", strip_tags($request->categories));

          $supplier->categories()->sync(null);
          foreach ($categories as $category) {
            $dbcategory = Categories::where('name', $category)->first();
            if(isset($dbcategory)){
              $supplier->categories()->attach($dbcategory);
              $supplier->save();
            }
          }

          if ($request->RFC && $request->CURP) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          } else if ($request->CURP) {
            $supplier->CURP = strip_tags($request->CURP);
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          } else if ($request->RFC) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          }

          if (!$request->RFC && !$request->CURP) {
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          }

          $supplier->clabe = strip_tags($request->clabe);
          $supplier->bank_id = $request->bank;
          $supplier->regimen = $request->taxes_id;


          $supplier->minimun_fee = ($request->minimun_fee < 150 ? 150 : $request->minimun_fee);
          $supplier->address = strip_tags($request->address);
          if ($request->lat != null && $request->lng != null) {
            $point = new Point($request->lat, $request->lng);
            $supplier->location = $point;
          }
          $supplier->save();
        } else {
          $supplier = new Suppliers();
          $supplier->user_id = $user->id;
          $supplier->company_name = strip_tags($request->company_name);
          if ($request->hasFile('cover_photo')){
            $image = $request->file('cover_photo');
            $filepath = public_path('img/users/'.  $user->id);
            /*if (!File::exists($filepath)) {
              File::makeDirectory($filepath, 0775, true);
            }*/
            $filename = time() . '.' . $image->getClientOriginalExtension();
            //Image::make($image)->resize(720, 480)->save( public_path('img/users/' . $id . '/' . $filename ) );
            $disk->putFileAs('img/users/'.  $user->id . '/', $image, $filename, 'public');
            $supplier->cover_photo = $disk->url('img/users/'.  $user->id . '/' . $filename);
            $supplier->save();
          } else if(!$supplier->cover_photo) {
            $supplier->cover_photo = asset('img/users/banner.png');
          }
          $supplier->save();

          $supplier->tags = str_replace(",", ", ", strip_tags($request->tags));
          $categories = explode(",", strip_tags($request->categories));

          foreach ($categories as $category) {
            $dbcategory = Categories::where('name', $category)->first();
            if(isset($dbcategory)){
              $supplier->categories()->attach($dbcategory);
              $supplier->save();
            }
          }

          if ($request->RFC && $request->CURP) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          } else if ($request->CURP) {
            $supplier->CURP = strip_tags($request->CURP);
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          } else if ($request->RFC) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          }
          $supplier->clabe = $request->clabe;
          $supplier->bank_id = $request->bank;
          $supplier->regimen = $request->taxes_id;


          $supplier->minimun_fee = ($request->minimun_fee < 150 ? 150 : $request->minimun_fee);
          //$supplier->minimun_fee = 150;
          $supplier->address = strip_tags($request->address);
          if($request->references_options != 5) {
            $supplier->references = strip_tags($request->references_options);
          } else {
            $supplier->references = strip_tags($request->references);
          }
          $supplier->location = new Point($request->lat, $request->lng);
          $supplier->save();
        }

        $user->role_id = 2;
        $user->save();

        return redirect('home');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
        $user = Auth::user();
        $banks = Banks::pluck('name', 'id');
        $categories_check = Suppliers::find($id);
        $disk = Storage::disk('gcs');
        $categories_names = $categories_check->categories->pluck('name');
        $supplier = Suppliers::where('id', $id)->first();

        if ($request->isMethod('get'))
          return view('supplier.form', ['supplier' => Suppliers::find($id)], compact('banks','categories_names'));

          if ($supplier) {
            if ($supplier->location !=null) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'nullable|string',
                'minimun_fee' => 'required|numeric',
                'address' => 'string',
                'lat' => 'numeric|nullable',
                'lng' => 'numeric|nullable',
                'references_options' => 'required|numeric',
                'references' => 'nullable|string',
              ];
              if (empty($request->RFC)) {
                $rules = [
                  'company_name' => 'required|string',
                  'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                  'categories' => 'required|string',
                  'tags' => 'required|string',
                  'CURP' => 'unique:suppliers|nullable|string|size:18',
                  'RFC' => 'string|size:14|nullable',
                  'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
                  'bank' => 'required|numeric',
                  'minimun_fee' => 'required|numeric',
                  'taxes_id' => 'required|numeric',
                  'address' => 'string',
                  'lat' => 'numeric|nullable',
                  'lng' => 'numeric|nullable',
                ];
              } else if (empty($request->CURP)) {
                $rules = [
                  'company_name' => 'required|string',
                  'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                  'categories' => 'required|string',
                  'tags' => 'required|string',
                  'CURP' => 'string|size:18|nullable',
                  'RFC' => 'unique:suppliers|nullable|string|size:13',
                  'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
                  'bank' => 'required|numeric',
                  'minimun_fee' => 'required|numeric',
                  'taxes_id' => 'required|numeric',
                  'address' => 'string',
                  'lat' => 'numeric|nullable',
                  'lng' => 'numeric|nullable',
                ];
              }
            }
          } else {
            $rules = [
              'company_name' => 'required|string',
              'cover_photo' => 'mimetypes:image/jpeg,image/png,image/jpg|max:2048',
              'categories' => 'required|string',
              'tags' => 'nullable|string',
              'minimun_fee' => 'required|numeric',
              'address' => 'required|string',
              'lat' => 'required|numeric',
              'lng' => 'required|numeric',
              'references_options' => 'required|numeric',
              'references' => 'nullable|string',
            ];
            if (empty($request->RFC)) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'required|mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'required|string',
                'CURP' => 'unique:suppliers|nullable|string|size:18',
                'RFC' => 'string|size:14|nullable',
                'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
                'bank' => 'required|numeric',
                'minimun_fee' => 'required|numeric',
                'taxes_id' => 'required|numeric',
                'address' => 'required|string',
                'lat' => 'required|numeric',
                'lng' => 'required|numeric',
              ];
            } else if (empty($request->CURP)) {
              $rules = [
                'company_name' => 'required|string',
                'cover_photo' => 'required|mimetypes:image/jpeg,image/png,image/jpg|max:2048',
                'categories' => 'required|string',
                'tags' => 'required|string',
                'CURP' => 'string|size:18|nullable',
                'RFC' => 'unique:suppliers|nullable|string|size:13',
                'clabe' => 'string|nullable|regex:/(^[0-9 ]+$)+/',
                'bank' => 'required|numeric',
                'minimun_fee' => 'required|numeric',
                'taxes_id' => 'required|numeric',
                'address' => 'required|string',
                'lat' => 'required|numeric',
                'lng' => 'required|numeric',
              ];
            }
          }

          $messages = [
            'company_name.required' => 'Se requiere el nombre de la empresa',
            'cover_photo.required' => 'Se requiere una foto de portada',
            'categories.required' => 'Se requiere una categoría',
            'tags.required' => 'Se requiere un tag',
            'RFC.required' => 'Se requiere un RFC',
            'CURP.required' => 'Se requiere un CURP',
            'RFC.unique' => 'RFC ya registrado',
            'CURP.unique' => 'CURP ya registrado',
            'RFC.size' => 'RFC no valido',
            'CURP.size' => 'CURP no valido',
            'taxes_id.required' => 'Se requiere un regimen fiscal',
            'clabe.required' => 'Se requiere una CLABE interbancaria',
            'minimun_fee.required' => 'Se requiere un monto mínimo a cobrar',
            'adress.required' => 'Se requiere una dirección',
            'lat.required' => 'Se requiere una dirección válida, si ya hay una dirección escrita, favor de volverla a escribir',
            'lng.required' => 'Se requiere una dirección válida, si ya hay una dirección escrita, favor de volverla a escribir',
          ];

          $validator = Validator::make($request->all(), $rules, $messages);
          if ($validator->fails()) {
            return redirect()->back()->withInput($request->all())->withErrors($validator);
          }

          $supplier->company_name = strip_tags($request->company_name);
          if ($request->hasFile('cover_photo')){
            $image = $request->file('cover_photo');
            $filepath = public_path('img/users/'.  $id);
            /*if (!File::exists($filepath)) {
              File::makeDirectory($filepath, 0775, true);
            }*/
            $filename = time() . '.' . $image->getClientOriginalExtension();
            //Image::make($image)->resize(720, 480)->save( public_path('img/users/' . $id . '/' . $filename ) );
            if ($supplier->cover_photo) {
              $disk->delete(str_replace('https://storage.googleapis.com/ichamba-1562349005909.appspot.com/', '', $supplier->cover_photo));
            }
            $disk->putFileAs('img/users/'.  $id . '/', $image, $filename, 'public');
            $supplier->cover_photo = $disk->url('img/users/'.  $id . '/' . $filename);
            $supplier->save();
          } else if(!$supplier->cover_photo) {
            $supplier->cover_photo = asset('img/users/banner.png');
          }
          $supplier->save();

          $supplier->tags = str_replace(",", ", ", strip_tags($request->tags));
          $categories = explode(",", strip_tags($request->categories));

          $supplier->categories()->sync(null);
          foreach ($categories as $category) {
            $dbcategory = Categories::where('name', $category)->first();
            if(isset($dbcategory)){
              $supplier->categories()->attach($dbcategory);
              $supplier->save();
            }
          }
          if ($request->RFC && $request->CURP) {
            $supplier->RFC = strip_tags($request->RFC);
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          } else if ($request->CURP) {
            $supplier->CURP = strip_tags($request->CURP);
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          } else if ($request->RFC) {
            if ($request->taxes_id == 1) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_fisica')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_fisica')->first()->id;
            } else if ($request->taxes_id == 2) {
              $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_SAT_moral')->first()->id;
              $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_SAT_moral')->first()->id;
            }
          }  

          if (!$request->RFC && !$request->CURP) {
            $supplier->IVA_id = iChambaParameter::where('parameter', 'IVA_NoSAT')->first()->id;
            $supplier->ISR_id = iChambaParameter::where('parameter', 'ISR_NoSAT')->first()->id;
          }

          $supplier->clabe = $request->clabe;
          $supplier->bank_id = $request->bank;
          $supplier->regimen = $request->taxes_id;


          $supplier->minimun_fee = ($request->minimun_fee < 150 ? 150 : $request->minimun_fee);
          $supplier->address = strip_tags($request->address);
          if($request->references_options != 5) {
            $supplier->references = strip_tags($request->references_options);
          } else {
            $supplier->references = strip_tags($request->references);
          }
          if ($request->lat != null && $request->lng != null) {
            $point = new Point($request->lat, $request->lng);
            $supplier->location = $point;
          }
          $supplier->save();

        return redirect('supplier');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
      Suppliers::destroy($id);
      return redirect('supplier');
    }

    public function certificate($id)
    {
      $supplier = Suppliers::where('id', $id)->first();

      if ($supplier->membership == false) {
        $supplier->membership = true;
      } else {
        $supplier->membership = false;
      }

      $supplier->save();

      return redirect('supplier');
    }

    public function check(Request $request) {

      $rules = [
        'category' => 'required|string|regex:/(^[a-zA-Z\s ÑñÁáÉéÍíÓóÚúÜü]+$)+/',
      ];
      $validator = Validator::make($request->all(), $rules);
      if ($validator->fails()) {
        return redirect()->back()->withInput($request->all())->withErrors($validator);
      }

      $suppliers = Suppliers::whereHas('categories', function($q) use ($request){
        $q->where('name', $request->category)->orwhere('en_name', $request->category);
      })->get();
      if ($suppliers != '[]') {
        echo('true');
      } else {
        return null;
      }
    }

    public function getpostulation(Request $request) {

      $user = Auth::user();
      $supplier = Suppliers::where('user_id', $user->id)->first();
      $distance = 0.5;
      $postulations = Postulations::distance('location', $supplier->location, $distance)->orderBy('created_at', 'DESC')->get();

      $postulationsinfo = array();

      foreach ($postulations as $postulation) {
        if (in_array($postulation->category_id, $supplier->categories->pluck('id')->toArray())) {
          $category = Categories::where('id', $postulation->category_id)->first();
          $already_post = in_array($postulation->id, $supplier->postulations->pluck('id')->toArray());
          $time_limit = Carbon::parse($postulation->appointment);
            if (Carbon::now()->diffInMinutes($time_limit, false) > 15) {
              $postulationinfo = array(
                'id' => $postulation->id,
                'category' => $category->name,
                'address' => str_replace(' ' . $postulation->int_number, '', $postulation->address),
                'references' => $postulation->references,
                'date' => $postulation->appointment,
                'lat' => $postulation->location->getLat(),
                'lng' => $postulation->location->getLng(),
                'amount' => $postulation->amount,
                'details' => $postulation->details,
                'time_limit' => (Carbon::now()->diffInMinutes($time_limit) - 15),
                'already_post' => $already_post
              );
              $postulationsinfo[] = $postulationinfo;
            }
        }
      }
      return response()->json($postulationsinfo);
    }

    public function getcontractedpostulation(Request $request) {

      $user = Auth::user();
      $supplier = Suppliers::where('user_id', $user->id)->first();
      $contracts = CurrentContracts::where('supplier_id', $supplier->id)->orderBy('created_at', 'DESC')->get();

      $contractsinfo = array();

      foreach ($contracts as $contract) {
          $category = Categories::where('id', $contract->category_id)->first();
              $contractinfo = array(
                'id' => $contract->id,
                'phone' => $contract->user->phone,
                'en_category' => $category->en_name,
                'category' => $category->name,
                'address' => $contract->address,
                'references' => $contract->references,
                'date' => $contract->appointment,
                'lat' => $contract->location->getLat(),
                'lng' => $contract->location->getLng(),
                'amount' => $contract->amount,
                'details' => $contract->details
              );
              $contractsinfo[] = $contractinfo;
      }
      return response()->json($contractsinfo);
    }

}
