<?php

use Illuminate\Support\Facades\Route;
// === USER CONTROLLERS ===
use App\Http\Controllers\{
    DashboardController,
    OrderController,
    DepositController,
    ReferralController,
    ReferralWithdrawController,
    ChatController,
    BroadcastPopupController,
    OrderV2Controller
};


use App\Models\User;
use Illuminate\Http\Request; 
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Services\JasaOtpService;
use Carbon\Carbon;
use App\Services\SmscodeService;
use App\Http\Controllers\LeaderboardController;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Auth\AuthenticatedSessionController;


use App\Http\Controllers\TelegramWebhookController;
use App\Http\Controllers\TelegramCekIDWebhookController;
use App\Http\Controllers\TelegramFixMerahController;
// === ADMIN CONTROLLERS ===
use App\Http\Controllers\Admin\DashboardController as AdminDashboard;
use App\Http\Controllers\Admin\TransactionsController;
use App\Http\Controllers\Admin\DepositsController;
use App\Http\Controllers\Admin\BalanceController;
use App\Http\Controllers\Admin\ReferralsController;
use App\Http\Controllers\Admin\InformationController;
use App\Http\Controllers\Admin\UsersController;
use App\Http\Controllers\Admin\BalanceLogsController;
use App\Http\Controllers\Admin\BroadcastController;
use App\Http\Controllers\Admin\EmailBroadcastController;

// === LANDING / UMUM ===
Route::get('/', function () {
    return view('welcome');
});

Route::get('download-aplikasi', function () {
    return view('download');
});

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

    if (auth()->check()) {
        return redirect('/apk/dashboard');
    }

    return view('apk.splash');

});
// un comment jika mau pake blade dan hapus / komen kode dibawah

// Route::get('/', function () {
//     return response(file_get_contents(public_path('homepage.html')))
//         ->header('Content-Type', 'text/html')
//         ->header('Cache-Control', 'public, max-age=60');
// });



// === REGISTER DENGAN REFERRAL ===
Route::get('/register', function (Request $request) {
    if ($request->has('ref')) {
        // cari siapa pemilik kode referral
        $refUser = User::where('referral_code', $request->ref)->first();
        if ($refUser) {
            session(['referrer_id' => $refUser->id]);
        }
    }
    return app(RegisteredUserController::class)->create($request);
})->name('register');


// === ADMIN PANEL ===
        Route::middleware(['auth', 'admin', 'adminip'])
            ->prefix('admin')
            ->name('admin.')
            ->group(function () {
        Route::get('/dashboard', [AdminDashboard::class, 'index'])->name('dashboard');
        Route::get('/transactions', [TransactionsController::class, 'index'])->name('transactions');
        Route::delete('/transactions/{id}', [TransactionsController::class, 'destroy'])
            ->name('transactions.destroy');
        Route::get('/deposits', [DepositsController::class, 'index'])->name('deposits');
        Route::get('/balance', [BalanceController::class, 'index'])->name('balance');
        Route::get('/users', [\App\Http\Controllers\Admin\UsersController::class, 'index'])->name('users');
        Route::post('/users/update', [\App\Http\Controllers\Admin\UsersController::class, 'update'])->name('users.update');
        Route::post('/users/delete', [UsersController::class, 'delete'])->name('users.delete');
        Route::post('/balance/adjust', [BalanceController::class, 'adjust'])->name('balance.adjust');
        
        Route::get('/referrals', [ReferralsController::class, 'index'])->name('referrals');
        Route::post('/referrals/withdraw/{id}/approve', [ReferralsController::class, 'approveWithdraw'])
        ->name('referral.withdraw.approve');
        Route::post('/referrals/withdraw/{id}/reject', [ReferralsController::class, 'rejectWithdraw'])
        ->name('referral.withdraw.reject');
        Route::delete('/referrals/withdraw/{id}', [ReferralsController::class, 'deleteWithdraw'])
        ->name('referral.withdraw.delete');
        
        Route::get('/stats', [AdminDashboard::class, 'stats'])->name('stats');
        Route::get('/information', [InformationController::class, 'index'])->name('information');
        Route::post('/information', [InformationController::class, 'store'])->name('information.store');
        Route::get('/information/{id}/edit', [InformationController::class,     'edit'])->name('information.edit');
        Route::put('/information/{id}', [InformationController::class, 'update'])->name('information.update');
        Route::delete('/information/{id}', [InformationController::class, 'destroy'])->name('information.destroy');
        Route::get('/balance/logs', [BalanceLogsController::class, 'index'])->name('balance.logs');
        Route::post('/toggle-maintenance/{type}', [\App\Http\Controllers\Admin\DashboardController::class, 'toggleMaintenanceType'])
            ->name('toggleMaintenanceType');
        Route::resource('broadcasts', \App\Http\Controllers\Admin\BroadcastController::class);
        Route::get('/broadcast-email-user', [EmailBroadcastController::class, 'index'])
            ->name('emailbroadcast');
        Route::post('/broadcast-email-user/send', [EmailBroadcastController::class, 'send'])
             ->name('emailbroadcast.send');
        Route::get('/transactions/ajax', [TransactionsController::class, 'ajax'])
    ->name('transactions.ajax');
    });

    // ======================
// APK AUTH
// ======================

Route::prefix('apk')->group(function () {

    Route::middleware('guest')->group(function () {

        Route::get('/login', function () {
            return view('apk.login');
        })->name('apk.login');

        Route::post('/login', [AuthenticatedSessionController::class, 'store'])
            ->name('apk.login.store');

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

            return view('apk.register', [

                'refCode' => $request->query('ref')

            ]);

        })->name('apk.register');

        Route::post('/register', [RegisteredUserController::class, 'store'])

            ->name('apk.register.store');

        Route::get('/forgot-password', function () {

        return view('apk.forgot-password');

    })->name('apk.password.request');
    Route::post('/forgot-password', [
    \App\Http\Controllers\Auth\PasswordResetLinkController::class,
    'store'
])->name('apk.password.email');

    });

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

    Auth::guard('web')->logout();

    $request->session()->invalidate();

    $request->session()->regenerateToken();

    return redirect('/apk/login');

})->middleware('auth')->name('apk.logout');

});
// === APK ROUTE ===
Route::middleware('auth')->prefix('apk')->group(function () {

    Route::get('/dashboard', [DashboardController::class, 'index']);

    Route::get('/order', function () {
        return view('apk.order');
    });
    Route::post('/order/create', [OrderV2Controller::class, 'apiOrder']);

Route::get('/order/{id}', function ($id) {

    $order = \App\Models\Order::where('id', $id)
        ->where('user_id', auth()->id())
        ->firstOrFail();

    return view('apk.order-detail', compact('order'));

});

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

    $user = auth()->user();

    return view('apk.profile', compact('user'));

});
    Route::get('/riwayat-order', function (Request $request) {

    $orders = \App\Models\Order::where('user_id', auth()->id())
        ->where('provider', 'smscode')
        ->when(
            $request->status,
            fn ($q) => $q->where('status', $request->status)
        )
        ->latest()
        ->paginate(15);

    return view('apk.riwayat-order', compact('orders'));
});


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

        $deposits = \App\Models\Deposit::where(

            'user_id',

            auth()->id()

        )

        ->latest()

        ->limit(20)

        ->get();

        return view('apk.deposit', compact('deposits'));

    });
    Route::get('/riwayat-deposit', function (Request $request) {

    $deposits = \App\Models\Deposit::where(
        'user_id',
        auth()->id()
    )
    ->when($request->search, function ($q) use ($request) {

        $q->where('trx_id', 'like', '%'.$request->search.'%');

    })
    ->latest()
    ->paginate(15);

    return view('apk.riwayat-deposit', compact('deposits'));

});
Route::get('/referral', [ReferralController::class, 'apk'])
    ->name('apk.referral');

Route::get('/daftar-harga', function () {
    return view('apk.daftar-harga');
});
Route::get('/informasi', function () {
    return view('apk.informasi');
});
Route::get('/syarat-ketentuan', function () {
    return view('apk.syarat-ketentuan');
});
Route::get('/support', function () {
    return view('apk.support');
});
Route::get('/dokumentasi-api', function () {
    return view('apk.dokumentasi-api');
});
});


// === USER AREA ===
    Route::middleware(['auth'])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
    Route::get('/dashboard/chart-data', [DashboardController::class, 'chartData'])
    ->name('dashboard.chart');
    Route::get('/profile', [App\Http\Controllers\ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [App\Http\Controllers\ProfileController::class, 'update'])->name('profile.update');
    Route::get('/deposit', [DepositController::class, 'index'])->name('deposit');
    Route::post('/deposit', [DepositController::class, 'store'])->name('deposit.store');
    Route::post('/deposit/cancel/{trx}', [DepositController::class, 'cancel'])->name('deposit.cancel');
    Route::get('/deposit/status/{trx}', function($trx){
    $d = \App\Models\Deposit::where('trx_id', $trx)->first();
    return ['status' => $d->status ?? 'UNKNOWN'];
    
    });
Route::view('/dokumentasi-api', 'docs.index')->name('dokumentasi-api');
Route::view('/dokumentasi-api/v1', 'docs.v1')->name('dokumentasi-api.v1');
Route::view('/dokumentasi-api/v2', 'docs.v2')->name('dokumentasi-api.v2');
    Route::get('/order', [OrderController::class, 'index'])->name('order');
    Route::post('/order', [OrderController::class, 'store'])->name('order.store');
    Route::get('/order/{id}', [OrderController::class, 'show'])->name('order.show');
    Route::prefix('orderv2')->middleware('auth')->group(function () {

    Route::get('/', [OrderV2Controller::class, 'index'])->name('orderv2.index');

    Route::get('/services/{country}', [OrderV2Controller::class, 'services']); // ✅ FIX

    Route::get('/products/{country}/{platform}', [OrderV2Controller::class, 'products']);

    Route::post('/store', [OrderV2Controller::class, 'store'])->name('orderv2.store');

    Route::get('/{id}', [OrderV2Controller::class, 'show'])->name('orderv2.show');

    Route::get('/check/{id}', [OrderV2Controller::class, 'checkOtp']);

    Route::post('/cancel/{id}', [OrderV2Controller::class, 'cancel']);
    
});

    Route::get('/riwayat', [OrderController::class, 'riwayat'])->name('riwayat');
    Route::get('/chat', [ChatController::class, 'index'])->name('chat.index');
    Route::post('/chat/send', [ChatController::class, 'send'])->name('chat.send');
    Route::get('/chat/latest', [ChatController::class, 'latest'])->name('chat.latest');
    Route::get('/chat', [ChatController::class, 'index'])->name('chat.index');
    Route::post('/chat/send', [ChatController::class, 'send'])->name('chat.send');
    Route::get('/broadcast/popup', [BroadcastPopupController::class, 'latest'])->name('broadcast.popup');
    Route::get('/broadcast/list', [BroadcastPopupController::class, 'list'])->name('broadcast.list');

    // AJAX Helpers
    
    Route::get('/ajax/operators/{negara}', [OrderController::class, 'operators'])->name('ajax.operators');
    Route::get('/ajax/services/{negara}', [OrderController::class, 'services'])->name('ajax.services');
    Route::get('/ajax/order/{id}/otp', [OrderController::class, 'checkOtp'])->name('ajax.order.otp');
    Route::post('/ajax/order/{id}/cancel', [OrderController::class, 'cancel'])->name('ajax.order.cancel');
    Route::get('/ajax/orders/status', [\App\Http\Controllers\OrderController::class, 'statusList'])
    ->name('ajax.orders.status');
    Route::get('/ajax/countries', function () {
        try {
            $service = new JasaOtpService(1);
            $res = $service->getCountries();
            $list = [];
            if (isset($res['data'])) {
                foreach ($res['data'] as $id => $nama) {
                    $list[] = [
                        'id_negara' => $id,
                        'nama_negara' => is_array($nama) ? ($nama['nama_negara'] ?? $id) : $nama
                    ];
                }
            } elseif (is_array($res)) {
                foreach ($res as $id => $nama) {
                    if (is_array($nama)) {
                        $list[] = [
                            'id_negara' => $nama['id_negara'] ?? $id,
                            'nama_negara' => $nama['nama_negara'] ?? $id
                        ];
                    } else {
                        $list[] = ['id_negara' => $id, 'nama_negara' => $nama];
                    }
                }
            }
            return response()->json(['success' => true, 'data' => $list]);
        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil negara: '.$e->getMessage(),
                'data' => []
            ]);
        }
    });
    Route::get('/ajax/layanan/{negara}', function ($negara, Request $request) {
    try {
        $server = (int)$request->get('server', 1);
        $service = new JasaOtpService($server);
        $res = $service->getServices($negara);
        $list = [];
        if (isset($res[$negara])) {
            foreach ($res[$negara] as $kode => $item) {
                $list[] = [
                    'kode' => $kode,
                    'layanan' => $item['layanan'] ?? $kode,
                    'harga' => (int)($item['harga'] ?? 0),
                ];
            }
        } elseif (isset($res['data'][$negara])) {
            foreach ($res['data'][$negara] as $kode => $item) {
                $list[] = [
                    'kode' => $kode,
                    'layanan' => $item['layanan'] ?? $kode,
                    'harga' => (int)($item['harga'] ?? 0),
                ];
            }
        }
        return response()->json(['success' => true, 'data' => $list]);
    } catch (\Throwable $e) {
        return response()->json([
            'success' => false,
            'message' => $e->getMessage(),
            'data' => []
        ]);
    }
});

    Route::get('/referral', [ReferralController::class, 'index'])->name('referral');
    Route::post('/referral/withdraw', [ReferralWithdrawController::class, 'withdraw'])->name('referral.withdraw');
        Route::get('/ajax/informasi-popup', function () {
        $infos = \App\Models\Information::latest()->take(3)->get();
        if ($infos->isEmpty()) return '';

        $html = '<div class="text-left space-y-4">';
        foreach ($infos as $info) {
            $html .= '<div style="padding:10px 0;border-bottom:1px solid #eee;">';
            $html .= '<h3 style="font-weight:600;color:#1e3a8a;margin-bottom:4px;">'
                     . e($info->title) . '</h3>';
            $content = preg_replace(
                '/(https?:\/\/[^\s<]+)/i',
                '<a href="$1" target="_blank" style="color:#2563eb;text-decoration:underline;">$1</a>',
                e($info->content)
            );
            $html .= '<div style="color:#333;white-space:pre-line;">' . nl2br($content) . '</div>';
            $html .= '<div style="text-align:right;color:#777;font-size:12px;margin-top:6px;">'
                     . $info->created_at->format('d M Y, H:i') . '</div>';
            $html .= '</div>';
        }
        $html .= '</div>';
        return $html;
    })->name('informasi.popup');
});
    Route::get('/notif/recent-orders', function() {

    $since = \Carbon\Carbon::now()->subMinutes(1);

    $orders = \Illuminate\Support\Facades\Cache::remember('recent_orders', 5, function () use ($since) {
        return \App\Models\Order::where('created_at', '>=', $since)
            ->whereIn('status', ['SUCCESS', 'PENDING', 'FAILED'])
            ->orderBy('id', 'asc')
            ->limit(10) 
            ->get([
                'id',
                'layanan_nama as service',
                'number',
                'harga',
                'status',
                'created_at'
            ]);
    });

    return response()->json($orders);

})->name('notif.recent');
    Route::get('/daftar-harga', function () {
    return view('daftar-harga.index');
    })->name('daftar.harga');
    Route::view('/syarat', 'syarat')->name('syarat');
    Route::view('/about', 'about')->name('about');
    Route::view('/informasi', 'informasi')->name('informasi');
    Route::view('/daftar-harga-v2', 'daftar-harga.indexv2')
    ->name('daftar-harga.v2');
Route::get('/notif/recent-deposits', [DepositController::class, 'recentDeposits']);
Route::any('/docs/{any?}', function () {
    abort(404);
})->where('any', '.*');
// =======================
// 🔐 AJAX (AMAN)
// =======================

// COUNTRIES
Route::get('/ajax/smscode/countries', function (SmscodeService $api) {
    return response()->json($api->getCountries());
});

// SERVICES
Route::get('/ajax/smscode/services/{country}', function ($country, SmscodeService $api) {
    return response()->json($api->getServices((int)$country));
});

// PRODUCTS (HARGA)
Route::get('/ajax/smscode/products', function (Request $req, SmscodeService $api) {
    return response()->json(
        $api->getProducts(
            (int)$req->country,
            (int)$req->service
        )
    );
});

// Callback
    Route::match(['GET', 'POST'], 'payment/tokopay/callback', [DepositController::class, 'callback'])
    ->withoutMiddleware([\App\Http\Middleware\VerifyCsrfToken::class])
    ->name('callback.pga');

//BLOG
Route::get('/tutorial-whatsapp-dengan-nokos', function () {
    return view('blog.tutorialwa');
})->name('blog.tutorialwa');

Route::get('/cara-isi-saldo-nusaotp', function () {
    return view('blog.tutorialdeposit');
})->name('blog.tutorialdeposit');
//OTHER

Route::get('/top-services', [LeaderboardController::class, 'index'])
    ->name('top-services');
Route::post('/telegramcekid/webhook', [TelegramCekIDWebhookController::class, 'webhook'])
    ->withoutMiddleware([
        \Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class
    ]);
    
Route::post('/telegram/webhook', [TelegramWebhookController::class, 'handle'])
    ->withoutMiddleware([
        \App\Http\Middleware\VerifyCsrfToken::class
    ]);
Route::prefix('telegram/fixmerah')->group(function () {

    Route::post('/webhook', [TelegramFixMerahController::class, 'webhook'])
        ->withoutMiddleware([
            \App\Http\Middleware\VerifyCsrfToken::class
        ]);

});
Route::get('/telegram/login/{token}', function ($token) {

    $data = Cache::get('telegram_login_'.$token);

    if (!$data) {
        abort(403, 'Token expired');
    }

    $telegramId = $data['telegram_id'];

    $user = \App\Models\User::where('telegram_id', $telegramId)->first();

    if (!$user) {

        $user = \App\Models\User::create([
            'name' => $data['name'],

            'telegram_id' => $telegramId,

            'telegram_username' => $data['username'],

            'email' => 'tg_'.$telegramId.'@telegram.local',

            'password' => bcrypt(Str::random(40)),
        ]);
    }

    Auth::login($user);

    Cache::forget('telegram_login_'.$token);

    return redirect('/dashboard');
});
    require __DIR__.'/auth.php';
