<?php

namespace App\Http\Controllers\CounterManager;

use Illuminate\Http\Request;
use App\Rules\FileTypeValidate;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;

class ProfileController extends Controller
{
    public function profile() {
        $pageTitle = 'Profile';
        $manager   = authUser('counterManager');
        return view('counter_manager.profile', compact('pageTitle', 'manager'));
    }

    public function profileUpdate(Request $request) {
        $manager = authUser('counterManager');
        $request->validate([
            'firstname' => 'required',
            'lastname'  => 'required',
            'address'   => 'nullable|string',
            'state'     => 'nullable|string',
            'zip'       => 'nullable|string',
            'city'      => 'nullable|string',
            'image'     => ['nullable', 'image', new FileTypeValidate(['jpg', 'jpeg', 'png'])],
        ]);

        if ($request->hasFile('image')) {
            try {
                $old            = $manager->image;
                $manager->image = fileUploader($request->image, getFilePath('counter_manager'), getFileSize('counter_manager'), $old);
            } catch (\Exception $exp) {
                $notify[] = ['error', 'Couldn\'t upload your image'];
                return back()->withNotify($notify);
            }
        }

        $manager->firstname = $request->firstname;
        $manager->lastname  = $request->lastname;
        $manager->address   = $request->address;
        $manager->state     = $request->state;
        $manager->zip       = $request->zip;
        $manager->city      = $request->city;
        $manager->save();

        $notify[] = ['success', 'Profile updated successfully'];
        return back()->withNotify($notify);
    }

    public function password() {
        $pageTitle = 'Password Setting';
        $manager   = authUser('counterManager');
        return view('counter_manager.password', compact('pageTitle', 'manager'));
    }

    public function passwordUpdate(Request $request) {
        $request->validate([
            'old_password' => 'required',
            'password'     => 'required|min:6|confirmed',
        ]);

        $manager = authUser('counterManager');
        if (!Hash::check($request->old_password, $manager->password)) {
            $notify[] = ['error', 'Password doesn\'t match!!'];
            return back()->withNotify($notify);
        }
        $manager->password = Hash::make($request->password);
        $manager->save();
        $notify[] = ['success', 'Password changed successfully.'];
        return to_route('counter.manager.password')->withNotify($notify);
    }
}
