<?php

namespace App\Http\Controllers\Client;

use App\Model\MailingList;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;


class UserController extends BaseController
{


    public function edit()
    {
        $newsletter = MailingList::where('email', $this->me->email)->first();

        view()->share('current_section', 'account');

        return view('client.user.edit', compact('newsletter'));
    }

    public function update(Request $request)
    {
        $user = $this->me;
        if ($new_password = $request->get('new_password')) {
            if ($old_password = request('old_password')) {
                if (!Hash::check($old_password, $user->password)) {
                    return back()->with('error', 'Parola veche invalida');
                }
            }
            $user->password = Hash::make($new_password);
        }
        $user->fill($request->all())->save();

        // handle newsletter
        $newsletter = MailingList::where('email', $this->me->email)->first();
        if ($newsletter && !$request->get('newsletter')) {
            $newsletter->delete();
        } else if (!$newsletter && $request->get('newsletter')) {
            (new MailingList)->fill(['email' => $this->me->email])->save();
        }

        return redirect()->route('client.user.edit')->with('status', 'Date actualizate.');
    }
}
