<?php

use Illuminate\Http\Request;
use Jenssegers\Agent\Facades\Agent;
use App\Http\Controllers\backoffice\BackofficeController;
use App\Http\Controllers\backoffice\BannerController;
use App\Http\Controllers\BonusController;
use App\Http\Controllers\MaintenanceController;
use App\Http\Controllers\backoffice\BannerPromosiController;
use App\Http\Controllers\backoffice\DatamemberController;
use App\Http\Controllers\backoffice\Deposit_bank;
use App\Http\Controllers\backoffice\DepositbankController;
use App\Http\Controllers\backoffice\DepositController;
use App\Http\Controllers\backoffice\HistoritransaksiController;
use App\Http\Controllers\backoffice\IconController;
use App\Http\Controllers\backoffice\LogoController;
use App\Http\Controllers\backoffice\PernyataanController;
use App\Http\Controllers\backoffice\ProfilAdminController;
// use App\Http\Controllers\backoffice\PromosiController;
use App\Http\Controllers\backoffice\WithdrawController;

use App\Http\Controllers\backoffice\GameAPIController;
use App\Http\Controllers\backoffice\PengaturanSaldoController;
use App\Http\Controllers\backoffice\GameSettingController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\SettingController;
use App\Http\Controllers\UserDepositController;
use App\Http\Controllers\SaldoController;
use App\Http\Controllers\UserHistoryController;
use App\Http\Controllers\UserPernyataanController;
use App\Http\Controllers\UserWithdrawController;
use App\Http\Middleware\CheckSingleSession;
use App\Models\CustomScript; // Import model CustomScript

use Illuminate\Support\Facades\DB;
use App\Models\Transaksi;
use App\Models\BannerPromosi;
use App\Models\Banner;
use App\Models\Game_list;
use App\Models\GameApi;
use App\Models\User;
use App\Models\Setting;
use App\Models\BankAccount;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Session;
use App\Http\Controllers\CaptchaServiceController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

#region user ( no login allowed )


Route::post('/checkAccNo', function (Request $request) {
  $no_rek = $request->input('acc_no');

  $existing_account = BankAccount::where('no_rek', $no_rek)->exists();

  if (!$existing_account) {
    return response()->json(true);
  } else {

    return response()->json("nomor rekening sudah terdaftar, silahkan masukkan nomor rekening yang lain.");
  }
});


Route::post('/add-user-bank', function (Request $request) {

  $validator = Validator::make($request->all(), [
    'acc_no' => ['required', 'string'],
    'acc_type' => ['required', 'in:5,7'],
    'nama_rek' => ['required', 'string'],
    'new_bank' => ['required', 'string'],
  ]);


  if ($validator->fails()) {
    return response()->json(['error' => $validator->errors()->first()], 400);
  }

  $userId = auth()->id();

  $bankAccount = new BankAccount();
  $methodValue = ($request->input('acc_type') == 5) ? 'Bank' : 'E-Wallet';
  $bankAccount->method = $methodValue;
  $bankAccount->nama_rek = $request->input('nama_rek');
  $bankAccount->bank = $request->input('new_bank');
  $bankAccount->no_rek = $request->input('acc_no');
  $bankAccount->user_id = $userId;
  $bankAccount->save();

  $userBankAccounts = BankAccount::where('user_id', $userId)->get();

  $bankData = [];
  foreach ($userBankAccounts as $bankAccount) {

    $methodName = $bankAccount->method == 'Bank' ? 'Bank' : 'E-Wallet';
    $bankData[] = [
      "_id" => $bankAccount->id,
      "provider_name" => $bankAccount->bank,
      "acc_name" => $bankAccount->nama_rek,
      "acc_no" => "XXX - XXX - " . substr($bankAccount->no_rek, -4),
      "method" => $bankAccount->method,
      "status" => 1,
      "created_at" => $bankAccount->created_at->format('U'),
      "method_name" => $methodName,
      "acc_no_fmt" => $bankAccount->no_rek,
      "id" => $bankAccount->bank
    ];
  }

  return response()->json([
    "m" => "Pembarui Berhasil",
    "reload" => true
  ]);
});

Route::get('/maintenance', [MaintenanceController::class, 'index'])->name('maintenance');

Route::get('/regaccform', [UserDepositController::class, 'showRegAccForm'])->name('regaccform');

Route::post('/add-bank', [UserDepositController::class, 'tambahBank'])->name('tambahBank');

Route::post('/validate-captcha', [RegisterController::class, 'validateCaptcha']);

Route::get('/refresh-captcha', [RegisterController::class, 'refreshCaptcha']);

Route::post('/logout', [LoginController::class, 'logout'])->name('logout');


Route::get('/', function () {
  $setting = Setting::first();
  $customScripts = CustomScript::all(); // Mengambil semua data custom scripts

  if ($setting->template !== 'main') {
    return view('layouts.'.$setting->template.'.welcome', compact('customScripts'));
  }

  return view('welcome', compact('customScripts'));
});

Route::get('/ajaxmyPromo', function () {
  return view('ajaxMyPromo');
});

Route::get('/ajaxmyBonus', function () {
  return view('ajaxMyBonus');
});

Route::get('/registertest', function () {
  return view('auth.register');
});

Route::get('/register-success', function () {
  return view('register-success');
});

Route::get('/promo/my-promo', function () {
  return view('my-promo');
});

Route::get('/promotion', function () {
  $banners = BannerPromosi::all();
  return view('promosi', compact('banners'));
});

Route::get('/register2', function () {
  $banners = BannerPromosi::all();
  return view('auth.register', compact('banners'));
});

// info route
Route::get('/info/terms-terms_conditions', function () {
  return view('info.terms-terms_conditions');
});

Route::get('/info/faq-general', function () {
  return view('info.faq-general');
});

Route::get('/info/faq-deposit', function () {
  return view('info.faq-deposit');
});

Route::get('/info/faq-faq_withdrawal', function () {
  return view('info.faq-faq_withdrawal');
});

Route::get('/info/faq-games', function () {
  return view('info.faq-games');
});

Route::get('/info/faq-technical', function () {
  return view('info.faq-technical');
});

Route::get('/info/faq-banking', function () {
  return view('info.faq-banking');
});

Route::get('/info/how-sportsbook', function () {
  return view('info.how-sportsbook');
});

Route::get('/info/how-live_casino', function () {
  return view('info.how-live_casino');
});

Route::get('/info/how-slots', function () {
  return view('info.how-slots');
});

Route::get('/info/how-poker', function () {
  return view('info.how-poker');
});

Route::get('/info/referral', function () {
  return view('info.referral');
});

Route::get('/slots', function () {
  return view('games.slots.slots');
});

Route::get('/sports', function () {
  return view('sport');
});

Route::get('/casino', function () {
  // return view('casino');

  $game_list = new Game_list();

  return view('games.game_list', ['title' => 'Casino', 'game_list' => $game_list->get_game_list('PragmaticPlay', 'LC')]);
});

Route::get('/p2p', function () {
  return view('p2p');
});

Route::get('/fish-hunter', function () {
  return view('fish-hunter');
});

Route::get('/lottery', function () {
  return view('lotre');
});

Route::get('/e-games', function () {
  return view('e-games');
});

Route::get('/cockfight', function () {
  return view('cockfight');
});

Route::get('/slots/pragmatic-play', function () {
  return view('games.slots.pragmatic-play');
});

Route::get('/slots/pgsoft', function () {
  return view('games.slots.pgsoft');
});

Route::get('/slots/habanero', function () {
  return view('games.slots.habanero');
});

Route::get('/slots/microgaming', function () {
  return view('games.slots.microgaming');
});

Route::get('/slots/playstar', function () {
  return view('games.slots.playstar');
});

Route::get('/slots/joker-gaming', function () {
  return view('games.slots.joker');
});

Route::get('/slots/playngo', function () {
  return view('games.slots.playngo');
});

Route::get('/slots/spadegaming', function () {
  return view('games.slots.spadegaming');
});

// menu
Route::get('/memo', function () {
  return view('memo');
});

Route::get('/contact-us', function () {
  return view('contact-us');
});

Route::get('/complain', function () {
  return view('complain');
});

Route::get('/refferal', function () {
  return view('refferal');
});

Route::get('/game_api', function () {
  $game_api = new Game_api();
  // $game_api->pragmatic_create_users();
  // $game_api->pragmatic_start_game();

  // return view('refferal');
});

Route::get('/game_list', function () {

  $game_list = Game_list::where([
    'data_type' => 'RNG',
    'provider' => 'PragmaticPlay',
    'status' => 1
  ])->get();

  return view('games.game_list', ['title' => 'SLOT', 'game_list' => $game_list]);
});

Route::get('/game_list_new', function () {
  $game_list = Game_list::where('game_group_id', 'bet')->get();

  return view('games.game_list', ['title' => 'SLOT', 'game_list' => $game_list]);
});






Route::get('/game_process', function (Request $request) {
  $game_id = $request->input('game_code');
  $provider = $request->input('provider');

  $game_data = Game_list::where([
    'game_code' => $game_id,
    'game_provider' => $provider,
  ])->first();

  if ($game_data) {
    $user = Auth::user(); // Ambil data user yang sedang login
    $extplayer = $user->extplayer; // Ambil nilai extplayer dari user yang sedang login

    $game_url = GameApi::playGame($extplayer, $game_data->game_code, $game_data->game_provider);

    $endpoint = GameApi::playGame($extplayer, $game_data->game_code, $game_data->game_provider);
    $response = Http::get($endpoint);

    if ($response->successful()) {
      $hasil = $response->json();
      if ($hasil['status'] == "success") {
        $playUrl = $hasil['gameUrl'];
        return redirect()->away($playUrl);
      } else {
        return response()->json(['error' => 'Failed to launch game'], 400);
      }
    } else {
      return redirect()->back()->with('error', 'Failed to launch game');
    }
  }
});


Route::get('/game_api_balance',
  function () {
    $game_api = new Game_api();
    $game_api->pragmatic_get_balance_pp();
  });

Route::get('/game_api_pg',
  function () {
    $game_api = new Game_api();
    $game_api->pgsoft_create_user();
  });

Route::get('/game_api_pg_start',
  function (Request $request) {
    $game_api = new Game_api();

    $game_id = $request->game_id;
    $game_api->pgsoft_start_game($game_id);
  });

Route::post('/admin_login',
  function () {
    $game_api = new Game_api();
    $game_api->pragmatic_get_balance_pp();
  });

Route::get('/pp_new_game',
  function () {
    $game_api = new Game_api();
    $game_api->pragmatic_create_users();
  });

Route::get('/pgsoft_wd',
  function () {
    $game_api = new Game_api();
    $game_api->pgsoft_check_balance(auth()->user()->id);
  });


Route::get('/username_phone',
  function (Request $request) {

    $username = addslashes(base64_decode($request->username));
    $phone = addslashes(base64_decode($request->phone));

    // check  current username
    $data_name = User::where([
      'name' => $username
    ])->first();

    // check current phone number
    $data_phone = User::where([
      'telp' => $phone
    ])->first();


    // true is avail
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
      'username' => empty($data_name),
      'phone' => empty($data_phone)
    ]);
  });


#endregion
Route::group(['middleware' => 'auth'],
  function () {



    // ROUTE USER
    Route::resource('/account/deposit', UserDepositController::class);
    Route::get('/account/load_methods_form', [UserDepositController::class, 'loadMethodForm'])->name('load_methods_form');
    Route::get('/account/load_deposit_form', [UserDepositController::class, 'loadDepositForm'])->name('load_deposit_form');

    Route::get('/account/load_deposit_form_ewallet', [UserDepositController::class, 'loadDepositFormEwallet'])->name('load_deposit_form_ewallet');

    Route::get('/account/load_deposit_form_qris', [UserDepositController::class, 'loadDepositFormQris'])->name('load_deposit_form_qris');

    Route::get('/account/load_deposit_form_pulsa', [UserDepositController::class, 'loadDepositFormPulsa'])->name('load_deposit_form_pulsa');

    Route::get('/getBal', [SaldoController::class, 'get_saldo']);
    Route::get('/getRefWalletBal', [SaldoController::class, 'get_saldo_referral']);


    Route::post('/checkWalletAmount', [UserWithdrawController::class, 'checkWalletAmount']);

    Route::resource('/account/withdrawal', UserWithdrawController::class);
    Route::resource('/account/lastDirectTransfer', UserHistoryController::class);
    Route::resource('/account/history', UserPernyataanController::class);

    // Route::get('/account/load_deposit_form', [UserDepositController::class, 'loadDepositForm'])->name('account.load_deposit_form');

    Route::get('/account/load_bank_info', [UserDepositController::class, 'loadBankInfo'])->name('account.load_bank_info');

    Route::group(['prefix' => 'api'], function () {
      Route::post('/promo_details', [BonusController::class, 'getPromoDetails']);
      Route::post('/add_bonus', [BonusController::class, 'addBonus']);
    });

    Route::post('/get_bank_info', [UserDepositController::class, 'getBankInfo'])->name('get_bank_info');

    Route::post('/deposit-bank-details', [UserDepositController::class, 'getBankDetails']);

    Route::post('/deposit-ewallet-details', [UserDepositController::class, 'getEwalletDetails']);

    Route::post('/deposit-qris-details', [UserDepositController::class, 'getQrisDetails']);

    Route::post('/deposit-pulsa-details', [UserDepositController::class, 'getPulsaDetails']);

    Route::post('/promo_details', [UserDepositController::class, 'getPromoDetails']);

    Route::get('/account/load_methods_form', [UserDepositController::class, 'loadMethodsForm']);

    Route::get('/ajax-login', 'Auth\LoginController@ajaxLogin')->name('ajax.login');

    Route::get('/ajaxprofileEdit', function () {
      return view('profile_edit');
    });

    Route::get('/ajaxchgPass', function () {
      return view('change_password');
    });

    Route::post('/ajaxchgPass', function(Request $request) {
      $current_user = Auth::user();

      header('Content-Type: application/json; charset=utf-8');
      // password fullfiled
      if (Hash::check($request->currentPwd, $current_user->password)) {
        $data_user = Auth::user();
        $data_user->password = Hash::make($request->newPwd);
        $data_user->save();

        echo json_encode([
          'error' => false,
          'msg' => "Password telah berhasil diubah"
        ]);
      } else {
        echo json_encode([
          'error' => true,
          'msg' => "Password Tidak Sesuai, Coba ulangi kembali"
        ]);
      }
    });



    // Route untuk memeriksa ketersediaan username
    Route::post('/checkUserNameAvailability',
      [UserController::class,
        'checkUserNameAvailability']);

    // Route untuk memeriksa ketersediaan email
    Route::post('/checkExistingEmail',
      [UserController::class,
        'checkExistingEmail']);

    // Route untuk memeriksa ketersediaan nomor ponsel
    Route::post('/checkExistingMobile',
      [UserController::class,
        'checkExistingMobile']);

    Route::get('/pokerjp',
      'App\Http\Controllers\PokerController@getJackpot');

  });
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');