<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\JiraService;
use App\Traits\AnalyzeData;
use App\Traits\HasFilterRequest;
use App\Traits\HasOrderByRequest;
use App\Traits\HasSearchRequest;
use Illuminate\Http\Request;
use Modules\Admin\app\Models\Sprint;
use Modules\Admin\app\Models\UserCriteria;

class ProfileController extends Controller
{
    use HasOrderByRequest;
    use HasFilterRequest;
    use HasSearchRequest;
    use AnalyzeData;

    protected $jiraService;

    public function __construct(JiraService $jiraService)
    {
        $this->jiraService = $jiraService;
    }

    public function getProfilesData()
    {
        $user = auth('admins')->user();

        $userEmail = $user->email;
        $projects = $this->jiraService->getAllProjects();

        $userCriterias = UserCriteria::with([
            'sprint',   // Join với bảng sprint
            'criteria', // Join với bảng criteria
        ])->where('user_email', $userEmail)->get();

        // Xử lý dữ liệu thành cấu trúc mong muốn
        $projectsData = $userCriterias->groupBy('sprint.project_id')->map(function ($userCriteriasByProject, $projectId) use ($projects) {
            $result = self::getProjectById($projects, $projectId);
            return [
                'name' => $result['name'],
                'sprints' => $userCriteriasByProject->groupBy('sprint.id')->map(function ($userCriteriasBySprint) {
                    $sprint = $userCriteriasBySprint->first()->sprint;
                    return [
                        'name' => $sprint->name,
                        'criterias' => $userCriteriasBySprint->map(function ($userCriteria) {
                            $criteria = $userCriteria->criteria;
                            return [
                                'criteria' => $criteria->name,
                                'note' => $userCriteria->note ?? '',
                                'createdBy' => $userCriteria->created_by ?? '', // Lấy tên user từ auth
                                'point' => $userCriteria->point ?? '',
                            ];
                        })
                    ];
                })->values()
            ];
        })->values();

        // Trả về kết quả
        return AbstractController::ResultSuccess($projectsData);
    }

    public function getProjectById($projects, $inputId)
    {
        $filteredProjects = array_filter($projects, function ($project) use ($inputId) {
            return $project['id'] == $inputId;
        });
        return array_values($filteredProjects) ? array_values($filteredProjects)[0] : array_values($filteredProjects);
    }
}
