<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\JobController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\BlogController;
use App\Http\Controllers\GameController;
use App\Http\Controllers\PageController;
use App\Http\Controllers\PostController;
use App\Http\Controllers\BlockController;
use App\Http\Controllers\EventController;
use App\Http\Controllers\GroupController;
use App\Http\Controllers\MovieController;
use App\Http\Controllers\SpaceController;
use App\Http\Controllers\StoryController;
use App\Http\Controllers\CourseController;
use App\Http\Controllers\FriendController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UserWalletController;
use App\Http\Controllers\MarketplaceController;
use App\Http\Controllers\NotificationController;
use App\Http\Controllers\UnifiedSearchController;
use App\Http\Controllers\Api\LivestreamController;
use App\Http\Controllers\Courses\StudentController;
use App\Http\Controllers\Courses\CourseController as CoursesController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\SettingsController;
use App\Http\Controllers\MessengerController;

// Existing Routes
Route::post('/login', [AuthController::class, 'login']);
Route::post('/social_login', [AuthController::class, 'socialLogin']);

// Public: Site settings (no auth)
Route::get('/get-site-settings', [SettingsController::class, 'getSiteSettingsPublic']);
Route::post('/request-reset', [AuthController::class, 'requestPasswordResetPin']);
Route::post('/reset-password', [AuthController::class, 'resetPasswordUsingPin']);
Route::post('/register', [AuthController::class, 'registerApi']);
Route::post('/send-push', [SettingsController::class, 'sendNotification']);
// Unified Search API routes (accessible without authentication)
Route::prefix('search')->group(function () {
    Route::get('/', [UnifiedSearchController::class, 'search']);
    Route::get('/autocomplete', [UnifiedSearchController::class, 'autocomplete']);
    Route::get('/trending', [UnifiedSearchController::class, 'trending']);
    Route::get('/history', [UnifiedSearchController::class, 'history'])->middleware('auth:sanctum');
    Route::get('/stats', [UnifiedSearchController::class, 'stats'])->middleware('auth:sanctum');
});

Route::middleware('auth:sanctum')->group(function () {




    Route::post('/update-device-token', [NotificationController::class, 'updateDeviceToken']);

    Route::post('/test-push-notification', [NotificationController::class, 'testPushNotification']);
    Route::post('/near-by-users', [ProfileController::class, 'nearByUsers']);




    Route::get('/user-details', [AuthController::class, 'userDetails']);
    Route::post('/logout', [AuthController::class, 'logout']);

    Route::post('/report-module', [UserController::class, 'reportModule']);

    Route::prefix('sessions')->group(function () {
        Route::get('/', [AuthController::class, 'getSessions'])->name('sessions.get');
        Route::post('/delete-session', [AuthController::class, 'deleteSession'])->name('sessions.delete');
    });

    // Messenger API routes (Demo - simplified for frontend testing)
    Route::prefix('messenger')->group(function () {
        Route::get('/conversations', [MessengerController::class, 'getConversations']);
        Route::post('/conversations', [MessengerController::class, 'createConversation']);
        Route::get('/conversations/{conversation}/messages', [MessengerController::class, 'getMessages']);
        Route::post('/conversations/{conversation}/messages', [MessengerController::class, 'sendMessage']);
        Route::get('/conversations/{conversation}/messages/{message}', [MessengerController::class, 'getMessage']);
        Route::put('/conversations/{conversation}/messages/{message}', [MessengerController::class, 'updateMessage']);
        Route::delete('/conversations/{conversation}/messages/{message}', [MessengerController::class, 'deleteMessage']);

        // Conversations with specific user
        Route::get('/conversations/with-user/{userId}', [MessengerController::class, 'getConversationsWithUser']);

        // Users
        Route::get('/users/search', [MessengerController::class, 'searchUsers']);

        // Typing indicators
        Route::post('/typing', [MessengerController::class, 'sendTyping']);

        // Message receipts
        Route::get('/receipts', [MessengerController::class, 'getReceipts']);
        Route::post('/receipts', [MessengerController::class, 'markAsRead']);

        // Real-time updates
        Route::get('/updates', [MessengerController::class, 'getUpdates']);
    });


    // Group all post-related routes together
    Route::prefix('post')->group(function () {
        // Post CRUD operations
        Route::post('create', [PostController::class, 'add_post']);
        Route::post('save', [PostController::class, 'savePost']);
        Route::get('saved-posts', [PostController::class, 'getSavedPosts']);
        Route::post('delete-post', [PostController::class, 'deletePost']);
        Route::get('detail/{id}', [PostController::class, 'getPostDetail'])->where('id', '[0-9]+');
        Route::post('update/{id}', [PostController::class, 'updatePost'])->where('id', '[0-9]+');
        Route::post('newsfeed', [PostController::class, 'getNewsfeed']);
        Route::post('trending-hashtags', [PostController::class, 'trendingHashtags']);
        Route::post('vote-poll', [PostController::class, 'votePollOption']);



        Route::post('change-privacy', [PostController::class, 'changePostPrivacy']);

        //post actions
        Route::post('action', [PostController::class, 'postAction']);
        Route::post('post-reaction-detail', [PostController::class, 'getPostReactionsByType']);
        Route::post('post-actions-detail', [PostController::class, 'getPostActionsByType']);
        Route::post('comment-action', [PostController::class, 'postCommentAction']);

        // Feed and filtering
        Route::get('page_posts/{id}', [PostController::class, 'getPagePosts'])->where('id', '[0-9]+');
        Route::get('group_posts/{id}', [PostController::class, 'getGroupPosts'])->where('id', '[0-9]+');
    });

    Route::prefix('page')->group(function () {
        Route::get('get-all', [PageController::class, 'getAllPages']);
        Route::get('user-pages', [PageController::class, 'userPages']);
        Route::post('add-new', [PageController::class, 'addPage']);
        Route::post('like-unlike-page', [PageController::class, 'likeUnlikePage']);
        Route::get('get-liked-pages', [PageController::class, 'getLikedPages']);
        Route::post('get-page-data', [PageController::class, 'getPageData']);
        Route::post('delete-page', [PageController::class, 'deletePage']);
        Route::post('update-page', [PageController::class, 'updatePage']);
        Route::get('liked-users', [PageController::class, 'getUsersWhoLikedPage']);
        Route::post('check-page-existence', [PageController::class, 'checkPageExistence']);
        Route::get('search', [PageController::class, 'search']);
    });
    Route::prefix('wallet')->group(function () {
        Route::post('deposit-amount', [UserWalletController::class, 'depositAmount']);
        Route::post('transfer-amount', [UserWalletController::class, 'transferAmount']);
        Route::get('withdraw-history', [UserWalletController::class, 'withdrawHistory']);
        Route::get('transaction-history', [UserWalletController::class, 'transactionHistory']);
        Route::get('deposit-history', [UserWalletController::class, 'depositHistory']);
        Route::get('get-wallet', [UserWalletController::class, 'getUserWallet']);
        Route::post('create-withdraw', [UserWalletController::class, 'createWithdrawRequest']);
        Route::post('upgrade-to-pro', [UserWalletController::class, 'upgradeToPro']);
    });



    Route::prefix('group')->group(function () {
        Route::get('all', [GroupController::class, 'getAllGroups']);
        Route::get('user-groups', [GroupController::class, 'getUserGroups']);
        Route::post('create', [GroupController::class, 'createGroup']);
        Route::post('update', [GroupController::class, 'updateGroup']);
        Route::post('delete', [GroupController::class, 'deleteGroup']);

        Route::post('join', [GroupController::class, 'joinGroup']);
        Route::post('leave', [GroupController::class, 'leaveGroup']);
        Route::post('invite-users', [GroupController::class, 'inviteUsers']);
        Route::post('remove-member', [GroupController::class, 'removeMember']);
        Route::get('members/{id}', [GroupController::class, 'getGroupMembers']);

        Route::post('make-admin', [GroupController::class, 'makeAdmin']);
        Route::post('remove-admin', [GroupController::class, 'removeAdmin']);
        Route::get('joined', [GroupController::class, 'getJoinedGroups']);
        Route::get('detail/{id}', [GroupController::class, 'getGroupDetail']);
    });
    Route::prefix('space')->group(function () {

        Route::post('create-space', [SpaceController::class, 'createSpace']);
        Route::post('get-spaces', [SpaceController::class, 'getSpaces']);
        Route::post('search-spaces', [SpaceController::class, 'searchSpaces']);
        Route::post('join-space', [SpaceController::class, 'joinSpace']);
        Route::post('add-cohost', [SpaceController::class, 'addCoHost']);
        Route::post('remove-cohost', [SpaceController::class, 'removeCoHost']);
        Route::post('remove-member', [SpaceController::class, 'removeMember']);
        Route::post('active-space', [SpaceController::class, 'activeSpace']);
        Route::post('update-space', [SpaceController::class, 'updateSpace']);
        Route::post('generate-agora-token', [SpaceController::class, 'generateAgoraToken']);
        Route::post('get-space-members', [SpaceController::class, 'getSpaceMembers']);
        Route::post('leave-space', [SpaceController::class, 'leaveSpace']);
        Route::post('add-space-lisnters', [SpaceController::class, 'addSpaceMembers']);
        Route::post('send-gift', [SpaceController::class, 'sendGift']);
        Route::post('get-gifts', [SpaceController::class, 'getGfits']);
        Route::post('invite-member', [SpaceController::class, 'inviteMember']);
        Route::post('report-space', [SpaceController::class, 'reportSpace']);
        Route::post('space-details', [SpaceController::class, 'spaceDetails']);
        Route::post('delete-space', [SpaceController::class, 'deleteSpace']);
        Route::post('check-space', [SpaceController::class, 'checkSpace']);
    });
    Route::prefix('jobs')->group(function () {

        // Job management
        Route::post('all', [JobController::class, 'getJobs']);
        Route::post('create', [JobController::class, 'createJob']);
        Route::post('update/{id}', [JobController::class, 'updateJob']);
        Route::delete('delete/{id}', [JobController::class, 'deleteJob']);
        Route::patch('toggle-status/{id}', [JobController::class, 'toggleJobStatus']);
        Route::patch('update-expiry/{id}', [JobController::class, 'updateJobExpiry']);

        // Job statistics and analytics
        Route::get('stats/{id}', [JobController::class, 'getJobStats']);

        // Application management
        Route::post('apply', [JobController::class, 'applyJob']);
        Route::delete('withdraw-application/{id}', [JobController::class, 'withdrawApplication']);
        Route::get('my-applications', [JobController::class, 'getMyApplications']);
        Route::patch('application/{id}/status', [JobController::class, 'updateApplicationStatus']);

        // Candidate management
        Route::get('candidates/{id}', [JobController::class, 'appliedCandidates']);


        // Recommendations
        Route::get('recommended', [JobController::class, 'getRecommendedJobs']);



        // Add the new route for getting job categories
        Route::get('categories', [JobController::class, 'getJobCategories']);

        // Add the new route for getting job details by ID
        Route::get('detail/{id}', [JobController::class, 'getJobDetailById']);

        // Add the new route for getting jobs created by the authenticated user
        Route::get('my-jobs', [JobController::class, 'getMyJobs']);
    });


    Route::prefix('event')->group(function () {
        // Create and manage events
        Route::post('add-event', [EventController::class, 'addEvent']);
        Route::post('update-event', [EventController::class, 'updateEvent']);
        Route::post('delete-event', [EventController::class, 'deleteEvent']);

        // Get event listings
        Route::post('get-events', [EventController::class, 'getEvents']);
        Route::get('detail/{slug}', [EventController::class, 'getEventDetail']);
        Route::get('detail_by_id/{id}', [EventController::class, 'getEventDetail']); // New route to get event by ID
        Route::get('my-events', [EventController::class, 'getMyEvents']);
        Route::get('interested-events', [EventController::class, 'getInterestedEvents']);

        Route::get('by-category/{category}', [EventController::class, 'getEventsByCategory']);
        Route::get('upcoming', [EventController::class, 'getUpcomingEvents']);

        // Participation
        Route::post('show-interest', [EventController::class, 'createInterest']);
        Route::post('go-to-event', [EventController::class, 'gotoEvent']);
        Route::post('join-event', [EventController::class, 'joinEvent']);

        // Participant management
        Route::get('{event_id}/participants', [EventController::class, 'getEventParticipants']);
        Route::post('approve-participant', [EventController::class, 'approveParticipant']);
        Route::post('reject-participant', [EventController::class, 'rejectParticipant']);
    });


    Route::prefix('movies')->group(function () {
        Route::get('/', [MovieController::class, 'index']);
        Route::get('/show/{slug}', [MovieController::class, 'show']);
        Route::get('/genre/{slug}', [MovieController::class, 'byGenre']);
        Route::get('/search', [MovieController::class, 'search']);
        Route::get('/watch/{slug}', [MovieController::class, 'watch']);

        Route::middleware('auth:sanctum')->group(function () {
            Route::post('/rate/{movie}', [MovieController::class, 'rate']);
        });
        Route::get('/detail/{slug}', [MovieController::class, 'getMovieDetailById']);
    });


    Route::prefix('marketplace')->group(function () {
        // Dashboard and statistics
        Route::get('dashboard-stats', [MarketplaceController::class, 'getDashboardStats'])->name('marketplace.dashboard-stats');

        // Product categories
        Route::get('categories', [MarketplaceController::class, 'getCategories'])->name('marketplace.categories');

        // Product management
        Route::get('products', [MarketplaceController::class, 'getProducts'])->name('marketplace.products');
        Route::post('product', [MarketplaceController::class, 'addProduct'])->name('marketplace.create');
        Route::get('product/{id}', [MarketplaceController::class, 'getProductDetail'])->name('marketplace.show');
        Route::delete('product/{id}', [MarketplaceController::class, 'deleteProduct'])->name('marketplace.delete');
        Route::get('recommended-products', [MarketplaceController::class, 'getRecommendedProducts'])->name('marketplace.recommended');

        // User's product interactions
        Route::post('toggle-save/{id}', [MarketplaceController::class, 'toggleSaveProduct'])->name('marketplace.toggle-save');

        // Store management
        Route::get('stores', [MarketplaceController::class, 'getStores'])->name('marketplace.stores');
        Route::post('add-store', [MarketplaceController::class, 'createStore'])->name('createstore');

        Route::get('store/{id}', [MarketplaceController::class, 'getStoreDetail'])->name('marketplace.store-detail');

        // Order management
        Route::get('orders', [MarketplaceController::class, 'getUserOrders'])->name('marketplace.orders');

        // Reviews
        Route::post('review', [MarketplaceController::class, 'submitReview'])->name('marketplace.submit-review');
        Route::post('add-review', [MarketplaceController::class, 'submitStoreReview'])->name('marketplace.submit-review');
        Route::post('get-store-reviews', [MarketplaceController::class, 'getStoreReviews'])->name('marketplace.submit-review');

        // Routes for sidebar features
        Route::get('saved-items', [MarketplaceController::class, 'getSavedProducts'])->name('marketplace.saved');
        Route::get('my-listings', [MarketplaceController::class, 'getUserProducts'])->name('marketplace.my-listings');
        Route::get('messages', [MarketplaceController::class, 'getMarketplaceMessages'])->name('marketplace.messages');
    });
    Route::prefix('livestream')->group(function () {
        // Dashboard and statistics
        Route::get('get', [LivestreamController::class, 'getLivestreams']);
        Route::post('create', [LivestreamController::class, 'create']);
        Route::post('join', [LivestreamController::class, 'joinLiveStream']);
        Route::get('get-livestream-viewer-count', [LivestreamController::class, 'liveStreamViewCount']);

        Route::post('end', [LivestreamController::class, 'endLiveStream']);
        Route::get('get-livestream-members', [LivestreamController::class, 'liveStreamMembers']);
        Route::get('get-comments', [LivestreamController::class, 'getCmment']);
        Route::post('add-comment', [LivestreamController::class, 'addComment']);
    });


    // Course API routes
    Route::prefix('courses')->group(function () {
        // Public course routes
        Route::get('/', [CoursesController::class, 'index']);
        Route::get('/categories', [CoursesController::class, 'categories']);
        Route::get('/category/{slug}', [CoursesController::class, 'category']);
        Route::get('/search', [CoursesController::class, 'search']);
        Route::get('/detail/{id}', [CoursesController::class, 'show']);
        Route::get('/{slug}', [CoursesController::class, 'show']);

        // Course enrollment and interactions (requires auth)
        Route::post('/{slug}/enroll', [CoursesController::class, 'enroll']);
        Route::get('/{slug}/checkout', [CoursesController::class, 'checkout']);
        Route::post('/{slug}/apply-coupon', [CoursesController::class, 'applyCoupon']);
        Route::post('/{slug}/process-payment', [CoursesController::class, 'processPayment']);
        Route::post('/{slug}/toggle-wishlist', [CoursesController::class, 'toggleWishlist']);

        // Course learning
        Route::get('/{slug}/learn/{lessonId?}', [CoursesController::class, 'learn']);
        Route::post('/{slug}/complete-lesson/{lessonId}', [CoursesController::class, 'completeLesson']);
        Route::post('/{slug}/ask-question/{lessonId}', [CoursesController::class, 'askQuestion']);
        Route::post('/answer-question/{questionId}', [CoursesController::class, 'answerQuestion']);
        Route::post('/mark-best-answer/{answerId}', [CoursesController::class, 'markBestAnswer']);
        Route::post('/{slug}/submit-review', [CoursesController::class, 'submitReview']);
    });

    // Student API routes
    Route::prefix('student')->group(function () {
        Route::get('/dashboard', [StudentController::class, 'dashboard']);
        Route::get('/my-courses', [StudentController::class, 'myCourses']);
        Route::get('/wishlist', [StudentController::class, 'wishlist']);
        Route::get('/purchase-history', [StudentController::class, 'purchaseHistory']);
        Route::delete('/wishlist/{id}', [StudentController::class, 'removeFromWishlist']);
    });

    // FriendController Routes
    Route::prefix('friends')->group(function () {
        Route::get('/get-all', [FriendController::class, 'getFriends']);
        Route::get('/get-sent-requests', [FriendController::class, 'getSentFriendRequests']);
        Route::get('/get-received-requests', [FriendController::class, 'getReceivedFriendRequests']);

        Route::post('/send-request', [FriendController::class, 'sendFriendRequest']);
        Route::post('/request-action', [FriendController::class, 'friendRequestAction']);
        Route::post('/unfriend', [FriendController::class, 'unfriend']);
        Route::get('/recommendations', [FriendController::class, 'fetchRecommended']);
        Route::post('/change-role', [FriendController::class, 'changeFriendRole']);
        Route::get('/get-followers', [FriendController::class, 'getFollowers']);
        Route::get('/stats', [FriendController::class, 'getStats']);
    });

    // Profile Completion & Dashboard API Routes
    Route::prefix('dashboard')->group(function () {
        Route::get('/profile-completion', [ProfileController::class, 'getProfileCompletion']);
        Route::get('/user-groups', [GroupController::class, 'getUserGroups']);
        Route::get('/suggested-users', [FriendController::class, 'getSuggestedUsers']);
    });

    Route::prefix('notifications')->group(function () {
        Route::get('/new', [NotificationController::class, 'showUserNewNotifications']);
        Route::post('/mark-all-read', [NotificationController::class, 'markAllAsRead']);
        Route::post('/delete', [NotificationController::class, 'deleteNotification']);
        Route::post('/delete-all', [NotificationController::class, 'deleteAllNotification']);
        Route::post('/mark-read', [NotificationController::class, 'markAsRead']);
    });

    Route::prefix('profile')->group(function () {

        Route::post('update', [ProfileController::class, 'update']);
        Route::post('update-notification-setting', [ProfileController::class, 'updateNotificatinSetting']);
        Route::post('update-picture', [ProfileController::class, 'updateProfilePicture']);
        Route::post('update-cover', [ProfileController::class, 'updateCoverPhoto']);
        Route::delete('delete-account', [ProfileController::class, 'destroy']);
        Route::get('search', [ProfileController::class, 'search']);
        Route::post('become-donor', [ProfileController::class, 'becomeDonor']);
        Route::get('list-donors', [ProfileController::class, 'listDonors']);
        Route::get('profile_settings', [ProfileController::class, 'profile_settings']);
        Route::get('id/{id}', [ProfileController::class, 'showById']);
        Route::get('{username}', [ProfileController::class, 'show']);
    });

    Route::prefix('blocks')->group(function () {
        Route::post('/block', [BlockController::class, 'blockUser']);
        Route::post('/unblock', [BlockController::class, 'blockUser']);
        Route::get('/list', [BlockController::class, 'blockList']);
    });

    Route::prefix('blogs')->group(function () {
        Route::get('/', [BlogController::class, 'index']);
        Route::get('/list', [BlogController::class, 'listBlogs']);
        Route::get('/search', [BlogController::class, 'search']);
        Route::get('/{id}', [BlogController::class, 'getBlogById']);
        Route::post('/', [BlogController::class, 'store']);
        Route::put('/{id}', [BlogController::class, 'update']);
        Route::delete('/{id}', [BlogController::class, 'destroy']);
    });

    Route::prefix('stories')->group(function () {
        Route::post('/', [StoryController::class, 'createStory'])->name('stories.create');
        Route::get('/', [StoryController::class, 'getStories'])->name('stories.get');
        Route::post('/mute-unmute', [StoryController::class, 'muteUnmuteUser'])->name('stories.muteUnmute');
        Route::post('/seen', [StoryController::class, 'seenStory'])->name('stories.seen');
        Route::get('/seen-users/{id}', [StoryController::class, 'storySeenUser'])->name('stories.seenUsers');
        Route::delete('/{id}', [StoryController::class, 'deleteStory'])->name('stories.delete');
    });

    Route::prefix('games')->group(function () {
        Route::get('/', [GameController::class, 'index']);
        Route::get('/show/{slug}', [GameController::class, 'show']);
        Route::post('/play/{slug}', [GameController::class, 'play']);
        Route::get('/category/{slug}', [GameController::class, 'byCategory']);
        Route::get('/search', [GameController::class, 'search']);
        Route::post('/rate/{game}', [GameController::class, 'rate']);
    });
});
