<?php

namespace App\Http\Controllers;

use App\Helpers\ResponseHelper;
use App\Models\ApiKey\ApikeyModel;
use App\Models\Category\CategoryModel;
use App\Models\Category\SubCategoryModel;
use App\Models\ErrorLogs\ErrorLogsModel;
use App\Models\Post\PostModel;
use App\Models\WalletModel;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Mockery\Exception;
use Tymon\JWTAuth\Facades\JWTAuth;
use function Symfony\Component\String\u;
use App\Http\Service\LocationService;

class AuthController extends Controller
{    protected $locationService;



    public function __construct(LocationService $locationService)
    {
        $this->locationService = $locationService;
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

    /**
     * @OA\Post(
     *     path="/v1/logout",
     *     summary="Logout the user",
     *     tags={"User"},
     *     @OA\Parameter(
     *         name="apikey",
     *         in="header",
     *         required=true,
     *         @OA\Schema(
     *             type="string"
     *         ),
     *         description="API key for the auth application"
     *     ),
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         required=true,
     *         @OA\Schema(
     *             type="string"
     *         ),
     *         description="JWT token to be validated"
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Successful logout",
     *         @OA\JsonContent(
     *             oneOf={
     *                 @OA\Schema(
     *                     type="object",
     *                     @OA\Property(property="status", type="integer", example=1),
     *                     @OA\Property(property="message", type="string", example="خروج کاربر با موفقیت انجام شد")
     *                 ),
     *                 @OA\Schema(
     *                     type="object",
     *                     @OA\Property(property="status", type="integer", example=0),
     *                     @OA\Property(property="message", type="string", example="خطا در احراز هویت سرویس"),
     *                     @OA\Property(property="code", type="integer", example=500)
     *                 )
     *             }
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="Internal server error",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="integer", example=0),
     *             @OA\Property(property="message", type="string", example="خطا در احراز هویت سرویس"),
     *             @OA\Property(property="code", type="integer", example=500)
     *         )
     *     ),
     *     security={
     *         {"api_key": {}}
     *     }
     * )
     */
    public function logout(Request $request)
    {
        $verifyApiKey = ApikeyModel::where('apikey', $request->header('apikey'))->first();

        if ($verifyApiKey) {

            Auth::logout();
            return response()->json([
                'status' => 1,
                'message' => 'خروج کاربر با موفقیت انجام شد',
            ]);
        } else {
            ErrorLogsModel::insert([
                'type' => 1,
                'description' => "User Log out | apikey auth unsuccessfully!",
                'ip_address' => $request->ip()
            ]);
            return response()->json(['status' => 0, 'message' => "خطا در احراز هویت سرویس", 'code' => 500], 200);
        }
    }

    /**
     * @OA\Post(
     *     path="/v1/refresh",
     *     summary="Refresh the JWT token",
     *     tags={"User"},
     *     @OA\Parameter(
     *         name="apikey",
     *         in="header",
     *         required=true,
     *         @OA\Schema(
     *             type="string"
     *         ),
     *         description="API key for the auth application"
     *     ),
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         required=true,
     *         @OA\Schema(
     *             type="string"
     *         ),
     *         description="JWT token to be validated"
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Successful response",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="integer", example=1),
     *             @OA\Property(property="message", type="string", example="اطلاعات کاربر با موفقیت دریافت شد"),
     *             @OA\Property(
     *                 property="data",
     *                 type="object",
     *                 @OA\Property(
     *                     property="user",
     *                     type="object",
     *                     @OA\Property(property="name", type="string", example="John"),
     *                     @OA\Property(property="family", type="string", example="Doe"),
     *                     @OA\Property(property="father_name", type="string", example="Richard"),
     *                     @OA\Property(property="nationalCode", type="string", example="1234567890"),
     *                     @OA\Property(property="number", type="string", example="0987654321"),
     *                     @OA\Property(property="username", type="string", example="johndoe"),
     *                     @OA\Property(property="password", type="string", example="password"),
     *                     @OA\Property(property="activateCode", type="string", example="1234"),
     *                     @OA\Property(property="isActivate", type="boolean", example=true),
     *                     @OA\Property(property="license", type="string", example="A12345BC")
     *                 ),
     *                 @OA\Property(
     *                     property="wallet",
     *                     type="object",
     *                     @OA\Property(property="user_id", type="integer", example=1),
     *                     @OA\Property(property="city_id", type="integer", example=100),
     *                     @OA\Property(property="credit", type="number", format="float", example=1000.50),
     *                     @OA\Property(property="created_at", type="string", format="date-time", example="2021-01-01T00:00:00.000000Z"),
     *                     @OA\Property(property="updated_at", type="string", format="date-time", example="2021-01-01T00:00:00.000000Z")
     *                 ),
     *                 @OA\Property(
     *                     property="authorisation",
     *                     type="object",
     *                     @OA\Property(property="token", type="string", example="new-jwt-token"),
     *                     @OA\Property(property="type", type="string", example="bearer")
     *                 )
     *             )
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="Internal server error",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="integer", example=0),
     *             @OA\Property(property="message", type="string", example="خطا در احراز هویت سرویس"),
     *             @OA\Property(property="code", type="integer", example=500)
     *         )
     *     ),
     *     security={
     *         {"api_key": {}}
     *     }
     * )
     */
    public function refresh(Request $request)
    {
        $verifyApiKey = ApikeyModel::where('apikey', $request->header('apikey'))->first();

        if ($verifyApiKey) {
            return response()->json([
                'status' => 1,
                'message' => 'اطلاعات کاربر با موفقیت دریافت شد',
                'data' => [
                    'authorisation' => [
                        'token' =>'bearer '. Auth::refresh(),
                    ]
                ],
            ]);
        } else {
            ErrorLogsModel::insert([
                'type' => 1,
                'description' => "Refresh Jwt Token | apikey auth unsuccessfully!",
                'ip_address' => $request->ip()
            ]);
            return response()->json(['status' => 0, 'message' => "خطا در احراز هویت سرویس", 'code' => 500], 200);

        }
    }

    /**
     * @OA\Get(
     *     path="/v1/getUser",
     *     summary="Get User Information",
     *     description="Retrieve information about the authenticated user with JWT token",
     *     tags={"User"},
     *     @OA\Parameter(
     *         name="apikey",
     *         in="header",
     *         required=true,
     *         @OA\Schema(
     *             type="string"
     *         ),
     *         description="API key for the auth application"
     *     ),
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         required=true,
     *         @OA\Schema(
     *             type="string"
     *         ),
     *         description="JWT token to be validated"
     *     ),
     *     security={
     *         {"bearerAuth": {}}
     *     },
     *     @OA\Response(
     *         response=200,
     *         description="Successful operation",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="status", type="integer", example=1),
     *             @OA\Property(
     *                 property="data",
     *                 type="object",
     *                 description="User data",
     *                 @OA\Property(
     *                     property="user",
     *                     ref="#/components/schemas/User"
     *                 ),
     *                 @OA\Property(
     *                     property="wallet",
     *                     ref="#/components/schemas/Wallet"
     *                 )
     *             ),
     *             @OA\Property(property="message", type="string", example="کاربر با موفقیت یافت شد")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthorized",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="error", type="string", example="Unauthorized")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="Internal server error",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="status", type="integer", example=0),
     *             @OA\Property(property="message", type="string", example="خطا در احراز هویت سرویس"),
     *             @OA\Property(property="code", type="integer", example=500)
     *         )
     *     )
     * )
     *
     * @OA\Schema(
     *     schema="User",
     *     title="User",
     *     description="User model data",
     *     @OA\Property(property="name", type="string", example="John"),
     *     @OA\Property(property="family", type="string", example="Doe"),
     *     @OA\Property(property="father_name", type="string", example="John"),
     *     @OA\Property(property="nationalCode", type="string", example="1234567890"),
     *     @OA\Property(property="number", type="string", example="9876543210"),
     *     @OA\Property(property="username", type="string", example="johndoe"),
     *     @OA\Property(property="password", type="string", example="password"),
     *     @OA\Property(property="activateCode", type="string", example="ABC123"),
     *     @OA\Property(property="isActivate", type="boolean", example=true),
     *     @OA\Property(property="license", type="string", example="ABCD1234")
     * )
     *
     * @OA\Schema(
     *     schema="Wallet",
     *     title="Wallet",
     *     description="User wallet data",
     *     @OA\Property(property="user_id", type="integer", example=1),
     *     @OA\Property(property="city_id", type="integer", example=100),
     *     @OA\Property(property="credit", type="number", format="float", example=1000.50),
     *     @OA\Property(property="created_at", type="string", format="date-time", example="2021-01-01T00:00:00.000000Z"),
     *     @OA\Property(property="updated_at", type="string", format="date-time", example="2021-01-01T00:00:00.000000Z")
     * )
     */
    public function getUser(Request $request)
    {
        $verifyApiKey = ApikeyModel::where('apikey', $request->header('apikey'))->first();

        if ($verifyApiKey) {
            return response()->json(['status' => 1,
                'data' => ['user' => (object)Auth::getUser()],
                'message' => 'کاربر با موفقیت یافت شد'], 200);

        } else {
            ErrorLogsModel::insert([
                'type' => 1,
                'description' => "Get User Detail | apikey auth unsuccessfully!",
                'ip_address' => $request->ip()
            ]);
            return response()->json(['status' => 0, 'message' => "خطا در احراز هویت سرویس", 'code' => 500], 200);

        }
    }


    public function updateUser(Request $request)
    {
        $data = $request->all();

        $user = Auth::user();
        $user->first_name = $data['first_name'] ?? $user->first_name;
        $user->last_name = $data['last_name'] ?? $user->last_name;
        $user->email = $data['email'] ?? $user->email;
        $user->password = $data['password'] ?? $user->passowrd;
        $user->save();

        return response()->json(['status' => 1, 'message' => 'کاربر با موفقیت بروزرسانی شد', 'data' => ['user' => Auth::user()]]);
    }

    public function getPostsUserShared()
    {
        $allPost = PostModel::where('seller', Auth::user()->getAuthIdentifier())->orderBy('id', 'desc')->get();
        if (count($allPost) > 0) {
            $post = []; // Initialize an array to hold all posts
            foreach ($allPost as $item) {
                $images = json_decode($item->image, true); // Decode the JSON string
                $firstImage = isset($images[0]) ? $images[0] : null; // Retrieve the first image URL

                $itemSubCategory = $item->sub_category_id;
                $sub_data = SubCategoryModel::where('id', $itemSubCategory)->first();
    
                $category_name = CategoryModel::where('id', $sub_data->category_id)->first()->title;

                
                $itemSubCategory = $item->sub_category_id;
                $sub_data = SubCategoryModel::where('id', $itemSubCategory)->first();
    
                $category_name = CategoryModel::where('id', $sub_data->category_id)->first()->title;
                list($city_name, $province_name) = $this->locationService->getCityAndProvinceNames($item->city_id);

                // تبدیل رشته تاریخ به شیء Carbon
        $postCreatedAtCarbon = Carbon::parse($item->created_at);

        // زمان فعلی
        $now = Carbon::now();

        // محاسبه تفاوت‌ها
        $diffInMinutes = $now->diffInMinutes($postCreatedAtCarbon);
        $diffInHours = $now->diffInHours($postCreatedAtCarbon);
        $diffInDays = $now->diffInDays($postCreatedAtCarbon);
        $diffInMonths = $now->diffInMonths($postCreatedAtCarbon);
        $diffInYears = $now->diffInYears($postCreatedAtCarbon);


        // نمایش تفاوت‌ها

// تعیین مقدار $cityAndTimeInfo بر اساس تفاوت زمانی
$cityAndTimeInfo = "";
if ($diffInMinutes < 60) {
    $cityAndTimeInfo = $diffInMinutes . " دقیقه پیش در " . $city_name;
} elseif ($diffInHours < 24) {
    $cityAndTimeInfo = $diffInHours . " ساعت پیش در " . $city_name;
} elseif ($diffInDays < 30) {
    $cityAndTimeInfo = $diffInDays . " روز پیش در " . $city_name;
} elseif ($diffInMonths < 12) {
    $cityAndTimeInfo = $diffInMonths . " ماه پیش در " . $city_name;
} else {
    $cityAndTimeInfo = $diffInYears . " سال پیش در " . $city_name;
}
                $post[] = [
                    'id' => $item->id,
                    'name' => $item->name,
                    'seller' => $item->seller,
                    'price' => $item->price,
                    'image' => $firstImage,
                    'address' => ['lat' => $item->location_lat, 'long' => $item->location_long],
                    'discountPercent' => $item->discountPercent,
                    'cat_names' => $category_name . ', ' . $sub_data->title,
                    'city' => $cityAndTimeInfo,
                ];
            }

            return response()->json(['status' => 1, 'message' => "لیست پست ها با موفقیت دریافت شد", 'data' => $post]);
        } else {
            return ResponseHelper::unSuccessResponse(0, "شما پستی ایجاد نکرده اید", 401);
        }
    }

    /**
     * @OA\Post(
     *     path="/v1/validateToken",
     *     summary="Validate JWT Token",
     *     description="Validate the JWT token passed in the request headers",
     *     tags={"User"},
     *     @OA\Parameter(
     *         name="apikey",
     *         in="header",
     *         required=true,
     *         @OA\Schema(
     *             type="string"
     *         ),
     *         description="API key for the authentication"
     *     ),
     *     @OA\Parameter(
     *         name="Authorization",
     *         in="header",
     *         required=true,
     *         @OA\Schema(
     *             type="string"
     *         ),
     *         description="JWT token to be validated"
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Successful operation",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="message", type="string", example="توکن شما فعال میباشد")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthorized",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="message", type="string", example="Unauthorized")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="Internal server error",
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="status", type="integer", example=0),
     *             @OA\Property(property="message", type="string", example="خطا در احراز هویت سرویس"),
     *             @OA\Property(property="code", type="integer", example=500)
     *         )
     *     )
     * )
     */
    public function validateToken(Request $request)
    {
        $verifyApiKey = ApikeyModel::where('apikey', $request->header('apikey'))->first();

        if ($verifyApiKey) {
// Retrieve the JWT token from the request headers, cookies, or wherever it is stored
            $token = $request->header('Authorization');

// Check if the token is valid
            try {
                $isValid = JWTAuth::parseToken($token)->check();
            } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
                // Token is invalid
                $isValid = false;
            } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
                // Token is expired
                $isValid = false;
            }

            if ($isValid) {
                // Token is valid
                return response()->json(['message' => 'توکن شما فعال میباشد']);
            } else {
                // Token is not valid
                return response()->json(['message' => 'Unauthorized']);
            }

        } else {
            ErrorLogsModel::insert([
                'type' => 1,
                'description' => "validate JWT Token | apiKet unAuthorize!",
                'ip_address' => $request->ip()
            ]);
            return response()->json(['status' => 0, 'message' => "خطا در احراز هویت سرویس", 'code' => 500], 200);
        }
    }


}
