<?php

namespace App\Http\Controllers;

use App\Repositories\BoostPostRepository;
use App\Repositories\ContactRepository;
use App\Repositories\NotificationHistoryRepository;
use App\Repositories\ReviewRepository;
use App\Repositories\SellingPostRepository;
use App\Repositories\TransactionRepository;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
    public function index()
    {
        $sellingPosts = SellingPostRepository::getAll();
        $boostPosts = BoostPostRepository::query()->count('id');
        $contacts = ContactRepository::query()->count('id');
        $topSellers = ReviewRepository::getTopSellers(5);
        $growthRate = TransactionRepository::earningGrowthRate();
        $currentMonth = TransactionRepository::currentMonthEarnings();
        $lastMonth = TransactionRepository::lastMonthEarnings();
        $totalEarnings = TransactionRepository::totalEarnings();
        $totalWalletRecharge = TransactionRepository::totalWalletRecharge();
        $totalDirectPurchaseEarnings = TransactionRepository::totalDirectPurchaseEarnings();
        $totalPendingPayments = TransactionRepository::totalPendingPayments();
        $boostplansold = BoostPostRepository::getTopSoldPlans();
        $filterPosts = SellingPostRepository::getSellingPostReport();


        return view('pages.home', compact('boostPosts', 'contacts', 'sellingPosts', 'topSellers', 'growthRate', 'totalEarnings', 'totalWalletRecharge', 'totalDirectPurchaseEarnings', 'totalPendingPayments', 'boostplansold', 'filterPosts'));
    }


    public function readSingleNotification(Request $request)
    {
        $notification = NotificationHistoryRepository::findOrFail($request->notification_id);
        $notification->update(['is_read' => true]);

        return response()->json([
            'status' => 'success',
            'message' => 'Notification marked as read'
        ]);
    }

    public function readAllNotification()
    {
        NotificationHistoryRepository::query()->where('receiver_id', null)->where('is_read', false)->update(['is_read' => true]);
        session()->flash('success', 'All notifications marked as read.');
        return redirect()->route('dashboard');
    }

    public function loadMoreNotifications(Request $request)
    {
        $page = $request->input('page', 1);
        $perPage = 10;
        $notifications = getNotifications(null, $page, $perPage);
        return response()->json([
            'notifications' => $notifications->items(),
            'has_more' => $notifications->hasMorePages()
        ]);
    }
}
