<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserAccountController extends Controller
{
    public function webUser()
    {
        $user = Auth::user();
        $userId = $user ? $user->id : null;
        $userData = null;
        if ($userId) {
            $userData = User::where("id", $userId)->first();
        }
        return view('frontend.web-user.user-account', compact('userData'));
    }

    public function editWebUser()
    {
        $user = Auth::user();
        $userId = $user ? $user->id : null;
        $userData = null;
        if ($userId) {
            $userData = User::where("id", $userId)->first();
        }
        return view('frontend.web-user.edit-account', compact('userData'));
    }
    public function updateWebUser(Request $request, $id)
    {
        $user = User::find($id);
        $user->name = $request->name;
        $user->email = $request->email;
        $user->phone = $request->phone;
        $user->save();
        return redirect()->route('web-account')->with('success','Your information has been updated successfully!');
    }
    public function userOrderHistory()
    {
        $user = Auth::user();

        $orders = Order::where('user_id', $user->id)
            ->with('orderDetails.product')
            ->orderBy('created_at', 'desc')
            ->get();
        return view('frontend.web-user.order-history', compact('orders'));
    }
    public function userChangePassword()
    {
        return view('frontend.web-user.change-password');
    }
    public function userUpdatePassword(Request $request)
    {

        $request->validate([
            'current_password' => 'required',
            'password'     => 'required|string|confirmed|min:3',
        ]);

        if (!Hash::check($request->current_password, Auth::user()->password)) {
            return redirect()->back()->with('error', "current password does not match");
        }

        $id = Auth::user()->id;
        if ($id) {
            User::whereId($id)->update([
                'password' => Hash::make($request->password),
            ]);
        }
        return redirect()->back()->with('success','Password has been updated successfully!');
    }
}
