<?php

namespace App\Repositories\Backend\License;

use App\Models\License;
use App\Models\Auth\User;
use App\Models\LicenseType;
use App\Models\LicenseLedger;
use App\Models\Auth\UserDetail;
use App\Models\LicenseMacMapping;
use Illuminate\Support\Facades\DB;
use App\Exceptions\GeneralException;
use App\Repositories\BaseRepository;

/**
 * Class SocialRepository.
 */
class LicenseRepository extends BaseRepository
{
    /**
     * PermissionRepository constructor.
     *
     * @param  LicenseType  $model
     */
    public function __construct(LicenseType $model)
    {
        $this->model = $model;
    }

    /**
     * @param int    $param
     *
     * @return mixed
     */
    public function getUserParticularLicense($param)
    {
        $userResult = null;
        $user = User::where('email', $param)->first();

        if ($user) {
            $userResult = UserDetail::with(['user'])->where('user_id', $user->id)->first();
        }

        return $userResult;
    }

    /**
     * @param array $data
     *
     * @throws \Exception
     * @throws \Throwable
     * @return User
     */
    public function create(array $data)
    {
        return DB::transaction(function () use ($data) {
            $licensetype = LicenseType::create([
                'name' => $data['name'],
                'duration' => $data['duration'],
                'status' => $data['status'],
                'licence_type' => $data['licensekey'],
            ]);
        });

        return $licensetype;
    }

    /**
     * @param int    $paged
     * @param string $orderBy
     * @param string $sort
     *
     * @return mixed
     */
    public function getActivePaginated($paged = 25, $orderBy = 'created_at', $sort = 'desc')
    {
        return LicenseType::orderBy($orderBy, $sort)
            ->paginate($paged);
    }

    /**
     * @param Role  $role
     * @param array $data
     *
     * @throws GeneralException
     * @throws \Throwable
     * @return mixed
     */
    public function update(LicenseType $licenseType, array $data)
    {
        return DB::transaction(function () use ($licenseType, $data) {
            if ($licenseType->update([
                'name' => $data['name'],
                'duration' => $data['duration'],
                'status' => $data['status'],
                'licence_type' => $data['licensekey'],
            ])) {
                return $licenseType;
            }

            throw new GeneralException(trans('exceptions.backend.access.license.licensetype.update_error'));
        });
    }

    /**
     * @param int    $param
     *
     * @return mixed
     */
    public function setStoreLicense($param)
    {
        $userResult = null;
        $user = User::where('email', $param['tags_license'])->first();
    
        
        if ($user) {
            if (isset(auth()->user()->userDetails[0]) && auth()->user()->userDetails[0]->credit == 0) {
                throw new GeneralException(__('exceptions.backend.access.license.erroramount'));
            }
           
            $license = License::create([
                'key_uuid' => hexdec(uniqid()),
                'licenseTypeId' => $param['licensekey'],
                'status' => 'active',
                'licenseUserId' => $user->id,
                'refferalUserId' => auth()->user()->id,
            ]);
            $debit = (int) auth()->user()->userDetails[0]->credit - 1;
            $authuserDetails = UserDetail::with(['user'])->where('user_id', auth()->user()->id)->first();
            $authuserDetails->credit = $debit;
            $authuserDetails->save();
        }

        return $license;
    }

    public function getActiveLicensePaginated($paged = 25, $orderBy = 'created_at', $sort = 'desc')
    {
        //dd(auth()->user()->id);
        $licenseUser = [];
        array_push($licenseUser, auth()->user()->id);
        $query = License::orderBy($orderBy, $sort);
        //dd(auth()->user()->userDetails[0]->parentDetails);
        if (auth()->user()->roles[0]->id != 1) {
            $userIds = UserDetail::where('parent', auth()->user()->id)->pluck('user_id')->toArray();
            $licenseUser = array_merge($licenseUser, $userIds);
            $query = $query->whereIn('refferalUserId', $licenseUser);
        }

        return $query->paginate($paged);
    }

    public function getLicenseMac($data)
    {
        $id = ($data != null) ? $data->id : 0;
        $licenceMac = LicenseMacMapping::where('macDetailId', $id)->pluck('lincensekeyId');

        return $query = License::whereIn('id', $licenceMac)->paginate(50);
    }

    public function getLicenseByKey(string $uuid)
    {
        return License::where('key_uuid', $uuid)->paginate(50);
    }

    /**
     * Update license with related macs and mappings
     * 
     * @author Jansen N. J <jansen@riolabz.com>
     */
    public function setLicenseMacUpdate($data)
    {
        $licenseStatus = $data['licensestatus'] == null ? 'inactive' : 'active';

        $macs = $data['mac'] ?: [];

        $licenseMac = LicenseMacMapping::where('lincensekeyId', $data['licenseId'])
            ->get();

        License::findOrFail($data['licenseId'])
            ->update(['status' => $licenseStatus]);

        LicenseMacMapping::where('lincensekeyId', $data['licenseId'])
            ->update(['license_key_status' => $licenseStatus]);

        $licenseMac->each(
            function ($mapping) use ($macs) {
                $macAddress = $mapping->macDetail->mac_uuib;

                $macStatus = \in_array($macAddress, $macs) ? 'active' : 'inactive';

                $mapping->update(['mac_status' => $macStatus]);

                $mapping->macDetail->update(['status' => $macStatus]);
            }
        );
    }

    public function getActiveIpPaginated($paged = 25, $orderBy = 'created_at', $sort = 'desc', $macId)
    {
        //dd(auth()->user()->id);
        $licenseUser = [];

        $query = LicenseLedger::orderBy($orderBy, $sort)->where('macDetailId', $macId);

        return $query->paginate($paged);
    }
}
