<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Http\Api\fiver;
use App\Models\User;
use App\Models\Saldo;
use App\Models\BankAccount;
use App\Models\BannerPromosi;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
    use RegistersUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest');
    }

    /* ===============================
     * FORM REGISTER
     * =============================== */
    public function index()
    {
        $banners = BannerPromosi::all();
        return view('auth.register', compact('banners'));
    }

    /* ===============================
     * VALIDASI
     * =============================== */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name'       => 'required|string|max:255|unique:users,name',
            'email'      => 'required|email|max:255|unique:users,email',
            'password'   => 'required|min:8|confirmed',
            'mobile_no'  => 'required|string|unique:users,telp',
            'acc_name'   => 'required|string|max:255',
            'bank_name'  => 'required|string|max:100',
            'acc_no'     => 'required|string|max:50',
        ]);
    }

    /* ===============================
     * CREATE USER
     * =============================== */
    protected function create(array $data)
    {
        return DB::transaction(function () use ($data) {

            // generate extplayer
            $username = strtolower(preg_replace('/\s+/', '', $data['name']));
            $extplayer = 'ab' . $username . substr(str_shuffle('abcdef0123456789'), 0, 4);

            // create user
            $user = User::create([
                'name'      => $data['name'],
                'email'     => $data['email'],
                'password'  => Hash::make($data['password']),
                'telp'      => $data['mobile_no'],
                'nama_rek'  => $data['acc_name'],
                'ref_code'  => $data['ref_code'] ?? null,
                'extplayer' => $extplayer,
            ]);

            // bank account
            BankAccount::create([
                'user_id'  => $user->id,
                'method'   => $data['method'] ?? 'Bank',
                'nama_rek' => $data['acc_name'],
                'bank'     => $data['bank_name'],
                'no_rek'   => $data['acc_no'],
            ]);

            // saldo wallet
            Saldo::create([
                'user_id'  => $user->id,
                'saldo'    => 0,
                'bonus'    => 0,
                'referral' => 0,
            ]);

            // create user di game API
            $api = new fiver();
            $res = json_decode($api->create($extplayer), true);

            if (!isset($res['status']) || $res['status'] !== true) {
                throw new \Exception($res['msg'] ?? 'Gagal create user game');
            }

            return $user;
        });
    }

    /* ===============================
     * AUTO LOGIN SETELAH REGISTER
     * =============================== */
    protected function registered($user)
    {
        Auth::login($user); // 🔥 PASTI AUTO LOGIN
        return redirect('/register-success');
    }

    /* ===============================
     * AJAX CHECK
     * =============================== */
    public function checkExistingEmail(Request $request)
    {
        return response()->json([
            'exists' => User::where('email', $request->email)->exists()
        ]);
    }

    public function checkExistingMobile(Request $request)
    {
        return response()->json([
            'exists' => User::where('telp', $request->mobile_no)->exists()
        ]);
    }
}