<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Auth;
use App\Http\Requests\PassRequest;

class CuentasController extends Controller
{
    public function cuenta(){
    	return view('user.cuenta');
    }

    public function cuenta_update(Request $request){
    	$i = User::all()->where('email',$request->email)->where('id','<>', Auth::user()->id)->count();

        if ($i>0) {            
            return redirect()->back()->with('success','success')->with('mensaje','El correo electrónico ya se encuentra asociada a otra cuenta');
        }

        $id = Auth::user()->id;
        $user = User::find($id);
        $url = null;

        if ($request->foto) {

            $file    = $request->file('foto');

            $name    = 'foto-'.$id.'.png';

            \Storage::disk('perfil')->put($name,  \File::get($file));

            $url = "/img/perfil/" . $name;
        }else{
            $url = $user->img;
        }

        $user->name    = $request->name;
        $user->email   = $request->email;
        $user->img     = $url;
        $user->save();

        return redirect()->back()->with('success','success')->with('mensaje','Datos de la cuenta actualizado con éxito');
    }

    public function clave(){
        return view('user.pass');
    }

    public function clave_update(PassRequest $request){
        $validar = \Hash::check($request->clave,Auth::user()->password);

        if ($validar) {
            
            $pass = User::find(Auth::user()->id);
            $pass->password = \Hash::make($request->password);
            $pass->save();

            return redirect()->back()->with('success','success')->with('mensaje','Contraseña actualizada con éxito');   

        }else{
            return redirect()->back()->with('success','success')->with('mensaje','Contraseña incorrecta'); 
        }
    }
}
