<?php


namespace App\Services\APIs\CustomerAPIs;

use App\Models\CheckReferralCode;
use App\Models\IamPrincipal;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Exception;

class ReferralCodeServices
{
    public function CheckReferral($customerIamId, $request)
    {
        try {
            $isExist = IamPrincipal::where('referral_code', $request->referral_code)
                ->where('id', '!=', $customerIamId)
                ->exists();
            if (!$isExist) {
                return jsonResponseWithErrorMessage(__('auth.invalid_referral_code'), 404);
            }

            // Check already used 3 times
            $referralCodeCount = CheckReferralCode::where('referral_code', $request->referral_code)->count();
            if ($referralCodeCount >= 3) {
                return jsonResponseWithErrorMessage(__('auth.limitation_over'), 404);
            }

            // Check if the referral code is already used by the same customer
            $usedByUser = CheckReferralCode::where('referral_code', $request->referral_code)
                ->where('iam_principal_xid', $customerIamId)
                ->exists();
            if ($usedByUser) {
                return jsonResponseWithErrorMessage(__('auth.already_used_code'), 404);
            }

            $storeId = new CheckReferralCode();
            $storeId->iam_principal_xid = $customerIamId;
            $storeId->referral_code = $request->referral_code;
            $storeId->save();

            return jsonResponseWithSuccessMessageApi(__('success.redeemed_successfully'), 200);
        } catch (Exception $ex) {
            Log::error('Check referral code service failed: ' . $ex->getMessage());
            return jsonResponseWithErrorMessageApi(__('auth.something_went_wrong'), 500);
        }
    }
}
