<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Services\JasaOtpService;
use App\Services\SmscodeService;

class BalanceController extends Controller
{
    public function index(Request $request)
    {
        $q = trim($request->get('q',''));

        // 🔹 Cari user berdasarkan ID atau Nama
        $users = User::when($q, fn($w) =>
    $w->where(function ($query) use ($q) {
        $query->where('id', 'like', "%{$q}%")
              ->orWhere('name', 'like', "%{$q}%")
              ->orWhere('email', 'like', "%{$q}%");
    })
)
->orderByDesc('balance')
->paginate(20)
->withQueryString();
        // 🔹 Total saldo semua user
     $totalUserBalance = User::where('reseller', 0)
    ->sum('balance') ?: 0;
        
try {
    $smscode = new SmscodeService(1);
    $saldoApiSmscode = $smscode->getBalance();
} catch (\Throwable $e) {
    $saldoApiSmscode = 0;
}

        // 🔹 Ambil saldo API JasaOTP dari service
        try {
            $jasaOtp = new JasaOtpService(1);
            $saldoApiJasaOtp = $jasaOtp->getBalance();
        } catch (\Throwable $e) {
            $saldoApiJasaOtp = 0;
        }

        return view('admin.balance', compact('users','q','totalUserBalance','saldoApiJasaOtp','saldoApiSmscode'));
    }

    public function adjust(Request $request)
    {
        $data = $request->validate([
            'user_id' => ['required','integer','exists:users,id'],
            'amount'  => ['required','numeric','min:1'],
            'action'  => ['required', Rule::in(['add','sub'])],
        ]);

        $user = User::findOrFail($data['user_id']);

        if ($data['action'] === 'add') {
            $user->balance += $data['amount'];
        } else {
            $user->balance = max(0, $user->balance - $data['amount']);
        }

        $user->save();

        return back()->with('success', 'Saldo berhasil diperbarui.');
    }
}
