<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\User;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class DashboardController extends Controller
{
    //
    public function index(){
        $this->middleware('auth');
        //get orders
        $orders = Order::where(["user_id" => auth()->user()->id])->get();
        return view("customer.index")->with(["orders" => $orders]);
    }

    public function updateAccount(Request $request){

        $request->validate([
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'tel' => ['required','numeric', 'min:11'],
            'address' => ['required'],
        ]);

        try {
            User::whereId(Auth()->user()->id)->update([
                "first_name" => $request->first_name,
                "last_name" => $request->last_name,
                "tel" => $request->tel,
                "address" => $request->address,
            ]);

            if(auth()->user()->user_group == '1'){
                return redirect()->back()->with(["success" => "Account updated successfully"]);
            }else{
                return redirect()->back()->with(["success" => "Account updated successfully"]);
            }
        } catch (Exception $th) {
            //throw $th;
            return redirect()->back()->with(["error" => "Oops, there was an error"]);
        }

    }

    public function changePassword(Request $request){
        $request->validate([
            'old_password' => 'required',
            'password' => 'required|confirmed',
            'password_confirmation' => 'required',
        ]);

        //verify password
        if(Hash::check($request->old_password, Auth::user()->password)){
            try {
                //change password
                DB::table("users")->where("id", Auth::user()->id)->update(["password" =>  Hash::make($request->password)]);
                return redirect()->back()->with("success", "Password changed");
            } catch (Exception $e) {
                return redirect()->back()->with("error", "Oops, there was an error, try again!!");
            }
        }else{
            return redirect()->back()->with("error", "Password do not match");
        }
    }
}
