<?php

namespace App\Services\User\Account;

use App\Http\Requests\User\ProfileUpdateRequest;
use Illuminate\Support\Facades\Storage;
use App\Models\Token;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use Morilog\Jalali\Jalalian;

class ProfileService
{
    /** validate birthday */
    public function getBirthday(ProfileUpdateRequest $request)
    {
        if ($request->exists('birthday') && $request->birthday != '') {
            try {
                $birthdayJalali = Jalalian::fromFormat('Y/m/d', $request->birthday);
                $birthdayTimestamp = $birthdayJalali->getTimestamp();

                if ($birthdayTimestamp < 0 || Jalalian::forge($birthdayTimestamp)->isFuture()) {
                    return null;
                }

                $birthdayCarbon = $birthdayJalali->toCarbon()->setTimezone('Asia/Tehran');

                return $birthdayCarbon->format('Y-m-d H:i:s');
            } catch (\Exception $e) {
                return null;
            }
        }

        return null;
    }

    /** validate gender */
    public function getGender(ProfileUpdateRequest $request)
    {
        if ($request->exists('gender') && $request->gender != '') {
            if ($request->gender == 'man' || $request->gender == 'woman' || $request->gender == 'unknown') {
                return $request->gender;
            }
        }

        return null;
    }

    /** validate social */
    public function getSocial(ProfileUpdateRequest $request)
    {
        if ($request->exists('social') && $request->social != '') {
            $social = $request->social;
            if (is_array($social) && array_key_exists('instagram', $social) && array_key_exists('telegram', $social) && array_key_exists('twitter', $social) && array_key_exists('facebook', $social)) {
                return serialize($social);
            }
        }

        return null;
    }

    /** upload user avatar */
    public function uploadAvatar(ProfileUpdateRequest $request, User $user)
    {
        $avatar = $user->avatar;
        if ($request->exists('avatar') && $request->file('avatar') != null) {
            $request->validate([
                'avatar' => ['required', 'file', 'max:10240', 'mimes:jpeg,jpg,png,webp,gif,svg'],
            ]);

            $file = $request->file('avatar');
            $fileFormat = $file->getClientOriginalExtension();
            $fileType = null;

            switch ($fileFormat) {
                case "jpeg":
                case "jpg":
                case "png":
                case "webp":
                case "gif":
                case "svg":
                    $fileType = "image";
                    break;
                default:
                    return;
                    break;
            }

            $fileName = 'file.' . time() . '.' . rand(10000, 99999) . '.' . $file->getClientOriginalExtension();
            $fileSize = floor($file->getSize() / 1000);
            $fileSaveAddressNoName = 'library/' . date('Y-m-d') . '/' . $user->id;
            $fileSaveAddress = $fileSaveAddressNoName . '/' . $fileName;
            $imageResolution = null;

            if ($fileType == "image") {
                $imageResolution = getimagesize($file)[0] . '×' . getimagesize($file)[1];
            }

            $uploadResult = '/media/' . $fileSaveAddress;
            Storage::disk('media')->put($fileSaveAddress, file_get_contents($file));

            if ($uploadResult) {
                $avatarFile = $user->files()->create([
                    'name' => $fileName,
                    'url' => $uploadResult,
                    'description' => $user->get_name,
                    'extension' => $fileFormat,
                    'size' => $fileSize,
                    'resolution' => $imageResolution,
                    'type' => $fileType,
                ]);

                $avatar = $avatarFile->id;
            }
        }

        return $avatar;
    }

    /** get ip location details */
    public function ipDetails($IPaddress)
    {
        $response = Http::timeout(4)->get("https://iplocate.io/api/lookup/" . $IPaddress);
        $details = $response->object();
        return $details;
    }

    /** validate user sessions */
    public function getSessions(User $user)
    {
        $sessions = Token::where('user_id', $user->id)->where('used', true)->select('id', 'user_id', 'ip', 'meta', 'created_at')->orderBy('created_at', 'desc')->paginate(20);

        foreach ($sessions as $session) {
            $deviceMeta = unserialize($session->meta);
            if ($deviceMeta['location'] == null) {
                try {
                    $location = $this->ipDetails($session->ip);
                    $deviceMeta['location'] = [
                        'country' => $location->country,
                        'city' => $location->city,
                        'latitude' => $location->country,
                        'longitude' => $location->country
                    ];
                    $session->update([
                        'meta' => serialize($deviceMeta)
                    ]);
                } catch (\Exception $e) {
                    $deviceMeta['location'] = null;
                }
            }
        }

        return $sessions;
    }
}
