<?php

use App\Models\UserNotification;
use App\Models\AdminNotification;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\ImageController;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\ServiceCategory;
use App\Models\ServiceProvider;
use App\Models\User;
use App\Models\UserBalanceLog;
use App\Models\UserLoginLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Jenssegers\Agent\Agent;

Route::get('tes-ip', function () {
    return dd(request()->ip());
});

Route::post('callback/dana', function(Request $request) {

    Log::info(json_encode($request->all()));

    $name = trim($request->input('name'));
    $package = trim($request->input('pkg'));
    $message = trim($request->input('text'));
    $signature = trim($request->input('signature'));
        
    if (!$name || !$package || !$message || !$signature) {
        Log::error("Invalid parameter");
        return response()->json(['error' => 'Invalid parameter'], 400);
    }

    $privateSignature = "BANGTEDDY";

    if (strtolower($name) != "dana" || strtolower($package) != "id.dana") {
        Log::error("Invalid package name");
        return response()->json(['error' => 'Invalid package name'], 400);
    }

    if ($signature != $privateSignature) {
        Log::error("Invalid signature");
        return response()->json(['error' => 'Invalid signature'], 400);
    }
        
    $deposits = Deposit::whereIn('deposit_method_id', ['10', '11', '12'])
                   ->where('status', 'Pending')
                   ->get();
    foreach ($deposits as $deposit) {

        $check_user = User::find($deposit->user_id);

        if ($check_user && preg_match("/baru saja kirim DANA ke kamu Rp".currency($deposit->balance)."/i", $message)) {
            $deposit->update([
                'status'     => 'Success',
                'updated_at' => now()
            ]);

            $first_balance = $check_user->balance;
            $last_balance = $check_user->balance + $deposit->balance;

            $check_user->update([
                'balance' => $last_balance,
            ]);

            UserBalanceLog::create([
                'user_id'       => $deposit->user_id,
                'type'          => 'Plus',
                'action'        => 'Deposit',
                'amount'        => $deposit->balance,
                'first_balance' => $first_balance,
                'last_balance'  => $last_balance,
                'description'   => 'Deposit #'.$deposit->id.'.',
            ]);

            $result = ['success' => true];
        } else if($check_user && preg_match("/Berhasil top up saldo Rp".currency($deposit->balance)."/i", $message)) {
            $deposit->update([
                'status'     => 'Success',
                'updated_at' => now()
            ]);

            $first_balance = $check_user->balance;
            $last_balance = $check_user->balance + $deposit->balance;

            $check_user->update([
                'balance' => $last_balance,
            ]);

            UserBalanceLog::create([
                'user_id'       => $deposit->user_id,
                'type'          => 'Plus',
                'action'        => 'Deposit',
                'amount'        => $deposit->balance,
                'first_balance' => $first_balance,
                'last_balance'  => $last_balance,
                'description'   => 'Deposit #'.$deposit->id.'.',
            ]);

            $result = ['success' => true];
        } else {
            $result = ['success' => false, 'error' => 'User not found'];
        }
    }
});

Route::post('callback/gopay', function(Request $request) {

    Log::info(json_encode($request->all()));

    $name = trim($request->input('name'));
    $package = trim($request->input('pkg'));
    $message = trim($request->input('text'));
    $signature = trim($request->input('signature'));
        
    if (!$name || !$package || !$message || !$signature) {
        Log::error("Invalid parameter");
        return response()->json(['error' => 'Invalid parameter'], 400);
    }

    $privateSignature = "BANGTEDDY";

    if (strtolower($name) != "gojek" || strtolower($package) != "com.gojek.app") {
        Log::error("Invalid package name");
        return response()->json(['error' => 'Invalid package name'], 400);
    }

    if ($signature != $privateSignature) {
        Log::error("Invalid signature");
        return response()->json(['error' => 'Invalid signature'], 400);
    }
        
    $deposits = Deposit::whereIn('deposit_method_id', ['1'])
                   ->where('status', 'Pending')
                   ->get();
    foreach ($deposits as $deposit) {

        $check_user = User::find($deposit->user_id);

        if ($check_user && preg_match("/ngirimin Rp".currency($deposit->balance)."/i", $message)) {
            $deposit->update([
                'status'     => 'Success',
                'updated_at' => now()
            ]);

            $first_balance = $check_user->balance;
            $last_balance = $check_user->balance + $deposit->balance;

            $check_user->update([
                'balance' => $last_balance,
            ]);

            UserBalanceLog::create([
                'user_id'       => $deposit->user_id,
                'type'          => 'Plus',
                'action'        => 'Deposit',
                'amount'        => $deposit->balance,
                'first_balance' => $first_balance,
                'last_balance'  => $last_balance,
                'description'   => 'Deposit #'.$deposit->id.'.',
            ]);

            $result = ['success' => true];
        } else if($check_user && preg_match("/up saldo sebesar Rp".currency($deposit->balance)."/i", $message)) {
            $deposit->update([
                'status'     => 'Success',
                'updated_at' => now()
            ]);

            $first_balance = $check_user->balance;
            $last_balance = $check_user->balance + $deposit->balance;

            $check_user->update([
                'balance' => $last_balance,
            ]);

            UserBalanceLog::create([
                'user_id'       => $deposit->user_id,
                'type'          => 'Plus',
                'action'        => 'Deposit',
                'amount'        => $deposit->balance,
                'first_balance' => $first_balance,
                'last_balance'  => $last_balance,
                'description'   => 'Deposit #'.$deposit->id.'.',
            ]);

            $result = ['success' => true];
        } else if($check_user && preg_match("/menerima GoPay sebanyak Rp".currency($deposit->balance)."/i", $message)) {
            $deposit->update([
                'status'     => 'Success',
                'updated_at' => now()
            ]);

            $first_balance = $check_user->balance;
            $last_balance = $check_user->balance + $deposit->balance;

            $check_user->update([
                'balance' => $last_balance,
            ]);

            UserBalanceLog::create([
                'user_id'       => $deposit->user_id,
                'type'          => 'Plus',
                'action'        => 'Deposit',
                'amount'        => $deposit->balance,
                'first_balance' => $first_balance,
                'last_balance'  => $last_balance,
                'description'   => 'Deposit #'.$deposit->id.'.',
            ]);

            $result = ['success' => true];
        } else {
            $result = ['success' => false, 'error' => 'User not found'];
        }
    }
});

/* Components Routes */
Route::group(['middleware' => ['web']], function () {
    Route::get('file/{folder}/{filename}', function ($folder, $filename) {
        $path = storage_path('app/public/'.$folder.'/');
        try {
            return response()->file($path.$filename);
        } catch (Exception $error) {
            return abort('404');
        }
    });
});
/* Components Routes */

/* Ajax Routes */
Route::group(['prefix' => 'ajax'], function() {
    Route::get('read_popup', function () {
        Session::forget('information_popup');
    });
    Route::get('admin/account/change-theme', [\App\Http\Controllers\AJAXController::class, 'change_theme_admin']);
    Route::get('account/change-theme', [\App\Http\Controllers\AJAXController::class, 'change_theme']);
    Route::get('service/detail', [\App\Http\Controllers\AJAXController::class, 'service_detail']);
    Route::get('service/favorite', [\App\Http\Controllers\AJAXController::class, 'service_favorite']);
    Route::get('create_api_key', [\App\Http\Controllers\AJAXController::class, 'create_api_key']);
    Route::get('service/list', [\App\Http\Controllers\AJAXController::class, 'service_list']);
    Route::get('service/category', [\App\Http\Controllers\AJAXController::class, 'service_category']);
    Route::get('service/price/bulk', [\App\Http\Controllers\AJAXController::class, 'service_price_bulk']);
    // Route::get('deposit/get_balance', [\App\Http\Controllers\AJAXController::class, 'deposit_get_balance']);
    Route::get('deposit/method/list', [\App\Http\Controllers\AJAXController::class, 'deposit_method_list']);
    Route::get('deposit/method/detail', [\App\Http\Controllers\AJAXController::class, 'deposit_method_detail']);

});
/* Ajax Routes */
