<?php

namespace App\Modules\Stats\controllers\api\v1;

use Illuminate\Support\Facades\DB;
use App\Modules\Bookings\Task;
use Call;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class CustomerControllerREST extends BaseController
{
    /**
     * Returns the daily data for repairs booked in and repairs completed.
     *
     * @return Illuminate\Support\Response
     */
    public function getActivity(Request $request)
    {
        $data = Task::query()->select(DB::raw('COUNT(id) as total, client_id, client_type'))->createdThisMonth($request->input('start_date'), $request->input('end_date'))->groupBy('client_type')->groupBy('client_id')->orderBy('total', 'desc')->take(50)->get();

        // Load all the client data
        foreach ($data as $key => $value) {
            $data[$key]->total = intval($value->total);
            $data[$key]->client = $value->client;
            $data[$key]->calls = Call::query()->where('client_type', $value->client_type)->where('client_id', $value->client_id)->createdThisMonth($request->input('start_date'), $request->input('end_date'))->count();
        }

        return $data;
    }
}
