<?php

namespace App\Http\Controllers\API\V4;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\DB;
use App\Models\Store;
use App\Models\Sale;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\File;
use App\Plans;
use App\Models\Permission;

class UserController extends Controller
{
     public function getUser(Request $request)
    {
        $key = $request->query('UserKey');

        if (!$key) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'UserKey parameter is required',
            ]);
        }

        // Find user by id_session (UserKey) 
        $user = User::where('id_session', $key)->first();

        if (!$user) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'User Not Found',
            ]);
        }

        // Get master account
        $master = User::where('phone_number', $user->master)->first();

        if (!$master) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'Master account not found',
            ]);
        }

        // Get plan info for master
        $plan = Plans::find($master->plan_id);

        // Get staff users for master (not blocked)
        $staffUsers = User::where('master', $master->phone_number)
            ->where('blokir', 'N')
            ->orderBy('name', 'ASC')
            ->get();

        if ($staffUsers->isEmpty()) {
            return response()->json([
                'status' => 'true',
                'errCode' => '02',
                'msg' => 'No Employee',
            ]);
        }

        $response = [];
        foreach ($staffUsers as $staff) {
            // Get related store
            //$store = Store::find($staff->id_store);

            // Get permissions for staff
            $permissions = Permission::where('user_id', $staff->id)->first();

            // Subscription end date fallback
            $subEnd = $master->sub_ends_at ?: '2020-07-02 13:36:30';

            $response[] = [
                'userkey' => $staff->id_session,
                'local_id' => $staff->local_id,
                'cloud_id' => $staff->id,
                'full_name' => $staff->name,
                'city' => $staff->city,
                'address' => $staff->address,
                'email' => $staff->email,
                'level' => $staff->level,
                'master' => $staff->master,
                'phone_number' => $staff->phone_number,
                'salary' => $staff->salary_fixed,
                'commission' => $staff->commission,
                'allowance' => $staff->allowance,
                'id_store' => $staff->id_store,
                'blokir' => $staff->blokir,
                'phone' => $staff->phone,
                'created_at' => $staff->created_at,
                'sub_ends_at' => $subEnd,
                'plan_status' => $master->plan_status,
                'referal' => $staff->referal,
                'date_upgrade' => $master->date_upgrade,
                'plan_id' => $master->plan_id,
                'img' => "https://{$request->getHttpHost()}/uploads/restorants/{$staff->img}",
                'updated_at' => $staff->updated_at_long,

                // Permissions mapped to booleans, handle if $permissions is null
                'permTransactions' => (bool) $permissions->perm_transactions,
                'permCheckoutPrice'=> (bool) $permissions->perm_checkout_price,
                'permDiscountTax'  => (bool) $permissions->perm_discount_tax,
                'permProductReports'=> (bool) $permissions->perm_product_reports,
                'permSalesReports' => (bool) $permissions->perm_sales_reports,
                'permDailyReports' => (bool) $permissions->perm_daily_reports,
                'permFinancialState'=> (bool) $permissions->perm_financial_state,
                'permUsers'        => (bool) $permissions->perm_users,
                'permProducts'     => (bool) $permissions->perm_products,
                'permInventory'    => (bool) $permissions->perm_inventory,
                'permOnlineStore'  => (bool) $permissions->perm_online_store,
                'permOnlineOrders' => (bool) $permissions->perm_online_orders,
                'permSettings'     => (bool) $permissions->perm_settings,
                'permExpences'     => (bool) $permissions->perm_expences,
                'permPurchase'     => (bool) $permissions->perm_purchase,
                'permSuppliers'    => (bool) $permissions->perm_suppliers,
            ];
        }

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

    public function getPlans(Request $request)
{
    

    $plans = Plans::all();

    if ($plans->isEmpty()) {
        return response()->json([
            'status' => 'true',
            'errCode' => '02',
            'msg' => 'No Plans'
        ]);
    }

    $response = $plans->map(function ($plan) {
        return [
            'id' => $plan->id,
            'name' => $plan->name,
            'limitItems' => $plan->limit_items,
            'limitBranch' => $plan->limit_branch,
            'limitStaff' => $plan->limit_staff,
            'limitOrders' => $plan->limit_orders,
            'price' => $plan->price,
            'annualPrice' => $plan->annual_price,
            'period' => $plan->period,
            'paddleId' => $plan->paddle_id,
            'createdAt' => $plan->created_at,
            'updatedAt' => $plan->updated_at,
            'description' => $plan->description,
            'features' => 'features',
            'limitViews' => $plan->limit_views,
            'enableOrdering' => $plan->enable_ordering == 1,
            'enableWebsite' => $plan->enable_website == 1,
            'enableInventory' => $plan->enable_inventory == 1,
            'enablePDFReport' => $plan->enable_pdf_report == 1,
            'enablePDFReceipt' => $plan->enable_pdf_receipt == 1,
            'enablePaymentGateway' => $plan->payment_gateway == 1,
            'enableDelivery' => $plan->enable_delivery == 1,
            'enablePrintReceipt' => $plan->enable_print_receipt == 1,
            'enableDebtPayLater' => $plan->enable_debt_paylater == 1,
            'enableReport' => $plan->enable_report == 1,
            'enableFinancial' => $plan->enable_financial == 1,
            'enableDigitalReceipt' => $plan->enable_digital_receipt == 1,
            'enableTracking' => $plan->enable_tracking == 1,
            'enableStockTransfer' => $plan->enable_stock_transfer == 1,
            'enableDisplay' => $plan->enable_display == 1,
            'enableDomain' => $plan->enable_domain == 1,
            'enableTaxes' => $plan->enable_taxes == 1,
            'enableTaskManage' => $plan->enable_task_manage == 1,
            'enableMedicalRecord' => $plan->enable_medical_record == 1,
            'enableWhatsApp' => $plan->enable_whatsapp == 1,
            'customers' => $plan->customers,
            'filterLimit' => $plan->filterLimit == 1,
            'todoList' => $plan->todoList == 1,
        ];
    });

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



public function getUserProfile(Request $request)
{
    $key = $request->query('key');

    $user = DB::table('users')->where('id_session', $key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'true',
            'errCode' => '00',
            'msg' => 'User Not Found'
        ]);
    }

    $master = DB::table('users')->where('phone_number', $user->master)->first();
    $plan = DB::table('plan')->where('id', $master->plan_id ?? 0)->first();

    $omsetResult = DB::table('sales_data')
        ->where('operator', $user->phone_number)
        ->whereNotIn('status', ['cancel'])
        ->select(DB::raw('SUM(totalorder) as total'))
        ->first();

    $omset = $omsetResult->total ?? 0;

    $company = DB::table('companies')->where('userz', $master->phone_number)->first();

    $configKeys = ['paystack_secretKey', 'paypal_client_id', 'paypal_secret', 'flutterwave_public_key', 'razorpay_key', 'razorpay_secret'];
    $configs = DB::table('configs')
        ->where('model_id', $company->id)
        ->whereIn('key', $configKeys)
        ->pluck('value', 'key');

    $myDate1b = now()->startOfMonth()->toDateString();
    $myDate2b = now()->endOfMonth()->toDateString();

    $transaksi = DB::table('sales_data')
        ->where('id_store', $user->id_store)
        ->whereNotIn('status', ['cancel'])
        ->whereBetween('date', [$myDate1b, $myDate2b])
        ->sum('totalorder');

    $order = DB::table('sales')
        ->where('id_store', $user->id_store)
        ->whereNotIn('status', ['cancel'])
        ->whereBetween('date', [$myDate1b, $myDate2b])
        ->sum('amount');

    $subdomain = "https://{$company->subdomain}.ontrack.ng";
    $signup = "https://{$request->getHttpHost()}/app/sign-{$company->subdomain}";
    $screen = "https://{$request->getHttpHost()}/screen/id-{$company->subdomain}";

    $users = DB::table('users')->where('id_session', $user->id_session)->get();

    if ($users->isEmpty()) {
        return response()->json([
            'status' => 'true',
            'errCode' => '02',
            'msg' => 'no data'
        ]);
    }

    $type = ($plan->id ?? 0) > 5 ? 'premium' : 'free';

    $data = $users->map(function ($x) use ($omset, $order, $transaksi, $subdomain, $signup, $screen, $configs, $type, $request) {
        return [
            'full_name' => $x->name,
            'address' => $x->address,
            'email' => $x->email,
            'phone_number' => $x->phone_number,
            'key' => $x->id_session,
            'afiliasi' => $x->afiliasi,
            'omset' => $omset,
            'saldo' => '',
            'subdomain' => $subdomain,
            'point' => '',
            'transaksi' => $transaksi,
            'order' => $order,
            'type' => $type,
            'paystackpk' => $configs['paystack_secretKey'] ?? 0,
            'paypalid' => $configs['paypal_client_id'] ?? 0,
            'paypalsecret' => $configs['paypal_secret'] ?? 0,
            'flutterpk' => $configs['flutterwave_public_key'] ?? 0,
            'razorpk' => $configs['razorpay_key'] ?? 0,
            'razorsk' => $configs['razorpay_secret'] ?? 0,
            'img' => url("uploads/restorants/{$x->img}"),
            'signup' => $signup,
            'screen' => $screen
        ];
    });

    return response()->json([
        'status' => 'true',
        'errCode' => '01',
        'msg' => 'Success',
        'data' => $data
    ]);
}


public function updateUserProfile(Request $request)
{
    $request->validate([
        'key' => 'required|string',
        'full_name' => 'required|string',
        'address' => 'required|string',
        'email' => 'required|email',
        'img' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
    ]);

    $key = $request->input('key');
    $user = User::where('id_session', $key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'true',
            'errCode' => '00',
            'msg' => 'User Not Found',
        ]);
    }

    $user->name = $request->input('full_name');
    $user->address = $request->input('address');
    $user->email = $request->input('email');

   
     // Handle image upload to public directory
    if ($request->hasFile('img')) {
        $file = $request->file('img');
        $filename = 'small_' . rand(1, 99) . '_' . Str::slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . $file->getClientOriginalExtension();
        $destinationPath = public_path('uploads/restorants');

        // Create directory if it doesn't exist
        if (!File::exists($destinationPath)) {
            File::makeDirectory($destinationPath, 0755, true);
        }

        $file->move($destinationPath, $filename);
 
        $user->img = $filename;
        // Optional: delete the old image if needed
         Storage::delete('public/uploads/restorants/' . $user->img);
    }

    $user->save();

    return response()->json([
        'status' => 'true',
        'errCode' => '01',
        'msg' => 'Success',
    ]);
}




public function createStaff(Request $request)
{
    $validator = Validator::make($request->all(), [
        'key' => 'required|string',
        'email' => 'required|email|unique:users,email',
        'phone_number' => 'required|string|unique:users,phone_number',
        'full_name' => 'required|string',
        'id_store' => 'required|integer',
        'address' => 'nullable|string',
        'level' => 'required|string',
        'salary_fixed' => 'nullable|numeric',
        'commission' => 'nullable|numeric',
        'allowance' => 'nullable|numeric',
        'piece' => 'nullable|numeric',
        'img' => 'nullable|image|mimes:jpg,jpeg,png',
    ]);

    if ($validator->fails()) {
        return response()->json([
            'status' => 'true',
            'errCode' => '02',
            'msg' => $validator->errors()->first()
        ]);
    }

    $user = User::where('id_session', $request->key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'true',
            'errCode' => '00',
            'msg' => 'User Not Found'
        ]);
    }

    $master = User::where('phone_number', $user->master)->first();
    $plan = Plans::find($master->plan_id);

    $staffCount = User::where('master', $user->master)->where('blokir', 'N')->count();
    if ($staffCount >= $plan->limit_staff) {
        return response()->json([
            'status' => 'true',
            'errCode' => '01',
            'msg' => 'Maximum ' . $plan->limit_staff . ' employees, Please upgrade Plan'
        ]);
    }

    $passwordPlain = bin2hex(random_bytes(3));
    $hashedPassword = password_hash($passwordPlain, PASSWORD_DEFAULT, ['cost' => 13]);

    // Handle Image Upload
    $imageName = 'avatar.png';
    if ($request->hasFile('img')) {
        $imageName = uniqid() . '.' . $request->img->extension();
        $request->img->move(public_path('uploads'), $imageName);
    }

    $ids=md5(strip_tags($request->phone_number));
    // Create User
    $newUser = User::create([
        'name' => $request->full_name,
        'email' => $request->email,
        'password' => $hashedPassword,
        'phone_number' => $request->phone_number,
        'phone' => $request->phone_number,
        'id_store' => $request->id_store,
        'restaurant_id' => $user->restaurant_id,
        'address' => $request->address ?? '',
        'master' => $master->phone_number,
        'id_session' => $ids,
        'afiliasi' =>  Str::random(10),
        'api_token' => Str::random(80),
        'level' => $request->level,
        'salary_fixed' => $request->salary_fixed ?? 0,
        'commission' => $request->commission ?? 0,
        'allowance' => $request->allowance ?? 0,
        'piece' => $request->piece ?? 0,
        'img' => $imageName,
    ]);

    // Create permissions
    Permission::create([
        'user_id' => $newUser->id,
        'perm_transactions' => $request->boolean('perm_transactions'),
        'perm_checkout_price' => $request->boolean('perm_checkout_price'),
        'perm_discount_tax' => $request->boolean('perm_discount_tax'),
        'perm_product_reports' => $request->boolean('perm_product_reports'),
        'perm_sales_reports' => $request->boolean('perm_sales_reports'),
        'perm_daily_reports' => $request->boolean('perm_daily_reports'),
        'perm_financial_state' => $request->boolean('perm_financial_state'),
        'perm_users' => $request->boolean('perm_users'),
        'perm_products' => $request->boolean('perm_products'),
        'perm_inventory' => $request->boolean('perm_inventory'),
        'perm_online_store' => $request->boolean('perm_online_store'),
        'perm_online_orders' => $request->boolean('perm_online_orders'),
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    // Assign role
    DB::table('model_has_roles')->insert([
        'role_id'    => 2,
        'model_type'=> 'App\\User',
        'model_id'  => $newUser->id,
    ]);

    // Send email
    try {
        Mail::send([], [], function ($message) use ($request, $user, $passwordPlain) {
            $content = view('emails.new_user_account', [
                'fullname' => $user->name,
                'nama_lengkap' => $request->full_name,
                'email' => $request->email,
                'pwd' => $passwordPlain,
                'no_telp' => $request->phone_number
            ])->render();

            $message->from('info@ontrack.ng', 'OnTrack App')
                    ->to($request->email, $request->full_name)
                    ->subject('A New Account Just Created for you.')
                    ->setBody($content, 'text/html');
        });

        return response()->json([
            'status' => 'true',
            'errCode' => '01',
            'msg' => 'Success, login detail has been sent to the employee email'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'status' => 'true',
            'errCode' => '09',
            'msg' => 'Failed to send email. ' . $e->getMessage()
        ]);
    }
}



public function getStaffs(Request $request)
{
    $key = $request->query('key');

    $user = User::where('id_session', $key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'true',
            'errCode' => '00',
            'msg' => 'User Not Found'
        ]);
    }

    $master = User::where('phone_number', $user->master)->first();

    if (!$master) {
        return response()->json([
            'status' => 'true',
            'errCode' => '03',
            'msg' => 'Master User Not Found'
        ]);
    }

    $plan = Plans::find($master->plan_id);
    $cekStaff = User::where('master', $master->master)
                    ->where('blokir', 'N')
                    ->count();

    $staffUsers = User::where('master', $master->phone_number)
                    ->where('blokir', 'N')
                    ->where('level', '!=', 'master')
                    ->orderBy('name', 'asc')
                    ->get();

    if ($staffUsers->isEmpty()) {
        return response()->json([
            'status' => 'true',
            'errCode' => '02',
            'msg' => 'No Employee'
        ]);
    }

    $data = [];

    foreach ($staffUsers as $staff) {
        $store = Store::find($staff->id_store);

        $totalWork = Sale::where('operator', $user->phone_number)
                              ->where('status', '!=', 'cancel')
                              ->count();

        $workProcess = Sale::where('operator', $user->phone_number)
                                ->where('status', 'billing')
                                ->count();

        $workFinish = Sale::where('operator', $user->phone_number)
                               ->where('status', 'finish')
                               ->count();

        $workPaid = Sale::where('operator', $user->phone_number)
                             ->where('status', 'paid of')
                             ->count();

        $permissions = Permission::where('user_id', $staff->id)->first();

        $data[] = [
            'full_name'        => $staff->name,
            'id'               => $staff->id,
            'city'             => $staff->city,
            'address'          => $staff->address,
            'email'            => $staff->email,
            'level'            => $staff->level,
            'master'           => $staff->master,
            'phone_number'     => $staff->phone_number,
            'key'              => $staff->id_session,
            'salary'           => $staff->salary_fixed,
            'commission'       => $staff->commission,
            'allowance'        => $staff->allowance,
            'piece'            => $staff->piece,
            'id_store'         => $staff->id_store,
            'name_store'       => optional($store)->name_store,
            'total_work'       => $totalWork,
            'work_procces'     => $workProcess,
            'work_finish'      => $workFinish,
            'work_paid'        => $workPaid,
            'img'              => url("uploads/restorants/{$staff->img}"),
            'permTransactions' => (bool) $permissions->perm_transactions,
            'permCheckoutPrice'=> (bool) $permissions->perm_checkout_price,
            'permDiscountTax'  => (bool) $permissions->perm_discount_tax,
            'permProductReports'=> (bool) $permissions->perm_product_reports,
            'permSalesReports' => (bool) $permissions->perm_sales_reports,
            'permDailyReports' => (bool) $permissions->perm_daily_reports,
            'permFinancialState'=> (bool) $permissions->perm_financial_state,
            'permUsers'        => (bool) $permissions->perm_users,
            'permProducts'     => (bool) $permissions->perm_products,
            'permInventory'    => (bool) $permissions->perm_inventory,
            'permOnlineStore'  => (bool) $permissions->perm_online_store,
            'permOnlineOrders' => (bool) $permissions->perm_online_orders,
            'permSettings'     => (bool) $permissions->perm_settings,
            'permExpences'     => (bool) $permissions->perm_expences,
            'permPurchase'     => (bool) $permissions->perm_purchase,
            'permSuppliers'    => (bool) $permissions->perm_suppliers,
            
            'limit'            => ($cekStaff < ($plan->limit_staff ?? 0)) ? 'premium' : 'premium'
        ];
    }

    return response()->json([
        'status' => 'true',
        'errCode' => '01',
        'msg' => 'Success',
        'data' => $data
    ]);
}


public function updateStaff(Request $request)
{
    $request->validate([
        'key' => 'required|string',
        'email' => 'required|email',
        'phone_number' => 'required|string',
        'full_name' => 'required|string',
        'id_store' => 'required|integer',
        'address' => 'nullable|string',
        'level' => 'required|string',
        'salary_fixed' => 'nullable|numeric',
        'commission' => 'nullable|numeric',
        'allowance' => 'nullable|numeric',
        'piece' => 'nullable|numeric',
        'id' => 'required|integer',
        'img' => 'nullable|image|max:2048',
    ]);

    $user = User::where('id_session', $request->key)->first();

    if (!$user) {
        return response()->json([
            'status' => 'false',
            'errCode' => '00',
            'msg' => 'User Not Found'
        ]);
    }

    $existingUser = User::where('phone_number', $request->phone_number)->first();

    DB::beginTransaction();

    try {
        $targetUser = User::findOrFail($request->id);

        // Handle image upload
        if ($request->hasFile('img')) {
            $image = $request->file('img');
            $folder = now()->format('m-d-y-H');
            $filename = rand(1, 99) . $image->getClientOriginalName();
            $path = $image->storeAs("uploads/{$folder}", $filename, 'public');
            $targetUser->img = $path;
        }

        // Update user
        $targetUser->update([
            'name' => $request->full_name,
            'email' => $request->email,
            'phone_number' => $request->phone_number,
            'id_store' => $request->id_store,
            'address' => $request->address,
            'level' => $request->level,
            'salary_fixed' => $request->salary_fixed ?? 0,
            'commission' => $request->commission ?? 0,
            'allowance' => $request->allowance ?? 0,
            'piece' => $request->piece ?? 0,
        ]);

        // Update permissions
        Permission::updateOrCreate(
            ['user_id' => $targetUser->id],
            [
                'perm_transactions' => $request->boolean('perm_transactions'),
                'perm_checkout_price' => $request->boolean('perm_checkout_price'),
                'perm_discount_tax' => $request->boolean('perm_discount_tax'),
                'perm_product_reports' => $request->boolean('perm_product_reports'),
                'perm_sales_reports' => $request->boolean('perm_sales_reports'),
                'perm_daily_reports' => $request->boolean('perm_daily_reports'),
                'perm_financial_state' => $request->boolean('perm_financial_state'),
                'perm_users' => $request->boolean('perm_users'),
                'perm_products' => $request->boolean('perm_products'),
                'perm_inventory' => $request->boolean('perm_inventory'),
                'perm_online_store' => $request->boolean('perm_online_store'),
                'perm_online_orders' => $request->boolean('perm_online_orders'),
                'perm_settings' => $request->boolean('perm_settings'),
                'perm_expences' => $request->boolean('perm_expences'),
                'perm_purchase' => $request->boolean('perm_purchase'),
                'perm_suppliers' => $request->boolean('perm_suppliers'),
                'updated_at' => now()
            ]
        );

        DB::commit();

        return response()->json([
            'status' => 'true',
            'errCode' => '01',
            'msg' => 'Success'
        ]);

    } catch (\Exception $e) {
        DB::rollBack();

        return response()->json([
            'status' => 'false',
            'errCode' => '08',
            'msg' => $e->getMessage()
        ]);
    }
}


    /**
     * Block a user by phone number.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function blockUser(Request $request)
    {
        $key = $request->query('key');
        $phoneNumber = $request->query('phone_number');

        // Attempt to find user by session key
        $user = User::where('id_session', $key)->first();

        if ($user) {
            // Block the user by phone number
            User::where('phone_number', $phoneNumber)->update(['blokir' => 'Y']);

            return response()->json([
                'status' => 'true',
                'errCode' => '01',
                'msg' => 'Success'
            ]);
        } else {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'User Not Found'
            ]);
        }
    }


 public function searchUsers(Request $request)
    {
        $key = $request->query('key');
        $search = $request->query('search');

        $user = User::where('id_session', $key)->first();

        if (!$user) {
            return response()->json([
                'status' => 'true',
                'errCode' => '00',
                'msg' => 'User Not Found'
            ]);
        }

        $master = User::where('phone_number', $user->master)->first();

        if (!$master) {
            return response()->json([
                'status' => 'true',
                'errCode' => '02',
                'msg' => 'Master account not found'
            ]);
        }

        $results = User::where('name', 'like', '%' . $search . '%')
            ->where('master', $master->phone_number)
            ->where('blokir', 'N')
            ->whereNotIn('level', ['master'])
            ->orderBy('name', 'asc')
            ->get();

        if ($results->isEmpty()) {
            return response()->json([
                'status' => 'true',
                'errCode' => '02',
                'msg' => 'no data'
            ]);
        }

        $data = $results->map(function ($user) {
            return [
                'full_name' => $user->name,
                'city' => $user->city,
                'address' => $user->address,
                'email' => $user->email,
                'phone_number' => $user->phone_number,
                'key' => $user->id_session,
                'img' => url("uploads/restorants/{$user->img}"),
                'id_store' => $user->id_store,
                'id' => $user->id,
                'salary_fixed' => $user->salary_fixed,
                'commission' => $user->commission,
                'allowance' => $user->allowance,
                'piece' => $user->piece,
                'level' => $user->level,
                'blokir' => $user->blokir
            ];
        });

        return response()->json([
            'status' => 'true',
            'errCode' => '01',
            'msg' => 'Success',
            'data' => $data
        ]);
    }

}
