<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Accounting;
use App\Models\Affiliate;
use App\Models\AffiliateCode;
use App\Models\Reward;
use App\Models\RewardAccounting;
use App\Models\Role;
use App\Models\UserMeta;
use App\Providers\RouteServiceProvider;
use App\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\QueryException;
use Illuminate\Validation\Rule;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }

    public function showRegistrationForm()
    {
        $seoSettings = getSeoMetas('register');
        $pageTitle = !empty($seoSettings['title']) ? $seoSettings['title'] : trans('site.register_page_title');
        $pageDescription = !empty($seoSettings['description']) ? $seoSettings['description'] : trans('site.register_page_title');
        $pageRobot = getPageRobot('register');

        $referralSettings = getReferralSettings();

        $referralCode = Cookie::get('referral_code');

        $data = [
            'pageTitle' => $pageTitle,
            'pageDescription' => $pageDescription,
            'pageRobot' => $pageRobot,
            'referralCode' => $referralCode,
            'referralSettings' => $referralSettings,
        ];

        return view(getTemplate() . '.auth.register', $data);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function prepareRegistrationData(array $data): array
    {
        if (!empty($data['mobile'])) {
            $data['mobile'] = normalizeUserMobile($data['country_code'] ?? '20', $data['mobile']);
        }

        return $data;
    }

    protected function validator(array $data)
    {
        $data = $this->prepareRegistrationData($data);

        $registerMethod = getGeneralSettings('register_method') ?? 'mobile';

        $mobileRequired = ($registerMethod === 'mobile');
        $emailRequired = ($registerMethod === 'email');

        return Validator::make($data, [
            'country_code' => [
                Rule::requiredIf($mobileRequired || !empty($data['mobile'])),
                'nullable',
            ],
            'mobile' => [
                Rule::requiredIf($mobileRequired),
                'nullable',
                'regex:/^20[0-9]{10}$/',
                'unique:users,mobile',
            ],
            'email' => [
                Rule::requiredIf($emailRequired),
                'nullable',
                'email',
                'max:255',
                'unique:users',
            ],
            'term' => 'required|accepted',
            'full_name' => 'required|string|min:3',
            'password' => 'required|string|min:6|confirmed',
            'password_confirmation' => 'required|same:password',
            'referral_code' => 'nullable|exists:affiliates_codes,code',
            'avatar' => 'required|image|max:2048',
        ], [
            'email.required' => 'البريد الإلكتروني مطلوب.',
            'email.unique' => 'هذا البريد الإلكتروني مسجّل مسبقاً.',
            'mobile.required' => 'رقم الموبايل مطلوب.',
            'mobile.unique' => 'رقم الموبايل مسجّل مسبقاً. إن كان حسابك قيد التفعيل سجّل الدخول أو افتح /verification.',
            'mobile.regex' => 'رقم الموبايل غير صحيح. استخدم صيغة 01XXXXXXXXX (11 رقم).',
            'avatar.required' => 'الصورة الشخصية مطلوبة.',
            'avatar.image' => 'يجب رفع صورة بصيغة صور (jpg, png...).',
            'term.required' => 'يجب الموافقة على الشروط والأحكام.',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param array $data
     * @return
     */
    protected function create(array $data)
    {
        $data = $this->prepareRegistrationData($data);

        $referralSettings = getReferralSettings();
        $usersAffiliateStatus = (!empty($referralSettings) and !empty($referralSettings['users_affiliate_status']));

        if (empty($data['timezone'])) {
            $data['timezone'] = getGeneralSettings('default_time_zone') ?? null;
        }

        $disableViewContentAfterUserRegister = getFeaturesSettings('disable_view_content_after_user_register');
        $accessContent = !((!empty($disableViewContentAfterUserRegister) and $disableViewContentAfterUserRegister));
        
         
        
        
       

        $user = createUserWithManualId([
            'role_name' => Role::$user,
            'role_id' => Role::getUserRoleId(),
            'mobile' => $data['mobile'] ?? null,
            'email' => $data['email'] ?? null,
            'full_name' => $data['full_name'],
            'status' => User::$pending,
            'access_content' => $accessContent ? 1 : 0,
            'password' => Hash::make($data['password']),
            'affiliate' => $usersAffiliateStatus ? 1 : 0,
            'timezone' => $data['timezone'] ?? null,
        ]);

        if (empty($user->id)) {
            throw new \RuntimeException('تعذر إنشاء الحساب. حاول مرة أخرى.');
        }

        $profileImage = $this->createImage($user, $data['avatar']);
        $user->update([
            'avatar' => $profileImage,
        ]);
        
        /*$user->avatar=$profileImage;
        $user->save();*/

        if (!empty($data['certificate_additional'])) {
            UserMeta::updateOrCreate([
                'user_id' => $user->id,
                'name' => 'certificate_additional'
            ], [
                'value' => $data['certificate_additional']
            ]);
        }

        return $user;
    }


    public function register(Request $request)
    {
        $data = $this->prepareRegistrationData($request->all());

        $this->validator($data)->validate();

        $existingUser = $this->findConflictingUser($data);
        if ($existingUser) {
            if ($existingUser->status === User::$pending) {
                return $this->resumePendingRegistration($existingUser, $data, $request);
            }

            if (!empty($data['mobile']) && $existingUser->mobile === $data['mobile']) {
                return back()
                    ->withInput($request->except('password', 'password_confirmation'))
                    ->withErrors(['mobile' => 'رقم الموبايل مسجّل مسبقاً. جرّب تسجيل الدخول من /login أو تفعيل الحساب من /verification.']);
            }

            if (!empty($data['email']) && $existingUser->email === $data['email']) {
                return back()
                    ->withInput($request->except('password', 'password_confirmation'))
                    ->withErrors(['email' => 'البريد الإلكتروني مسجّل مسبقاً. جرّب تسجيل الدخول من /login.']);
            }
        }

        try {
            $user = $this->create($data);
        } catch (QueryException $e) {
            if ((int) $e->getCode() === 23000) {
                return back()
                    ->withInput($request->except('password', 'password_confirmation'))
                    ->withErrors(['register' => 'رقم الموبايل أو البريد مسجّل مسبقاً. إن سجّلت من قبل ولم تفعّل الحساب، افتح /verification أو سجّل الدخول من /login.']);
            }

            report($e);

            return back()
                ->withInput($request->except('password', 'password_confirmation'))
                ->withErrors(['register' => 'تعذر إنشاء الحساب. حاول مرة أخرى.']);
        } catch (\Throwable $e) {
            report($e);

            return back()
                ->withInput($request->except('password', 'password_confirmation'))
                ->withErrors(['register' => 'تعذر إنشاء الحساب: ' . $e->getMessage()]);
        }

        return $this->completeRegistrationAfterCreate($user, $request, $data);
    }

    private function findConflictingUser(array $data): ?User
    {
        if (!empty($data['mobile'])) {
            $byMobile = User::where('mobile', $data['mobile'])->first();
            if ($byMobile) {
                return $byMobile;
            }
        }

        if (!empty($data['email'])) {
            return User::where('email', $data['email'])->first();
        }

        return null;
    }

    private function resumePendingRegistration(User $user, array $data, Request $request)
    {
        $user->update([
            'full_name' => $data['full_name'],
            'password' => Hash::make($data['password']),
            'email' => $data['email'] ?? $user->email,
        ]);

        if ($request->hasFile('avatar')) {
            $user->update(['avatar' => $this->createImage($user, $request->file('avatar'))]);
        }

        return $this->completeRegistrationAfterCreate($user, $request, $data, true);
    }

    private function completeRegistrationAfterCreate(User $user, Request $request, array $data, bool $resumed = false)
    {
        if (!$resumed) {
            event(new Registered($user));
        }

        $registerMethod = getGeneralSettings('register_method') ?? 'mobile';

        $value = $registerMethod === 'email'
            ? ($data['email'] ?? $user->email)
            : ($data['mobile'] ?? $user->mobile);

        if (empty($value)) {
            return back()
                ->withInput($request->except('password', 'password_confirmation'))
                ->withErrors([
                    $registerMethod => $registerMethod === 'email'
                        ? 'البريد الإلكتروني مطلوب.'
                        : 'رقم الموبايل مطلوب.',
                ]);
        }

        $verificationController = new VerificationController();
        $checkConfirmed = $verificationController->checkConfirmed($registerMethod, $value, $user);

        $referralCode = $request->get('referral_code', null);

        if (!empty($checkConfirmed['status']) && $checkConfirmed['status'] === 'send') {
            if (!empty($referralCode)) {
                session()->put('referralCode', $referralCode);
            }

            $codeSent = $checkConfirmed['code_sent'] ?? true;

            $createdMsg = $resumed
                ? 'لديك حساب بانتظار التفعيل. أدخل رمز التفعيل المرسل إليك.'
                : ($codeSent
                    ? 'تم إنشاء الحساب. أدخل رمز التفعيل المرسل إلى بريدك.'
                    : 'تم إنشاء الحساب. تعذر إرسال الإيميل تلقائياً — استخدم «إعادة الإرسال» في صفحة التفعيل.');

            return redirect('/verification')->with([
                'toast' => [
                    'title' => trans('auth.signup'),
                    'msg' => $createdMsg,
                    'status' => $codeSent ? 'success' : 'warning',
                ],
            ]);
        }

        if (!empty($checkConfirmed['status']) && $checkConfirmed['status'] === 'verified') {
            $this->guard()->login($user);

            $user->update([
                'status' => User::$active,
            ]);

            $registerReward = RewardAccounting::calculateScore(Reward::REGISTER);
            RewardAccounting::makeRewardAccounting($user->id, $registerReward, Reward::REGISTER, $user->id, true);

            if (!empty($referralCode)) {
                Affiliate::storeReferral($user, $referralCode);
            }

            if ($response = $this->registered($request, $user)) {
                return $response;
            }

            return $request->wantsJson()
                ? new JsonResponse([], 201)
                : redirect($this->redirectPath());
        }

        return back()
            ->withInput($request->except('password', 'password_confirmation'))
            ->withErrors(['register' => 'تعذر إكمال التسجيل. حاول مرة أخرى أو تواصل مع الدعم.']);
    }
    
    public function createImage($user,$img)
    {
        $folderPath = "/" . $user->id . '/avatar/';
        //$folderPath = "/store";
    
        $image_type = $img->extension();
        //$image_base64 = base64_decode($image_parts[1]);
        $file = uniqid() . '.' . $image_type;

        
        
        //Storage::disk('local')->put($folderPath.$file, $img, 'public');
        //Storage::disk('public')->put($folderPath, $img);
        $x= $img->store($folderPath);
        
        //return $file;

        return Storage::disk('public')->url($x);

        return Storage::disk('public')->url($folderPath . $file);
    }
}
