<?php

namespace App\Repositories\SoftwareLicense;

use App\Models\SoftwareLicense\SoftwareLicenseUser;

/**
 * Software License user Repository
 */
class LicenseUserRepository
{

    /**
     * List Software License users
     */
    public function getLicenseUsers($licenseId)
    {
        return SoftwareLicenseUser::with(['license', 'user', 'licenseKey', 'zoomMember'])->where('software_license_id', $licenseId);
    }

    /**
     * filters with exact match with the serch value 
     */
    public function filterByExactMatch($licenseUsers, $filterKey, $filterValue)
    {
        if (is_array($filterValue)) {
            return  $licenseUsers->whereIn($filterKey, $filterValue);
        }

        return $licenseUsers->where($filterKey, $filterValue);
    }

    /**
     * filters with date range match with the serch value 
     */
    public function filterByDateRangeMatch($licenseUsers, $filterKey, $filterValue)
    {
        if (strpos($filterKey, '_from') !== false) {
            return $licenseUsers = $licenseUsers->whereDate(str_replace('_from', '', $filterKey), '>=', convert_to_db_date($filterValue));
        }

        if (strpos($filterKey, '_to') !== false) {
            return  $licenseUsers = $licenseUsers->whereDate(str_replace('_to', '', $filterKey), '<=', convert_to_db_date($filterValue));
        }

        return $licenseUsers;
    }

    /**
     * filters based on  user status(active or terminated)
     */
    public function filterByUserStatus($licenseUsers, $filterKey, $filterValue)
    {

        return  $licenseUsers->whereHas(str_replace('_status', '', $filterKey), function ($licenseUsers) use ($filterValue) {
            if ($filterValue == 1) {

                return $licenseUsers->active();
            }
            if ($filterValue == 2) {

                return  $licenseUsers->inActive();
            }
            return  $licenseUsers;
        });
    }

    /**
     * filters with text match with the serch value
     */
    public function filterByUserTextMatch($licenseUsers, $searchText)
    {
        return  $licenseUsers->where(function ($licenseUsers) use ($searchText) {
            $licenseUsers->where('name', 'like', $searchText . '%')
                ->orWhere('email', 'like', $searchText . '%');
        });
    }
}
