<?php

namespace App\Http\Controllers\user;

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

class GetBonusController extends Controller
{
    public function index()
    {
        // Fetch the first active bonus for display (optional)
        $data = Bonus::where('status', 'active')->first();
        return view('app.main.bonus.index', compact('data'));
    }

    public function gift()
    {
        return view('app.main.gift.index');
    }

    public function submitBonusCode(Request $request)
    {
        $request->validate([
            'bonus_code' => 'required'
        ]);

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

        // Bean Driving Logic: Check any active bonus that matches the entered code
        $bonus = Bonus::where('status', 'active')->where('code', $code)->first();

        if (!$bonus) {
            return redirect()->route('user.promo')->with('error', 'Invalid or expired gift code.');
        }

        // Check if the user has already used THIS specific bonus code
        $checkBonusUses = BonusLedger::where('bonus_id', $bonus->id)->where('user_id', $user->id)->first();
        if ($checkBonusUses) {
            return redirect()->route('user.promo')->with('error', 'You have already used this code.');
        }

        // Check if the total usage limit for this code is reached
        if ($bonus->counter >= $bonus->set_service_counter) {
            return redirect()->route('user.promo')->with('error', 'This code usage limit has been reached.');
        }

        // --- RANDOM VS FIX LOGIC START ---
        if ($bonus->type == 'random') {
            // Generates a random amount between 1 and 4
            $finalAmount = rand(1, 4);
        } else {
            // Uses the fixed amount set in Admin Panel
            $finalAmount = $bonus->amount;
        }
        // --- RANDOM VS FIX LOGIC END ---

        // Update User Balance
        $user->balance += $finalAmount;
        $user->save();

        // Record in User Ledger
        $ledger = new UserLedger();
        $ledger->user_id = $user->id;
        $ledger->reason = 'bonus';
        $ledger->perticulation = 'Congratulations! You received a bonus of ' . price($finalAmount);
        $ledger->amount = $finalAmount;
        $ledger->debit = $finalAmount;
        $ledger->status = 'approved';
        $ledger->date = date('d-m-Y H:i');
        $ledger->save();

        // Increment Bonus Counter
        $bonus->increment('counter');

        // Record in Bonus Ledger
        $bonus_ledger = new BonusLedger();
        $bonus_ledger->user_id = $user->id;
        $bonus_ledger->bonus_id = $bonus->id;
        $bonus_ledger->amount = $finalAmount;
        $bonus_ledger->bonus_code = $code;
        $bonus_ledger->save();

        return redirect()->route('user.promo')->with('success', 'Successfully redeemed! Amount: ' . price($finalAmount));
    }

    public function preview()
    {
        $datas = BonusLedger::with(['bonus', 'user'])->where('user_id', Auth::id())->orderByDesc('id')->get();
        return view('app.main.bonus.bonus-preview', compact('datas'));
    }

    public function checkin(Request $request)
    {
        $check = Checkin::where('user_id', Auth::user()->id)->orderByDesc('id')->first();
        
        // Allow checkin if no record exists OR if 24 hours have passed
        if (!$check || now()->greaterThanOrEqualTo($check->date)) {
            $model = new Checkin();
            $model->user_id = Auth::id();
            $model->date = now()->addHours(24);
            $model->amount = setting('checkin');
            $model->save();

            $user = Auth::user();
            $user->balance += setting('checkin');
            $user->save();

            return redirect()->back()->with('success', 'Daily check-in bonus received successfully.');
        }

        return redirect()->back()->with('error', 'You have already claimed your daily check-in bonus.');
    }

    public function checkin_ledger()
    {
        $checkins = Checkin::where('user_id', Auth::id())->orderByDesc('id')->get();
        return view('app.main.checkin-ledger', compact('checkins'));
    }
}
