<?php

namespace App\Http\Controllers\Admin\APIs\RestaurantApi;

use App\Http\Controllers\Controller;
use App\Services\APIs\RestaurantService\RedeemApiService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Exception;

class RedeemControllerApi extends Controller
{
    protected $RedeemApiService;

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

       /**
     * Created By : sayli Raut
     * Created at : 11 June 2024
     * Use : To get redeem voucher/restaurant.
     */
    public function getRedemedData()
    {
        try {
            $token = readRestHeaderToken();
            if ($token) {
                $restIamId = $token['sub'];
                return $this->RedeemApiService->getRedemedData($restIamId);
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.user_deleted'), 409);
            }
        } catch (Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }

    public function undoRedemption(Request $request)
    {
        try {
            $token = readRestHeaderToken();
            if ($token) {
                $restIamId = $token['sub'];
                $validator = Validator::make($request->all(), [
                    'voucher_id' => 'required',
                ]);

                if ($validator->fails()) {
                    return jsonResponseWithErrorMessageApi($validator->errors()->first(), 400);
                }

                return $this->RedeemApiService->undoRedemption($restIamId, $request);
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.user_deleted'), 409);
            }
        } catch (Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }

      /**
     * Created By : sayli Raut
     * Created at : 11 June 2024
     * Use : Search Redemption coupon.
     */
    public function searchRedemption(Request $request)
    {
        try {
            $token = readRestHeaderToken();
            if ($token) {
                $restIamId = $token['sub'];
                return $this->RedeemApiService->searchRedemption($restIamId, $request);
            } else {
                return jsonResponseWithErrorMessageApi(__('auth.user_deleted'), 409);
            }
        } catch (\Exception $e) {
            Log::error("An error occurred in " . __METHOD__ . ": " . $e->getMessage(), ['exception' => $e]);
            return jsonResponseWithErrorMessage(__('auth.something_went_wrong'), 500);
        }
    }
}
