<?php

// ========================
// 📦 Imports (استدعاء الكلاسات)
// ========================
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\DB;
use function Symfony\Component\String\u;

use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\SettingController;

use App\Models\User;
use App\Models\Category;
use App\Models\Question;
use App\Models\UserLike;


// ========================
// ⚙️ Routes عامة (بدون تسجيل دخول)
// ========================

// جلب إعدادات التطبيق
Route::get('/settings', [SettingController::class, 'getSettings']);

// تسجيل مستخدم جديد
Route::post('/register', [AuthController::class, 'register']);

// تسجيل الدخول
Route::post('/login', [AuthController::class, 'login']);

// تسجيل دخول عبر Google
Route::post('/google-login', [AuthController::class, 'googleLogin']);


// ========================
// 🔐 Routes محمية (تحتاج تسجيل دخول)
// ========================
Route::middleware('auth:sanctum')->group(function () {

    // تسجيل الخروج
    Route::post('/logout', [AuthController::class, 'logout']);

    // جلب بيانات المستخدم
    Route::get('/profile', [AuthController::class, 'profile']);

});


// ========================
// 👤 تحديث بيانات المستخدم
// ========================
Route::middleware('auth:sanctum')->post('/update-profile', function (Request $request) {

    $user = $request->user();

    // التحقق من البيانات
    $request->validate([
        'name' => 'nullable|string|max:255',
        'username' => 'nullable|string|max:255|unique:users,username,' . $user->id,
    ]);

    // تحديث الاسم
    if ($request->has('name')) {
        $user->name = $request->name;
    }

    // تحديث اليوزرنيم
    if ($request->has('username')) {
        $user->username = $request->username;
    }

    $user->save();

    return response()->json([
        'message' => 'تم التحديث',
        'user' => $user
    ]);
});


// ========================
// 📂 الأقسام (Categories)
// ========================

// جلب كل الأقسام
Route::get('/categories', function () {
    return Category::all();
});

// جلب الأقسام المميزة فقط
Route::get('/featured-categories', function () {
    return Category::where('is_featured', true)->get();
});

// إنشاء قسم جديد
Route::post('/categories', function (Request $request) {
    return Category::create([
        'name' => $request->name,
        'image' => $request->image,
        'is_featured' => $request->is_featured,
    ]);
});


// ========================
// ❓ الأسئلة (Questions)
// ========================

// جلب الأسئلة حسب القسم
Route::get('/categories/{id}/questions', function ($id) {
    return Question::where('category_id', $id)->get();
});

// إضافة سؤال جديد
Route::post('/questions', function (Request $request) {
    return Question::create([
        'category_id' => $request->category_id,
        'question' => $request->question,
        'option1' => $request->option1,
        'option2' => $request->option2,
        'option3' => $request->option3,
        'option4' => $request->option4,
        'correct_answer' => $request->correct_answer,
        'time' => $request->time,
        'points' => $request->points,
    ]);
});


// ========================
// 🏆 ترتيب المستخدمين (Leaderboard)
// ========================
Route::get('/leaderboard', function () {
    return User::orderBy('points', 'desc')
        ->take(10)
        ->get(['id', 'name', 'photo', 'points', 'user_code']);
});


// ========================
// 👤 عرض بروفايل مستخدم عام
// ========================
Route::middleware('auth:sanctum')->get('/user/public/{code}', function (Request $request, $code) {

    $user = User::where('user_code', $code)->first();

    if (!$user) {
        return response()->json([
            'message' => 'User not found'
        ], 404);
    }

    return response()->json([
        'user' => [
            'name' => $user->name,
            'username' => $user->username,
            'level' => $user->level,
            'points' => $user->points,
            'likes' => $user->likes,
            'photo' => $user->photo,
            'is_verified' => $user->is_verified,
        ]
    ]);
});


// ========================
// ❤️ نظام اللايكات
// ========================
Route::middleware('auth:sanctum')->post('/toggle-like/{code}', function (Request $request, $code) {

    $user = $request->user();

    $targetUser = User::where('user_code', $code)->first();

    if (!$targetUser) {
        return response()->json(['message' => 'User not found'], 404);
    }

    // منع المستخدم من عمل لايك لنفسه
    if ($user->user_code === $targetUser->user_code) {
        return response()->json(['message' => 'Cannot like yourself'], 400);
    }

    $existing = UserLike::where('user_id', $user->user_code)
        ->where('liked_user_id', $targetUser->user_code)
        ->first();

    if ($existing) {

        // 🔴 إزالة اللايك
        $existing->delete();
        $targetUser->decrement('likes');

        return response()->json([
            'liked' => false,
            'likes' => $targetUser->likes
        ]);

    } else {

        // 🟢 إضافة لايك
        UserLike::create([
            'user_id' => $user->user_code,
            'liked_user_id' => $targetUser->user_code,
        ]);

        $targetUser->increment('likes');

        return response()->json([
            'liked' => true,
            'likes' => $targetUser->likes
        ]);
    }
});


// ========================
// ⭐ تحديث النقاط
// ========================
Route::middleware('auth:sanctum')->post('/update-points', function (Request $request) {

    $user = $request->user();

    $user->points += $request->points;
    $user->answered_questions += 1;

    $user->save();

    return response()->json([
        'user' => $user
    ]);
});


// ========================
// ❌ حذف الحساب (حاليًا وهمي)
// ========================
Route::middleware('auth:sanctum')->post('/delete-account', function (Request $request) {

    return response()->json([
        'message' => 'تم حذف الحساب بنجاح',
    ]);
});


// ========================
// 🩺 فحص السيرفر (Health Check)
// ========================
Route::get('/health', function () {
    return response()->json(['status' => 'OK'], 200);
});