<?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\ReferralController;


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\PaymentGatewayController;
use App\Http\Controllers\GameController;
use App\Http\Controllers\GameRtpController;




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 App\Http\Controllers\BalanceController;
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('/payment/jayapay/callback', [PaymentGatewayController::class, 'callback']);

Route::post('/jayapay/callback', [PaymentGatewayController::class, 'callback'])
    ->name('jayapay.callback');
    
Route::get('/getBal', [SaldoController::class, 'get_saldo']);
    
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::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('games.sport.sport');
});

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


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

});

Route::get('/casino/pragmatic', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'PRAGMATICLIVE')
        ->where('game_category', 'LIVE')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.casino.pragmatic', [
        'gamelist' => $gamelist
    ]);
});

Route::get('/casino/evo', function () {

    $gamelist = DB::table('fiver_games')
        ->where('game_provider', 'EVOLUTION')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.casino.evolution', [
        'gamelist' => $gamelist
    ]);
});

Route::get('/casino/ezugi', function () {

    $gamelist = DB::table('fiver_games')
        ->where('game_provider', 'EZUGI')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.casino.ezugi', [
        'gamelist' => $gamelist
    ]);
});

Route::get('/poker', function () {
  return view('games.poker.p2p');
});
Route::get('/live', function () {
  return view('games.live.live');
});
Route::get('/fish-hunter', function () {
  return view('games.fish-hunter.fish-hunter');
});

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

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

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

Route::get('/slots/pragmatic-play', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'PRAGMATIC')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderByRaw("
            CASE
                WHEN game_name LIKE '%Gates of Olympus%' THEN 1
                WHEN game_name LIKE '%Olympus%' THEN 2
                WHEN game_name LIKE '%Starlight%' THEN 3
                WHEN game_name LIKE '%Gatot%' THEN 4
                WHEN game_name LIKE '%Mahjong%' THEN 5
                ELSE 99
            END
        ")
        ->orderByDesc('id')
        ->get();

    return view('games.slots.pragmatic-play', [
        'gamelist' => $gamelist
    ]);
});

Route::get('/slots/pgsoft', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'PGSOFT') // samakan dengan data di DB kamu
        ->where('game_category', 'slot')
        ->where('status', 1)

        ->orderByRaw("
            CASE
                WHEN game_name LIKE '%Mahjong Ways%' THEN 1
                WHEN game_name LIKE '%Mahjong Ways 2%' THEN 2
                WHEN game_name LIKE '%Wild Bandito%' THEN 3
                WHEN game_name LIKE '%Wild Bounty%' THEN 4
                WHEN game_name LIKE '%Lucky Neko%' THEN 5
                ELSE 99
            END
        ")

        ->orderByDesc('id')
        ->get();

    return view('games.slots.pgsoft', [
        'gamelist' => $gamelist
    ]);
});



Route::get('/slots/habanero', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'HABANERO')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.habanero', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/fatpanda', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'FATPANDA')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.fatpanda', [
        'gamelist' => $gamelist
    ]);
});

Route::get('/slots/microgaming', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'MICROGAMING')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.microgaming', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/betsoft', function () {

    $maintenance = true; // ⛔ BETSOFT sedang maintenance

    if ($maintenance) {
        return view('games.slots.maintenance', [
            'provider' => 'BETSOFT'
        ]);
    }

});
Route::get('/slots/nextspin', function () {

    $maintenance = true; // ⛔ NEXTSPIN sedang maintenance

    if ($maintenance) {
        return view('games.slots.maintenance', [
            'provider' => 'NEXTSPIN'
        ]);
    }

});
Route::get('/slots/toptrend', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'TOPTREND')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.toptrend', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/cq9', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'CQ9')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.cq9', [
        'gamelist' => $gamelist
    ]);
});

Route::get('/slots/playstar', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'PLAYSON')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.playstar', [
        'gamelist' => $gamelist
    ]);
});

Route::get('/slots/joker-gaming', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'HABANERO')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.joker-gaming', [
        'gamelist' => $gamelist
    ]);
});

Route::get('/slots/playngo', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'PLAYNGO')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.playngo', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/hacksaw', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'HACKSAW')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.joker-gaming', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/spadegaming', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'SPADEGAMING')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.spadegaming', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/wowgaming', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'BOOONGO')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.wowgaming', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/booongo', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'BOOONGO')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.booongo', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/jili', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'CQ9')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.jili', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/evoplay', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'EVOPLAY')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.evoplay', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/sigma', function () {

    $maintenance = true; // ⛔ SIGMA sedang maintenance

    if ($maintenance) {
        return view('games.slots.maintenance', [
            'provider' => 'SIGMA'
        ]);
    }

});
Route::get('/slots/nolimitcity', function () {

    $maintenance = true; // ⛔ NOLIMITCITY sedang maintenance

    if ($maintenance) {
        return view('games.slots.maintenance', [
            'provider' => 'NOLIMIT'
        ]);
    }

});

Route::get('/slots/advantplay', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'DREAMTECH')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.advantplay', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/ygg', function () {

    $maintenance = true; // ⛔ YGG Drasil sedang maintenance

    if ($maintenance) {
        return view('games.slots.maintenance', [
            'provider' => 'YGG'
        ]);
    }

});

Route::get('/slots/fachai', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'FACHAI')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.fachai', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/jdb', function () {

    $maintenance = true; // ⛔ JDB sedang maintenance

    if ($maintenance) {
        return view('games.slots.maintenance', [
            'provider' => 'JDB'
        ]);
    }

});

Route::get('/slots/fastspin', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'FASTSPIN')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.fastspin', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/slots/playtech', function () {

    $gamelist = DB::table('fiver_games2')
        ->where('game_provider', 'EVOPLAY')
        ->where('game_category', 'slot')
        ->where('status', 1)
        ->orderBy('game_name')
        ->get();

    return view('games.slots.playtech', [
        'gamelist' => $gamelist
    ]);
});
Route::get('/game/rtp', [GameRtpController::class, 'get']);

Route::get('/game/rtp-all', function () {

    $rtp = DB::table('game_rtp')
        ->where('expired_at', '>', now())
        ->get()
        ->keyBy(function ($item) {
            return $item->game_code.'_'.$item->game_provider;
        });

    return response()->json($rtp);
});


Route::post('/game/launch', [GameController::class, 'connect_games'])
    ->middleware('auth')
    ->name('game.launch');
    
// menu
Route::get('/memo', function () {
  return view('memo');
});

// menu
Route::get('/member-level', function () {
  return view('member-level');
});

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

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

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


Route::post('/refferal', function () {
    return view('refferal'); // atau return partial ajax
});




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::post('/game/launch', [GameController::class, 'connect_games'])
    ->middleware('auth')
    ->name('game.launch');


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 () {

    /* ===============================
     * SALDO
     * =============================== */
    Route::get('/get-saldo', [SaldoController::class, 'get_saldo']);
    Route::get('/get-saldo-referral', [SaldoController::class, 'get_saldo_referral']);
    

    
/* ===============================
 * DEPOSIT (SIMPLE / ORIGINAL)
 * =============================== */
Route::resource('/account/deposit', UserDepositController::class);

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

Route::get('/account/load_deposit_form', [UserDepositController::class, 'loadDepositForm']);
Route::get('/account/load_deposit_form_ewallet', [UserDepositController::class, 'loadDepositFormEwallet']);
Route::get('/account/load_deposit_form_qris', [UserDepositController::class, 'loadDepositFormQris']);
Route::get('/account/load_deposit_form_pulsa', [UserDepositController::class, 'loadDepositFormPulsa']);

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']);
    /* ===============================
     * WITHDRAW
     * =============================== */
    Route::post('/checkWalletAmount', [UserWithdrawController::class, 'checkWalletAmount']);
    Route::resource('/account/withdrawal', UserWithdrawController::class);

    /* ===============================
     * HISTORY
     * =============================== */
    Route::resource('/account/lastDirectTransfer', UserHistoryController::class);
    Route::resource('/account/history', UserPernyataanController::class);
    
    Route::post('/create-payment', [PaymentGatewayController::class, 'createPayment'])->name('create-payment');
    Route::get('/payment/status', [PaymentGatewayController::class, 'statusPayment'])->name('status.payment');
    Route::get('/qrcode/show', function(Request $request) {
        $decodedUrl = base64_decode($request->encodedUrl);
        return redirect($decodedUrl);
    })->name('qrcode.show');
    Route::get('/payment/qris', [PaymentGatewayController::class, 'paymentQris'])->name('bayar.qris');
    Route::post('/payment/create', [PaymentGatewayController::class, 'createPayment'])->name('payment.create');
    Route::post('/jayapay/callback', [PaymentGatewayController::class, 'callback'])->name('jayapay.callback');
    Route::post('/jayapay/create', [PaymentGatewayController::class, 'createPayment'])->name('jayapay.create');
    Route::post('/jayapay/payment', [PaymentGatewayController::class, 'createPayment'])->name('jayapay.payment');

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

    /* ===============================
     * PROFILE / PASSWORD
     * =============================== */
     Route::get('/profile', function () {
    return view('profile_edit');
});
    Route::get('/ajaxprofileEdit', function () {
    return view('profile_edit');
});

Route::get('/ajaxchgPass', function () {
    return view('change_password');
});
    
    Route::get('/refferal', [ReferralController::class, 'downline']);

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

        if (\Hash::check($request->currentPwd, $user->password)) {
            $user->password = \Hash::make($request->newPwd);
            $user->save();

            return response()->json([
                'error' => false,
                'msg' => 'Password telah berhasil diubah'
            ]);
        }

        return response()->json([
            'error' => true,
            'msg' => 'Password tidak sesuai'
        ]);
    });

    /* ===============================
     * USER CHECK
     * =============================== */
    Route::post('/checkUserNameAvailability', [UserController::class, 'checkUserNameAvailability']);
    Route::post('/checkExistingEmail', [UserController::class, 'checkExistingEmail']);
    Route::post('/checkExistingMobile', [UserController::class, 'checkExistingMobile']);

    /* ===============================
     * POKER
     * =============================== */
    Route::get('/pokerjp', [PokerController::class, 'getJackpot']);

});

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