<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\ProfileRequest;
use App\Services\ImageService;
use Illuminate\Support\Facades\Hash;
use App\Traits\ImageUploadTrait;

class CustomerController extends Controller{
    use ImageUploadTrait;

    public function dashboard(){
        return view('frontend.user.dashboard');
    }

    public function profile(){
        return view('frontend.user.profile');
    }

    public function addresses(){
        return view('frontend.user.addresses');
    }

    public function orders(){
        return view('frontend.user.orders');
    }

    public function payments(){
        return view('frontend.user.payments');
    }



    public function updateProfile(ProfileRequest $request){
        $user = auth(activeGuard())->user();
        if (!empty($request->password) && !Hash::check($request->password, $user->password)) {
            $password = bcrypt($request->password);
        }

        if ($request->hasFile('user_image')) {
            $user->uploadFiles([$request->user_image],['width' => 150, "height" => 100]);
        }

        $user->update([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'phone' => $request->phone,
            'receive_email' => $request->boolean("receive_email"),
            'password' => $password ?? $user->password
        ]);

        toast(action_message("updated"), 'success');
        return redirect()->route('user.dashboard');
    }

    public function removeImage(){
        if (auth(activeGuard())->user()->user_image) {
            (new ImageService())->unlinkImage(auth(activeGuard())->user()->user_image, 'users');
            auth(activeGuard())->user()->update(['user_image' => NULL]);

            toast('Image removed successfully', 'success');
            return redirect()->back();
        }

        toast('please try again later', 'warning');
        return redirect()->back();
    }

}
