<?php

namespace App\Repositories\Dashboard;

use App\Models\Asset;
use App\Models\Region;
use Carbon\Carbon;
use Cache;

class DashboardRepository
{
    public function assetsInStatus($statusId)
    {
        return Asset::where('asset_status_id', $statusId);
    }

    public function assetsInStatuses($status)
    {
        return Asset::whereHas('assetStatus', function ($query) use ($status) {
            $query->whereIn('slug', $status);
        });
    }

    public function getAssetCreated($months)
    {
        $firstDayCurrentMonthLastYear = first_day_current_month_year();
        $assets = Asset::select('id', 'created_at')->whereDate('created_at', '>=', $firstDayCurrentMonthLastYear)->get();
        $assetsGroupedByMonth =  group_by_months($assets);

        return $this->getFormattedData($assetsGroupedByMonth, $months);
    }

    public function getFormattedData($assets, $months)
    {
        $formattedData = [];
        $i = 0;
        $firstDayCurrentMonthLastYear = first_day_next_month_last_year();
        $assetCountByMonth = Asset::whereDate('created_at', '<', $firstDayCurrentMonthLastYear)->count();
        foreach ($months as $monthNumber => $monthName) {
            $i++;
            $monthCount = $assets->get($monthNumber);
            $formattedData[] = [
                'month' => '2017-' . $i,
                'asset' => $assetCountByMonth += is_countable($monthCount) ? count($monthCount) : 0
            ];
        }

        return $formattedData;
    }

    public function getRegionTotalAssets()
    {
        return Region::selectRaw('count(assets.id) as count, regions.id')
            ->join('locations', 'locations.region_id', '=', 'regions.id')
            ->join('assets', 'assets.location_id', '=', 'locations.id')
            ->join('asset_statuses', 'asset_statuses.id', '=', 'assets.asset_status_id')
            ->whereIn('asset_statuses.slug', ['brand_new', 'used', 'used_loaner'])
            ->groupBy('regions.id');
    }

    public function loanerPastDue()
    {
        return Asset::whereHas('assetStatus', function ($query) {
            $query->where('slug', 'loaned');
        })
            ->whereDate('loaner_return_date', '<', Carbon::today()->toDateString());
    }

    public function loanerDueWeek()
    {
        return Asset::whereHas('assetStatus', function ($query) {
            $query->where('slug', 'loaned');
        })
            ->whereDate('loaner_return_date', '>=', Carbon::now()->startOfWeek()->toDateString())
            ->whereDate('loaner_return_date', '<=', Carbon::now()->endOfWeek()->toDateString());
    }

    public function retentionPastDue()
    {
        return Asset::whereHas('assetStatus', function ($query) {
            $query->where('slug', 'retain_hold');
        })
            ->whereDate('loaner_retention_date', '<', Carbon::today()->toDateString());
    }

    public function retentionDueWeek()
    {
        return Asset::whereHas('assetStatus', function ($query) {
            $query->where('slug', 'retain_hold');
        })
            ->whereDate('loaner_retention_date', '>=', Carbon::now()->startOfWeek()->toDateString())
            ->whereDate('loaner_retention_date', '<=', Carbon::now()->endOfWeek()->toDateString());
    }

    public function leasePastDue()
    {
        return Asset::whereDate('lease_end_date', '<', Carbon::today()->toDateString());
    }

    public function leaseDueWeek()
    {
        return Asset::whereDate('lease_end_date', '>=', Carbon::now()->startOfWeek()->toDateString())
            ->whereDate('lease_end_date', '<=', Carbon::now()->endOfWeek()->toDateString());
    }


    /**
     * fetches data for the widget on the dashboard to show how many computers are available whether brand new or in any used type of status
     * @param mixed $status
     * 
     * @return [type]
     */
    public function getComputerWidgetData($status)
    {
        $assets = Asset::with('assetType', 'assetStatus', 'makeAndModel.manufacturer')
            ->whereHas('assetType', function ($query) {
                $query->whereIn('slug', ['computer', 'laptop', 'desktop']);
            })
            ->whereHas('assetStatus', function ($query) use ($status) {
                $query->whereIn('slug', $status);
            });

        $macAssets = $assets->clone()->whereHas('makeAndModel.manufacturer', function ($query) {
            $query->where('slug', 'apple');
        })->count();

        $pcAssets = $assets->clone()->whereHas('makeAndModel.manufacturer', function ($query) {
            $query->whereIn('slug', config('manufacturer-asset-types.pc'));
        })->whereHas('makeAndModel', function ($query) {
            $query->where('slug', 'not like', '%chromebook%');
        })->count();



        $computersWidgetData['mac_assets'] = $macAssets ?? 0;
        $computersWidgetData['pc_assets'] = $pcAssets ?? 0;
        $computersWidgetData['slug'] = implode(',', $status);

        return $computersWidgetData;
    }
}
