<?php

namespace App\Http\Controllers\Admin;

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

class ReferralCodeController extends Controller
{

    protected $ReferralCodeServices;

    public function __construct(ReferralCodeServices $ReferralCodeServices)
    {
        $this->ReferralCodeServices = $ReferralCodeServices;
    }
    public function CheckReferral(Request $request)
    {
        try {
            $token = readHeaderToken();
            $validator = Validator::make($request->all(), [
                'referral_code' => 'required',
            ]);

            if ($validator->fails()) {
                $validationErrors = $validator->errors()->all();
                Log::error("Validation error: " . implode(", ", $validationErrors));
                return jsonResponseWithErrorMessageApi($validationErrors, 403);
            }

            if ($token) {
                $customerIamId = $token['sub'];
                $response = $this->ReferralCodeServices->CheckReferral($customerIamId, $request);
                return $response;
            } 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);
        }
    }
}
