<?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\Log;
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'));
    }

    /* ===============================
     * VALIDATOR
     * =============================== */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name'       => 'required|string|min:6|max:12|unique:users,name',
            'email'      => 'required|email|max:255|unique:users,email',
            'password'   => 'required|min:8|confirmed',
            'mobile_no'  => 'required|string|min:5|max:20|unique:users,telp',

            'acc_name'   => 'required|string|max:255',
            'bank_name'  => 'required|string|max:100',
            'acc_no'     => 'required|string|max:50',

            // ✅ CAPTCHA TIDAK DIUBAH
            'captcha'    => 'required|captcha',

            'method'     => 'required',
        ]);
    }

    /* ===============================
     * CREATE USER (DB + GAME API)
     * =============================== */
    protected function create(array $data)
{
    DB::beginTransaction();

    try {

        /**
         * ===============================
         * 1. REGISTER KE FIVER DULU
         * ===============================
         */
        $username = preg_replace('/\s+/', '', strtolower($data['name']));

        $fiver = new fiver();
        $res   = $fiver->createUser($username);

        Log::info('FIVER CREATE USER RESPONSE', $res);

        if (
            !isset($res['status']) ||
            (int)$res['status'] !== 1 ||
            empty($res['user_code'])
        ) {
            throw new \Exception('Gagal register user ke Fiver');
        }

        // ✅ INI SATU-SATUNYA extplayer YANG BENAR
        $extplayer = $res['user_code'];

        /**
         * ===============================
         * 2. CREATE USER LOKAL
         * ===============================
         */
        $user = User::create([
            'name'      => $data['name'],
            'nama_rek'  => $data['acc_name'],
            'email'     => $data['email'],
            'password'  => Hash::make($data['password']),
            'telp'      => $data['mobile_no'],
            'ref_code'  => $data['ref_code'] ?? null,
            'extplayer' => $extplayer, // 🔥 VALID
        ]);

        /**
         * ===============================
         * 3. BANK ACCOUNT
         * ===============================
         */
        BankAccount::create([
            'user_id'  => $user->id,
            'method'   => $data['method'],
            'nama_rek' => $data['acc_name'],
            'bank'     => $data['bank_name'],
            'no_rek'   => $data['acc_no'],
        ]);

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

        DB::commit();

        Log::info('REGISTER SUCCESS', [
            'user_id'   => $user->id,
            'extplayer' => $extplayer,
        ]);

        return $user;

    } catch (\Throwable $e) {

        DB::rollBack();

        Log::critical('REGISTER FAILED TOTAL', [
            'error' => $e->getMessage(),
        ]);

        throw $e;
    }
}

    /* ===============================
     * SETELAH REGISTER
     * =============================== */
    protected function registered($user)
{
    if ($user && $user->id) {
        Log::info('REGISTER SUCCESS', [
            'user_id'   => $user->id,
            'extplayer' => $user->extplayer,
        ]);
    }

    return redirect('/register-success');
}

    /* ===============================
     * REFRESH CAPTCHA (TETAP BAWAAN)
     * =============================== */
    public function refreshCaptcha()
    {
        return captcha_src();
    }

    /* ===============================
     * 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()
        ]);
    }
}