<?php

namespace App\Http\Controllers\Api;

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

class SettingsController extends Controller
{
    /**
     * Set or change Withdrawal PIN (6 digits). Used to confirm withdrawals.
     */
    public function setPin(Request $request)
    {
        $user = $request->user();
        $hasExistingPin = !empty($user->withdrawal_pin_hash);

        $rules = [
            'new_pin' => 'required|string|digits:6',
            'new_pin_confirmation' => 'required|same:new_pin',
        ];
        if ($hasExistingPin) {
            $rules['current_pin'] = 'required|string|digits:6';
        }

        $validator = Validator::make($request->all(), $rules, [
            'new_pin.digits' => 'PIN must be exactly 6 digits.',
            'new_pin_confirmation.same' => 'PIN confirmation does not match.',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        if ($hasExistingPin) {
            if (!Hash::check($request->current_pin, $user->withdrawal_pin_hash)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Current PIN is incorrect.'
                ], 422);
            }
        }

        $user->update([
            'withdrawal_pin_hash' => Hash::make($request->new_pin),
        ]);

        return response()->json([
            'success' => true,
            'message' => $hasExistingPin ? 'PIN changed successfully.' : 'PIN set successfully. Use it to confirm withdrawals.',
        ]);
    }
}
