<?php

namespace App\Repositories\DiscoveryTools;

use App\Models\KandjiDevices;
use App\Models\AssetStatus;
use App\Models\Asset;
use App\Models\AssetType;
use App\Models\Manufacturer;
use DB;

class KandjiRepository extends AbstractRepository
{
    /**
     * Making query for All kandji report
     */
    public function getAllDevices()
    {
        $assets = KandjiDevices::with(
            'asset',
            'user:id,first_name,last_name,email,status,department_id',
            'user.department:id,name',
            'asset.assetStatus',
            'mobileCarrier:id,name,country_id',
            'mobileCarrier.country:id,name',
            'asset.makeAndModel',
            'asset.assetType',
            'asset.makeAndModel.manufacturer',
            'asset.location:id,room_name',
            'asset.user:id,first_name,last_name,email,status,department_id,city',
            'asset.user.department:id,name',
            'asset.latestAssetHistory:id,asset_id,updated_at'
        );

        return $assets;
    }

    /**
     * Devices not created
     */
    public function getAssetsNotCreated()
    {
        return KandjiDevices::with(
            'asset',
            'user:id,first_name,last_name,email,status,department_id',
            'user.department:id,name',
            'asset.assetStatus',
            'asset.makeAndModel',
            'asset.assetType',
            'mobileCarrier:id,name,country_id',
            'mobileCarrier.country:id,name',
            'asset.makeAndModel.manufacturer',
            'asset.location:id,room_name',
            'asset.user:id,first_name,last_name,email,status,department_id,city',
            'asset.user.department:id,name',
            'asset.latestAssetHistory:id,asset_id,updated_at'
        )->where('asset_id', 0);
    }

    /**
     * Making query for User Mismatch report
     */
    public function getUserMismatchDevices()
    {
        $statusId   = AssetStatus::whereIn('slug', ['assigned'])->get()->pluck('id');
        $assets = KandjiDevices::select('kandji_devices.*')->with(
            'asset',
            'user:id,first_name,last_name,email,status,department_id',
            'user.department:id,name',
            'asset.assetStatus',
            'mobileCarrier:id,name,country_id',
            'mobileCarrier.country:id,name',
            'asset.makeAndModel',
            'asset.assetType',
            'asset.makeAndModel.manufacturer',
            'asset.location:id,room_name',
            'asset.user:id,first_name,last_name,email,status,department_id,city',
            'asset.user.department:id,name',
            'asset.latestAssetHistory:id,asset_id,updated_at'
        )
            ->join("assets", function ($join) use ($statusId) {
                $join->on('assets.serial_no', '=', 'kandji_devices.serial_no')
                    ->on('assets.user_id', '<>', 'kandji_devices.user_id')
                    ->whereIn('assets.asset_status_id', $statusId);
            });

        return $assets;
    }

    /**
     * Making query for DevicesNotActive report
     */
    public function getDevicesNotActive()
    {
        $statusId = AssetStatus::whereIn('slug', ['assigned', 'loaned'])->get()->pluck('id');

        $assets = KandjiDevices::with(
            'asset',
            'user:id,first_name,last_name,email,status,department_id',
            'user.department:id,name',
            'asset.assetStatus',
            'asset.makeAndModel',
            'asset.assetType',
            'mobileCarrier:id,name,country_id',
            'mobileCarrier.country:id,name',
            'asset.makeAndModel.manufacturer',
            'asset.location:id,room_name',
            'asset.user:id,first_name,last_name,email,status,department_id,city',
            'asset.user.department:id,name',
            'asset.latestAssetHistory:id,asset_id,updated_at'
        )
            ->where('last_checkin', '<', \Carbon\Carbon::now()->subDays(30))
            ->whereHas('asset', function ($query) use ($statusId) {
                $query->whereIn('asset_status_id', $statusId);
            });

        return $assets;
    }

    /**
     * Making query for  'Not checking in, not Managed & deployed' report
     */
    public function getNotManaged()
    {
        $statusId    = AssetStatus::whereIn('slug', ['assigned', 'loaned'])->get()->pluck('id');
        $assetTypeId = AssetType::whereIn('slug', ['laptop', 'mobile_phone', 'tablet', 'computer'])->get()->pluck('id');

        $query       = Asset::select('assets.*')
            ->with(
                'user:id,first_name,last_name,email,status,department_id',
                'user.department:id,name',
                'assetStatus',
                'makeAndModel',
                'carrier:id,name,country_id',
                'carrier.country:id,name',
                'assetType',
                'makeAndModel.manufacturer',
                'location:id,room_name',
                'latestAssetHistory:id,asset_id,updated_at'
            )
            ->whereIn('asset_status_id', $statusId)
            ->whereIn('asset_type_id', $assetTypeId)
            ->doesntHave('airwatch')
            ->doesntHave('chromebook')
            ->doesntHave('intune')
            ->doesntHave('jamf')
            ->doesntHave('KandjiDevices')
            ->doesntHave('mobileIron')
            ->whereHas('makeAndModel', function ($query) {
                $query->whereHas('manufacturer', function ($query) {
                    $query->where('name', 'Apple');
                }); // Assuming the manufacturer relationship is correctly defined in the MakeAndModel model.
            });

        return $query;
    }

    /**
     * Making query for Devices On Hand Checked In report
     */
    public function getDevicesOnHandCheckedIn()
    {
        $statusId   = AssetStatus::onHandStatuses()->get()->pluck('id');
        $query      = KandjiDevices::select('kandji_devices.*')
            ->with(
                'asset',
                'user:id,first_name,last_name,email,status,department_id',
                'user.department:id,name',
                'asset.assetStatus',
                'asset.makeAndModel',
                'mobileCarrier:id,name,country_id',
                'mobileCarrier.country:id,name',
                'asset.assetType',
                'asset.makeAndModel.manufacturer',
                'asset.location:id,room_name',
                'asset.user:id,first_name,last_name,email,status,department_id,city',
                'asset.user.department:id,name',
                'asset.latestAssetHistory:id,asset_id,updated_at'
            )
            ->join("assets", function ($join) {
                $join->on('assets.id', '=', 'kandji_devices.asset_id');
            })
            ->where('kandji_devices.last_checkin', '>', DB::raw('assets.last_status_update'))
            ->whereIn('assets.asset_status_id', $statusId);

        return $query;
    }

    /**
     * To populate data in some of kadji reports filters
     * @param mixed $search
     * @param mixed $type
     *
     * @return [type]
     */
    public function filterField($search, $type)
    {
        if ($type == 'userName') {
            $res = KandjiDevices::distinct('email')->select('email', 'user_name')
                ->where(function ($query) use ($search) {
                    $query->where('user_name', 'like', $search . '%')
                        ->orWhere('email', 'like', $search . '%');
                })
                ->limit(15)->get();

            $result = $res->mapWithKeys(function ($item, $key) {
                return [
                    $key => [

                        'id' => $item->email,
                        'text' => $item->user_name . ' - ' . $item->email,
                    ]
                ];
            });
            return $result;
        }

        $res = KandjiDevices::distinct()->select("$type")->where("$type", 'like', '%' . $search . '%')->get();
        $result = $res->mapWithKeys(function ($item, $key) use ($type) {
            return [
                $key => [
                    'id' => $item[$type],
                    'text' => $item[$type],
                ]
            ];
        });

        return $result;
    }
}
