<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use App\Models\VerificationCode;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        try {
            $request->validate([
                'name' => 'required|string|max:255',
                'password' => 'required|min:6|max:64',
                // 'phone' => 'required|digits_between:8,14|unique:users',
                'phone' => 'required|regex:/^\+[1-9]\d{7,14}$/|unique:users',
                'img' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                'gender' => 'required|in:male,female,other',
                'notification_id' => 'required|string|max:255',
                'device_id' => 'required|string|max:255',
                'device_type' => 'required|string|in:ios,apk',
                // 'email' => 'required|email:filter',
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, null, $e->getMessage(), $e->errors(), 422);
        }

        if (!empty($request->img)) {
            $imagePath = $request->file('img')->store('/user_pictures', ['disk' => 'uploads']);
            $imagePath = "/storage/uploads/$imagePath";
        } else {
            $imagePath = null;
        }

        $newUser = new User();
        $newUser->name = $request->name;
        $newUser->password = bcrypt($request->password);
        $newUser->phone = $request->phone;
        $newUser->img = $imagePath;
        $newUser->gender = $request->gender;
        $newUser->notification_id = $request->notification_id;
        $newUser->device_id = $request->device_id;
        $newUser->device_type = $request->device_type;
        $newUser->save();

        $token = $newUser->createToken("user-$newUser->id")->plainTextToken;

        return sendCustomResponse(true, ['token' => $token, 'user' => $newUser], '', '', 200);
    }


    public function me(Request $request)
    {
        return sendCustomResponse(true, $request->user(), '', '', 200);
    }


    public function login(Request $request)
    {

        try {
            $request->validate([
                'phone' => 'required|max:20|exists:users,phone',
                'password' => 'required|max:200|',
                'notification_id' => 'required|string|max:255', //firebase notifications
                'device_id' => 'required|string|max:255',
                'device_type' => 'required|in:ios,apk'
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, null, $e->getMessage(), $e->errors(), 422);
        }

        $user = User::where('phone', $request->phone)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return sendCustomResponse(false, null, __('trans.auth.error_login'), '', 422);
        } else {

            if ($user->is_block) {
                return sendCustomResponse(false, null, $user->is_block_message, '', 422);
            }

            $user->update(['notification_id' => $request->notification_id, 'device_type' => $request->device_type]);

            if (empty($user->device_id)) {
                $user->update(['device_id' => $request->device_id]);
            }

            if (!$user->allow_any_device && $user->device_id != $request->device_id) {
                return sendCustomResponse(false, null, "This phone number is linked to another device!", '', 422);
            }
        }

        $token = $user->createToken("user-$user->id")->plainTextToken;

        return sendCustomResponse(true, ['token' => $token, 'user' => $user], "", '', 200);
    }


    public function logout()
    {
        if (auth('sanctum')->check()) {
            auth('sanctum')->user()->tokens()->delete();

            return sendCustomResponse(true, '', __('trans.auth.logged_out_successfully'), '', 200);
        }
        return sendCustomResponse(false, '', __('trans.auth.unauthenticated'), '', 401);
    }


    public function forgetPassword(Request $request)
    {
        try {
            $request->validate([
                'phone' => 'required|max:20|exists:users,phone',
                // 'country_code' => 'required|max:20',
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, null, $e->getMessage(), $e->errors(), 422);
        }

        $newPassword = mt_rand(1000, 9999);
        $user = User::where('phone', $request->phone)->first();
        $user->update(['password' => bcrypt($newPassword)]);
        $message = "You can log in with the new password: $newPassword";
        $phone = $request->country_code . $request->phone;
        Log::info("New password was sent successfully", [$newPassword, $phone]);
        sendWhatsappMessage($phone, $message);

        return sendCustomResponse(true, "", "New password was sent successfully", '', 200);
    }


    public function updateProfile(Request $request)
    {
        $user = $request->user();

        try {
            $request->validate([
                'name' => 'required|string|max:100',
                'img' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                'gender' => 'required|in:male,female,other',
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, null, $e->getMessage(), $e->errors(), 422);
        }

        $newImage = $user->img;

        if (!empty($request->img)) {
            $oldPath = $request->user()->img;
            if ($oldPath) {
                File::delete(public_path($oldPath));
            }
            $newImage = $request->file('img')->store('/user_pictures', ['disk' => 'uploads']);
            $newImage = "/uploads/$newImage";
        }


        $user->update([
            'name' => $request->name,
            'gender' => $request->gender,
            'img' => $newImage
        ]);
        return sendCustomResponse(true, $user, '', '', 200);
    }

    // public function countryCodes()
    // {
    //     return sendCustomResponse(true, countryCodes(), '', '', 200);
    // }


    public function changePassword(Request $request)
    {
        try {
            $request->validate([
                'old_password' => 'required|max:200',
                'new_password' => 'required|max:200|different:old_password',
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, null, $e->getMessage(), $e->errors(), 422);
        }

        $user = $request->user();
        if (!Hash::check($request->old_password, $user->password)) {
            return sendCustomResponse(false, null, __('trans.auth.wrong_password'), '', 422);
        }

        $user->password = bcrypt($request->new_password);
        $user->save();

        return sendCustomResponse(true, $user, __('trans.auth.password_changed'), '', 200);
    }


    public function sendVerficationCode(Request $request)
    {
        try {

            /**
             * Breakdown of the Regex Pattern
             * ^: Asserts the position at the start of the string.
             * \+: Matches a literal plus sign character.
             * [1-9]: Matches a single digit from 1 to 9 (the first digit of the country code cannot be zero).
             * \d{7,14}: Matches between 7 and 14 additional digits.
             * $: Asserts the position at the end of the string.
             * Total length allowed by this pattern is between 9 and 16 characters (1 plus sign + 1 leading digit + 7 to 14 digits).
             *
             */
            $request->validate([
                'phone' => 'required|regex:/^\+[1-9]\d{7,14}$/',
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, '', $e->getMessage(), $e->errors(), 422);
        }

        $verficationCode = mt_rand(1000, 9999);
        $phone = $request->phone;
        $message = "Your verification code is: $verficationCode";

        // Log::info("Verification code sent successfully", [$verficationCode, $phone]);
        $is_sent = sendWhatsappMessage($phone, $message);

        if (!$is_sent) {
            return sendCustomResponse(false, '', 'Failed to send verification code', '', 422);
        }

        VerificationCode::updateOrCreate([
            'phone' => $request->phone,
        ], [
            'code' => $verficationCode
        ]);

        return sendCustomResponse(true, '', 'Verification code sent successfully', '', 200);
    }


    public function verifyCode(Request $request)
    {
        try {
            /**
             * Breakdown of the Regex Pattern
             * ^: Asserts the position at the start of the string.
             * \+: Matches a literal plus sign character.
             * [1-9]: Matches a single digit from 1 to 9 (the first digit of the country code cannot be zero).
             * \d{7,14}: Matches between 7 and 14 additional digits.
             * $: Asserts the position at the end of the string.
             * Total length allowed by this pattern is between 9 and 16 characters (1 plus sign + 1 leading digit + 7 to 14 digits).
             *
             */
            $request->validate([
                'phone' => 'required|regex:/^\+[1-9]\d{7,14}$/',
                'code' => 'required|digits:4',
            ]);
        } catch (ValidationException $e) {
            return sendCustomResponse(false, '', $e->getMessage(), $e->errors(), 422);
        }

        $verificationCode = VerificationCode::where([
            'phone' => $request->phone,
            'code' => $request->code,
        ])->first();

        if (!$verificationCode) {
            return sendCustomResponse(false, '', 'Invalid verification code', '', 422);
        }

        $verificationCode->delete();
        return sendCustomResponse(true, '', 'Verification code verified successfully', '', 200);
    }
}
