<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Customer;
use App\CustomerAddress;
use Auth;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Hash;

class CustomersController extends Controller
{
    public function register(){
        return view('shop.customers.register');
    }

    public function login(){
        return view('shop.customers.login');
    }

    public function store(Request $request){
        $rules = [
            'first_name' =>'required',
            'last_name' => 'required',
            'email' => 'required|unique:customers',
            'phone' => 'required|unique:customers',
            'address' => 'required',
            'postcode' => 'required',
            'city' => 'required',
            'password' => 'min:6|required_with:password_confirmation|same:password_confirmation',
            'password_confirmation' => 'min:6'
        ];

        $request->validate($rules);
        $request['password'] = Hash::make($request->password);
        $customer = Customer::create($request->all());
        CustomerAddress::create([
            'customer_id' => $customer->id,
            'address1' => $request['address'],
            'postcode' => $request['postcode'],
            'city' => $request['city'],
            'country' => 'Bosna i Hercegovina'
        ]);

        return  route('/');
    }

    public function auth(Request $request){
        //validate form data
        $request->validate([
            'email' => 'required',
            'password' => 'required'
        ]);
        //atemppt to log user in
        if(Auth::guard('customers')->attempt(['email' => $request->email, 'password' => $request->password])){
            return redirect()->intended();
        }else{
            return redirect()->back();
        }

    }

    public function logout(){
        Auth::guard('customers')->logout();
        return redirect()->route('/');
    }
}
