<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Http; // Import Http facade

class RegisterController extends Controller
{
  public function register(Request $request) {
    $validatedData = $request->validate([
        'username' => 'required|alpha_num',
        'password' => 'required|min:6',
        'konfirmasi_pass' => 'required|same:password',
        'email' => 'required|email',
        'no_whatsapp' => 'required|numeric',
        'bank' => 'required|alpha_num',
        'pemilik_rekening' => 'required|alpha_num',
        'norek' => 'required|numeric',
        'refferal' => 'nullable|alpha_num',
    ]);

    // Buat user baru
    $username = str_replace(' ', '', $request->username);
    $kode_unik = substr(str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890'), 0, 4);
    $extplayer = 'ab' . $username . $kode_unik;

    $user = new User;
    $user->username = strtolower(htmlspecialchars($username));
    $user->extplayer = $extplayer;
    $user->password = bcrypt($request->password);
    $user->email = htmlspecialchars($request->email);
    $user->no_whatsapp = $request->no_whatsapp;
    $user->bank = htmlspecialchars($request->bank);
    $user->pemilik_rekening = htmlspecialchars($request->pemilik_rekening);
    $user->norek = $request->norek;
    $user->refferal = $request->refferal;
    $user->status = 'Active';
    $user->level = 'user';
    $user->save();

    // Panggil API untuk membuat member
    $response = Http::get(env('BASE_API'), [
    'cmd' => 'create',
    'agent_code' => env('AGENT_CODE'),
    'username' => $extplayer,
    'signature' => env('SIGNATURE'),
]);

    // Handle response dari API

    // Redirect atau berikan respons sesuai kebutuhan
    return redirect()->route('home')->with('success', 'Registrasi berhasil!');
}
}