<?php

namespace App\Repositories\Api;

use App\Models\Asset;
use App\Models\AssetType;
use DB;

class SearchAssetRepository extends AbstractApiRepository
{
    public function getJoinedAssetQuery()
    {
        $assets = Asset::with(['user', 'location', 'chromebook', 'jamf', 'intune', 'airwatch'])
            ->with(['assetHistoryCreated:created_by', 'assetHistoryCreated.user', 'latestAssetHistory'])
            ->with(['parentAsset:id,asset_tag,serial_no', 'childrenAsset:id,asset_tag,serial_no'])
            ->with(['carrier', 'makeAndModel', 'makeAndModel.manufacturer', 'assetType', 'technicalSpec', 'assetStatus', 'assetTracking']);

        return $assets;
    }

    /**
     * simple search throgh assets
     * @param mixed $assets
     * @param mixed $search
     *
     * @return [type]
     */
    public function searchAssetsWithGeneralQueries($assets, $search)
    {
        if ($search == '') {
            return $assets;
        }

        foreach (config('api-filter-fields.assets.filter_fields') as $key => $value) {
            if ($key == 0) {
                $assets->where($value, 'like', $search . '%');
            } else {
                $assets->orWhere($value, 'like', $search . '%');
            }
        }

        foreach (config('api-filter-fields.assets.relational_filter_fields') as $key => $value) {
            if ($key == 'email') {
                $assets->orWhereHas('user', function ($query) use ($search) {
                    $query->where('first_name', 'like', $search . '%')
                        ->orWhere('last_name', 'like', $search . '%')
                        ->orWhereRaw("CONCAT(`first_name`, ' ', `last_name`) like ?", [$search . '%'])
                        ->orWhere('email', 'like', $search . '%');
                });
            } else {
                $assets->orWhereHas($value['relation'], function ($query) use ($search, $value) {
                    $query->where($value['db_field'], 'like', '%' . $search . '%');
                });
            }
        }


        return $assets;
    }

    /**
     * Search Joined manufacturer and makeand model name
     * @param mixed $assets
     * @param mixed $search
     *
     * @return [type]
     */
    public function searchAssetWithHardwareStandard($assets, $search)
    {
        if ($search == '') {
            return $assets;
        }

        $search = explode(',', $search);
        if (($key = array_search('', $search)) !== false) {
            unset($search[$key]);
        }

        $assets  = $assets->select('assets.*')->leftJoin('make_and_models', 'assets.make_and_model_id', '=', 'make_and_models.id')->leftJoin('manufacturers', 'manufacturers.id', '=', 'make_and_models.manufacturer_id');

        foreach ($search as $key => $element) {
            if ($key == 0) {
                $assets->whereRaw("CONCAT(`manufacturers`.`name`, ' - ', `make_and_models`.`name`) LIKE ?", [$element . '%']);
            } else {
                $assets->orWhereRaw("CONCAT(`manufacturers`.`name`, ' - ', `make_and_models`.`name`) LIKE ?", [$element . '%']);
            }
        }

        return $assets;
    }

    /**
     * Search by user status
     * @param mixed $assets
     * @param mixed $search
     *
     * @return [type]
     */
    public function searchAssetWithEmployeeStatus($assets, $search)
    {
        if ($search == '') {
            return $assets;
        }
        return $assets->whereHas('user', function ($query) use ($search) {
            if (in_array($search, ['active', 'Active', 'true', 1])) {
                $query->where('status', 1);
            }

            if (in_array($search, ['inactive', 'Inactive', 'false'])) {
                $query->where('status', 0);
            }
        });
    }


    /**
     * Append terminated user asset condition with main query
     * @param mixed $assets
     *
     * @return [type]
     */
    public function getTerminatedUserAssets($assets)
    {
        return $assets->whereHas('user', function ($query) {
            $query->where('status', 0);
        });
    }


    /**
     * Search Assets Within Terminated From and to Dates
     * @param mixed $assets
     * @param mixed $search
     *
     * @return [type]
     */
    public function searchAssetsWithinTerminatedDates($assets, $fromDate = null, $toDate = null)
    {
        if ($fromDate || $toDate) {
            return $assets->whereHas('user', function ($query) use ($fromDate, $toDate) {
                if ($fromDate) {
                    $query->whereDate('terminated_date', '>=', convert_to_db_date($fromDate));
                }
                if ($toDate) {
                    $query->whereDate('terminated_date', '<=', convert_to_db_date($toDate));
                }
            });
        }

        return $assets;
    }

    /**
     * Filter asset using user
     * @param mixed $assets
     * @param mixed $search
     *
     * @return [type]
     */
    public function searchAssetWithUserFIelds($assets, $search)
    {
        if ($search == '') {
            return $assets;
        }
        $search = explode(',', $search);
        if (($key = array_search('', $search)) !== false) {
            unset($search[$key]);
        }
        $assets->whereHas('user', function ($query) use ($search) {
            foreach ($search as $key => $element) {
                if ($key == 0) {
                    $query->where('first_name', 'like', $element . '%')
                        ->orWhere('last_name', 'like', $element . '%')
                        ->orWhereRaw("CONCAT(`first_name`, ' ', `last_name`) like ?", [$element . '%']);
                    if (filter_var($element, FILTER_VALIDATE_EMAIL)) {
                        $query->orWhere('email', 'like', $element . '%');
                    }
                } else {
                    $query->orWhere('first_name', 'like', $element . '%')
                        ->orWhere('last_name', 'like', $element . '%')
                        ->orWhereRaw("CONCAT(`first_name`, ' ', `last_name`) like ?", [$element . '%']);
                    if (filter_var($element, FILTER_VALIDATE_EMAIL)) {
                        $query->orWhere('email', 'like', $element . '%');
                    }
                }
            }
        });

        return $assets;
    }
}
