<?php

namespace App\Http\Controllers\User;

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

class GiftRedeemController extends Controller
{
    /**
     * Redeem a bonus or gift code.
     */
    public function redeem(Request $request)
    {
        try {
            // Validate input
            $validator = Validator::make($request->all(), [
                'bonus_code' => 'required|string|max:255',
            ]);

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

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

            // Find active bonus
            $bonus = Bonus::where('status', 'active')->first();
            if (!$bonus) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'No active bonus available'
                ]);
            }

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

            // Already used?
            $used = BonusLedger::where('user_id', $user->id)
                ->where('bonus_id', $bonus->id)
                ->exists();
            if ($used) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'You have already used this code'
                ]);
            }

            // Check limit
            if ($bonus->counter >= $bonus->set_service_counter) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Bonus limit reached'
                ]);
            }

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

            // Create ledger entry
            UserLedger::create([
                'user_id' => $user->id,
                'reason' => 'gift_redeem',
                'perticulation' => 'Redeemed gift code ' . $bonus->code,
                'amount' => $bonus->amount,
                'debit' => $bonus->amount,
                'status' => 'approved',
                'date' => now()->format('d-m-Y H:i'),
            ]);

            // Log usage
            BonusLedger::create([
                'user_id' => $user->id,
                'bonus_id' => $bonus->id,
                'amount' => $bonus->amount,
                'bonus_code' => $code,
            ]);

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

            return response()->json([
                'status' => 'success',
                'amount' => $bonus->amount,
                'message' => 'Gift code redeemed successfully!'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Please try again later.',
                'error' => $e->getMessage() // optional for debug
            ]);
        }
    }
}
