<?php

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

use Illuminate\Support\Facades\Input;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use App\Modules\Bookings\Task;
use App\Modules\Bookings\Repair;
use App\Modules\Bookings\Support;
use App\Modules\Bookings\Onsite;
use App\Modules\Bookings\TaskFeedback;
use App\Modules\Gamification\PointsTransaction;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;

class UserControllerREST extends BaseController
{
    /**
     * Get a summary of the user data for a given period of time.
     *
     * @param  int $id
     *
     * @return array
     */
    public function getSummary(Request $request, $id)
    {
        $user = User::findOrFail($id);

        $data = [
            'name'      => $user->name,
            'user'      => $user,
            'completed' => [
                'repairs' => Repair::query()->repairs()->thisMonth($request->input('start_date'), $request->input('end_date'))->completed_stats()->where('assigned_to', $user->id)->count(),
                'support' => Support::query()->support()->thisMonth($request->input('start_date'), $request->input('end_date'))->completed_stats()->where('assigned_to', $user->id)->count(),
                'onsite'  => Onsite::query()->onsite()->thisMonth($request->input('start_date'), $request->input('end_date'))->completed()->where('assigned_to', $user->id)->count(),
            ],
            'open' => [
                'repairs' => Repair::query()->repairs()->createdThisMonth($request->input('start_date'), $request->input('end_date'))->open()->where('assigned_to', $user->id)->count(),
                'support' => Support::query()->support()->createdThisMonth($request->input('start_date'), $request->input('end_date'))->open()->where('assigned_to', $user->id)->count(),
                'onsite'  => Onsite::query()->onsite()->createdThisMonth($request->input('start_date'), $request->input('end_date'))->open()->where('assigned_to', $user->id)->count(),
                'total'   => Task::query()->where('assigned_to', $user->id)->open()->count(),
            ],
            'income' => [
                'points' => PointsTransaction::query()->where('user_id', $user->id)->sum('amount'),
                'labour' => Task::query()->where('assigned_to', $user->id)->completed()->thisMonth($request->input('start_date'), $request->input('end_date'))->sum('labour'),
                'parts'  => Task::query()->join('parts', 'tasks.id', '=', 'parts.related_id')->where('parts.related_type', 'task')->where('tasks.assigned_to', $user->id)->completed()->thisMonth($request->input('start_date'), $request->input('end_date'))->select(\DB::raw('SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as total'))->first()->total,
            ],
            'rating' => floatval(TaskFeedback::query()->where('user_id', $id)->whereNotNull('rating')->avg('rating')),
        ];

        $data['load'] = round($data['open']['total'] / 15 * 100, 2);

        return response()->json($data);
    }

    /**
     * Returns the labour and points data to be used in a graph.
     *
     * @param  int $id
     *
     * @return array
     */
    public function getGraph(Request $request, $id)
    {
        // Modern date format selection with match expression
        $dateFormat = match ($request->input('view', 'daily')) {
            'weekly' => '%Y-%u',
            'monthly' => '%Y-%m',
            'yearly' => '%Y',
            default => '%Y-%m-%d'
        };

        $start_date = date('Y-m-d H:i:s', $request->input('start_date', time()));
        $end_date = date('Y-m-d H:i:s', $request->input('end_date', time()));

        // Modernized labour query with parameter binding
        $labour = Task::query()
                        ->selectRaw("sum(labour) as cnt, DATE_FORMAT(completed_at, ?) as date", [$dateFormat])
                        ->where('assigned_to', $id)
                        ->completed()
                        ->thisMonth($request->input('start_date'), $request->input('end_date'))
                        ->groupByRaw("DATE_FORMAT(completed_at, ?)", [$dateFormat]);

        // Modernized points query with parameter binding
        $points = PointsTransaction::query()
                                    ->selectRaw("sum(amount) as cnt, DATE_FORMAT(created_at, ?) as date", [$dateFormat])
                                    ->where('user_id', $id)
                                    ->createdRange($request->input('start_date'), $request->input('end_date'))
                                    ->groupByRaw("DATE_FORMAT(created_at, ?)", [$dateFormat]);

        // Fixed wages query - restored original Laravel5 business logic with proper DATE_FORMAT JOIN
        $wages = DB::select("
            SELECT round(sum(pay), 2) as cnt, DATE_FORMAT(q.time, ?) as `date`
            FROM (
                SELECT abs(time_to_sec(TIMEDIFF(a.time, b.time)) / 3600) * (SELECT rate_per_hour FROM hr_user_details WHERE user_id = ?) as pay, a.`time`
                FROM hr_time_log as a
                JOIN hr_time_log as b ON DATE_FORMAT(a.time, '%Y-%m-%d') = DATE_FORMAT(b.time, '%Y-%m-%d') AND a.user_id = b.user_id
                WHERE a.user_id = ? AND a.type = 'in' AND b.type = 'out' AND a.time >= ? AND b.time <= ? AND b.time < NOW()
            ) as q 
            GROUP BY DATE_FORMAT(q.time, ?)",
            [$dateFormat, $id, $id, $start_date, $end_date, $dateFormat]
        );

        // Disable eager loads
        $labour->setEagerLoads([]);

        return [
            'labour' => $labour->get(),
            'points' => $points->get(),
            'wages'  => $wages,
        ];
    }
}
