<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Bonus;
use App\Models\BonusLedger;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class SpinController extends Controller
{
    public function submitBonusCodeconfirm(Request $request)
    {
        // Validasi input
        $validator = Validator::make($request->all(), [
            'code' => 'required'
        ]);

        if ($validator->fails()) {
            return redirect()->back()->with('error', 'Kode harus diisi.');
        }

        $user = Auth::user();
        $code = $request->code;

        // Ambil bonus aktif
        $bonus = Bonus::where('status', 'active')->first();

        if (!$bonus) {
            return redirect()->back()->with('error', 'Tidak ada bonus aktif saat ini.');
        }

        if ($code !== $bonus->code) {
            return redirect()->back()->with('error', 'Kode yang dimasukkan salah.');
        }

        // Cek apakah user sudah pakai kode ini sebelumnya
        $used = BonusLedger::where('bonus_id', $bonus->id)
            ->where('user_id', $user->id)
            ->exists();

        if ($used) {
            return redirect()->back()->with('error', 'Kamu sudah pernah menggunakan kode ini.');
        }

        // Cek apakah kuota bonus masih ada
        if ($bonus->counter >= $bonus->set_service_counter) {
            return redirect()->back()->with('error', 'Kuota bonus hari ini sudah habis.');
        }

        // Tambahkan bonus ke saldo user
        $user->deposit_wallet += $bonus->amount;
        $user->save();

        // Tambah counter bonus
        $bonus->counter++;
        $bonus->save();

        // Catat pemakaian bonus ke BonusLedger
        $bonusLedger = new BonusLedger();
        $bonusLedger->user_id = $user->id;
        $bonusLedger->bonus_id = $bonus->id;
        $bonusLedger->bonus_code = $code;
        $bonusLedger->save();

        // Notif sukses
        return redirect()->back()->with('success', 'Kode berhasil digunakan! Saldo kamu bertambah Rp' . number_format($bonus->amount, 0, ',', '.'));
    }
}