<?php

namespace App\Http\Controllers\user;

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

class GiftRedeemController extends Controller
{
    /**
     * Redeem a bonus or gift code with Fix or Random logic.
     */
    public function redeem(Request $request)
    {
        $user = Auth::user();
        if (!$user) {
            return response()->json([
                'status' => 'error',
                'message' => 'You must be logged in to redeem a code.'
            ]);
        }

        $validator = Validator::make($request->all(), [
            'bonus_code' => 'required|string|max:255',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'message' => $validator->errors()->first()
            ]);
        }

        $code = trim($request->bonus_code);

        try {
            // Find active bonus by code
            $bonus = Bonus::where('status', 'active')
                ->where('code', $code)
                ->first();

            if (!$bonus) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Invalid or inactive bonus code.'
                ]);
            }

            // Already used check
            $alreadyUsed = BonusLedger::where('user_id', $user->id)
                ->where('bonus_id', $bonus->id)
                ->exists();

            if ($alreadyUsed) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'You have already used this code.'
                ]);
            }

            // Bonus usage limit check
            if ($bonus->counter >= $bonus->set_service_counter) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'This bonus has reached its usage limit.'
                ]);
            }

            // Random or Fix Logic
            if ($bonus->type == 'random') {
                $finalAmount = rand(1, 4); 
            } else {
                $finalAmount = $bonus->amount;
            }

            // Update user balance
            $user->increment('balance', $finalAmount);

            // Record in UserLedger - FIXED TO COUNT IN PROFILE
            $ledger = new UserLedger();
            $ledger->user_id = $user->id;
            $ledger->reason = 'gift_redeem';
            $ledger->perticulation = 'Congratulations! You received ' . $finalAmount . ' from code ' . $bonus->code;
            $ledger->amount = $finalAmount;
            $ledger->credit = $finalAmount; // This ensures it counts in income
            $ledger->type = 'credit'; 
            $ledger->status = 'approved';
            $ledger->date = now()->format('d-m-Y H:i');
            $ledger->save();

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

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

            return response()->json([
                'status' => 'success',
                'amount' => $finalAmount,
                'message' => 'Success! You received: ' . $finalAmount
            ]);

        } catch (\Exception $e) {
            Log::error('GiftRedeem Error: ' . $e->getMessage());
            return response()->json([
                'status' => 'error',
                'message' => 'Something went wrong.'
            ]);
        }
    }
}
