<?php

namespace App\Http\Controllers;

use App\Repositories\Member\VoucherEvent\VoucherEventRepository;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class VoucherEventController extends Controller
{
    protected $voucherEventRepository;

    public function __construct(VoucherEventRepository $voucherEventRepository)
    {
        $this->voucherEventRepository = $voucherEventRepository;
    }

    /**
     * Redeem a voucher event
     *
     * @param int $voucherEvent
     * @param Request $request
     * @return JsonResponse
     */
    public function redeem($voucherEvent, Request $request): JsonResponse
    {
        try {
            // Get the authenticated user
            $user = auth()->user();
            
            if (!$user) {
                return response()->json([
                    'success' => false,
                    'message' => 'User not authenticated'
                ], 401);
            }

            // Call the repository's redeem method
            $result = $this->voucherEventRepository->redeem($voucherEvent, $user);

            if ($result) {
                return response()->json([
                    'success' => true,
                    'message' => $result['message'] ?? 'Voucher redeemed successfully!',
                    'data' => $result['data'] ?? null
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => $result['message'] ?? 'Failed to redeem voucher'
                ], 400);
            }

        } catch (\Exception $e) {
            Log::error($e);
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
}
