<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Admin\app\Models\Technical;
use Modules\Admin\app\Models\TechnicalUser;
use App\Traits\AnalyzeData;
use App\Traits\HasFilterRequest;
use App\Traits\HasOrderByRequest;
use App\Traits\HasSearchRequest;
use Modules\Admin\app\Models\Admin;

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

    public function getAllUsers()
    {
        $users = Admin::where('permission', 'like', '%staff%')->get()->toArray();
        return AbstractController::ResultSuccess($users);
    }

    public function getAllTechnical(Request $request)
    {
        $technicals = new Technical;

        // Order by
        $this->orderByRequest($technicals, $request);

        $technicals->orderBy('name', 'asc');
        // Filter
        $this->filterRequest(
            builder: $technicals,
            request: $request,
            filterKeys: [
                'name' => self::F_TEXT,
                'level' => self::F_TEXT,
            ]
        );

        $this->searchRequest(
            builder: $technicals,
            value: $request->get('search'),
            fields: [
                'name',
                'level'
            ]
        );

        $responseData = $technicals->get();

        return AbstractController::ResultSuccess($responseData);
    }

    public function createTechnical(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'level' => 'nullable|integer|min:1|max:3',
        ]);
        $technical = Technical::create([
            'name' => $request->name,
            'level' => $request->level,
        ]);

        return AbstractController::ResultSuccess($technical, "Technical created successfully!");
    }

    public function deleteTechnical(Request $request)
    {
        $id = $request->input('id');
        $technical = Technical::find($id);
        if (!$technical) {
            return AbstractController::ResultError("Technical not found");
        }
        $technical->delete();
        return AbstractController::ResultSuccess("Technical deleted successfully!");
    }

    public function getTechnicalsByUserId($userId)
    {
        $technicalData = self::getDataTechnicalsByUserId($userId);
        return AbstractController::ResultSuccess($technicalData);

        // // Lấy tất cả các technical
        // $allTechnicals = Technical::all();

        // if ($technicals->isEmpty() && $allTechnicals->isEmpty()) {
        //     return AbstractController::ResultError("No technicals found.");
        // }

        // // Chuẩn bị dữ liệu để trả về
        // $technicalData = $allTechnicals->map(function ($technical) use ($technicals) {
        //     // Tìm kiếm kỹ thuật từ bảng technical_users
        //     $technicalUser = $technicals->firstWhere('technical_id', $technical->id);

        //     return [
        //         'id' => $technical->id,
        //         'name' => $technical->name,
        //         'level' => $technical->level,
        //         'point' => $technicalUser ? $technicalUser->point : 0, // Nếu không tồn tại, điểm mặc định là 0
        //         'updated_at' => $technicalUser ? $technicalUser->updated_at : null // Nếu không tồn tại, updated_at là null
        //     ];
        // });
        // $sortedTechnicalData = $technicalData->sortByDesc('point')->values(); // values() để giữ lại chỉ số


        // return AbstractController::ResultSuccess($sortedTechnicalData);
    }

    public static function getDataTechnicalsByUserId($userId)
    {
        $technicals = TechnicalUser::with('technical')
            ->where('user_id', $userId)
            ->where('point', '>', 0)
            ->orderBy('point', 'desc')
            ->orderBy('updated_at', 'desc')
            ->get();
        if ($technicals->isEmpty()) {
            return [];
        }

        // Chuẩn bị dữ liệu để trả về
        $technicalData = $technicals->map(function ($technicalUser) {
            return [
                'id' => $technicalUser->technical->id,
                'name' => $technicalUser->technical->name,
                'level' => $technicalUser->technical->level,
                'point' => $technicalUser->point,
                'updated_at' => $technicalUser->updated_at
            ];
        });
        return $technicalData;
    }


    public function getTechnicalsOfUser()
    {
        $userInfo = auth('admins')->user();
        $userId = $userInfo->id;
        $technicals = TechnicalUser::with('technical')
            ->where('user_id', $userId)
            ->get();

        // if ($technicals->isEmpty()) {
        //     return AbstractController::ResultError("No technicals found for this user.");
        // }

        // // Chuẩn bị dữ liệu để trả về
        // $technicalData = $technicals->map(function ($technicalUser) {
        //     return [
        //         'id' => $technicalUser->technical->id,
        //         'name' => $technicalUser->technical->name,
        //         'level' => $technicalUser->technical->level,
        //         'point' => $technicalUser->point,
        //         'updated_at' => $technicalUser->updated_at
        //     ];
        // });
        // return AbstractController::ResultSuccess($technicalData);


        $allTechnicals = Technical::all();

        if ($technicals->isEmpty() && $allTechnicals->isEmpty()) {
            return AbstractController::ResultError("No technicals found.");
        }

        // Chuẩn bị dữ liệu để trả về
        $technicalData = $allTechnicals->map(function ($technical) use ($technicals) {
            // Tìm kiếm kỹ thuật từ bảng technical_users
            $technicalUser = $technicals->firstWhere('technical_id', $technical->id);

            return [
                'id' => $technical->id,
                'name' => $technical->name,
                'level' => $technical->level,
                'point' => $technicalUser ? $technicalUser->point : 0, // Nếu không tồn tại, điểm mặc định là 0
                'updated_at' => $technicalUser ? $technicalUser->updated_at : null // Nếu không tồn tại, updated_at là null
            ];
        });
        $sortedTechnicalData = $technicalData->sortByDesc('point')->values(); // values() để giữ lại chỉ số


        return AbstractController::ResultSuccess($sortedTechnicalData);
    }

    public function getListUserByTechnicalId($technicalId)
    {
        $users = TechnicalUser::with('user')
            ->where('technical_id', $technicalId)
            ->get();

        if ($users->isEmpty()) {
            return AbstractController::ResultError("No users found for this technical.");
        }
        $userData = $users->map(function ($technicalUser) {
            if ($technicalUser->user) {
                return [
                    'user_id' => $technicalUser->user->id ?? "",
                    'name' => $technicalUser->user->name,
                    'email' => $technicalUser->user->email,
                    'point' => $technicalUser->point
                ];
            }
        });

        return AbstractController::ResultSuccess($userData);
    }

    public function updateTechnicalsUser(Request $request)
    {
        $userInfo = auth('admins')->user();

        $validatedData = $request->validate([
            'technicals' => 'required|array',
            'technicals.*.technical_id' => 'required|exists:technicals,id', // Phải tồn tại trong bảng technicals
            'technicals.*.point' => 'required|integer|min:0|max:3', // Điểm trong khoảng [0-3]
        ]);

        $existingTechnicals = TechnicalUser::where('user_id', $userInfo->id)->get()->keyBy('technical_id');
        
        foreach ($validatedData['technicals'] as $technical) {
            $existingTechnical = $existingTechnicals->get($technical['technical_id']);
            if ($existingTechnical) {
                // Nếu technical_id đã tồn tại và point khác, thì update
                if ($existingTechnical->point !== $technical['point']) {
                    $existingTechnical->update([
                        'point' => $technical['point']
                    ]);
                }
            } else {
                // Nếu technical_id chưa tồn tại, tạo mới
                TechnicalUser::create([
                    'user_id' => $userInfo->id,
                    'technical_id' => $technical['technical_id'],
                    'point' => $technical['point']
                ]);
            }
        }

        return AbstractController::ResultSuccess('Technicals for user updated successfully.');
    }
}
