<?php

namespace App\Http\Controllers;

use App\Models\UpdatePassword;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator; // Import the Validator facade

class UpdatePasswordController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['only' => ['update']]);
    }

    public function update(Request $request, $id)
    {
        echo 'param cek:'.$request . $id;
        // Validate the incoming request
        $validator = Validator::make($request->all(), [
            'pass_mobile' => 'required', // Added validation rules
        ]);

        // Check if validation fails
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        // Find the user by username
        $user = UpdatePassword::where('username', $id)->first();

        // Check if the user exists
        if (!$user) {
            return response()->json(['message' => 'User not found', 'username' => $id], 404);
        }

        // Hash the new password
        $user->pass_mobile = Hash::make($request->input('pass_mobile'));
        
        // Save the updated user data
        $user->save();

        // Log the successful update
        error_log("Update success: " . json_encode($user));

        return response()->json(['message' => 'Password updated successfully', 'user' => $user]);
    }
}
