<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\ActiveNumber;
use App\Models\Payment;
use App\Models\SmmOrder;
use App\Models\SmmProvider;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Setting;
use Illuminate\Http\Request;

class DashController extends Controller
{
    public function dashboard()
    {
        $title = 'Dashboard';

        $totalUsers       = User::count();
        $activeUsers      = User::where('status', 1)->count();
        $inactiveUsers    = User::where('status', 0)->count();
        $totalUserBalance = User::sum('balance');

        $successfulPayments = Payment::where('status', 'success')->get();
        $totalDeposits      = $successfulPayments->sum('amount');
        $todayDeposits      = $successfulPayments->where('created_at', '>=', now()->startOfDay())->sum('amount');

        $totalWithdrawn = Transaction::where('type', 'debit')->sum('amount');
        $totalNumbers  = ActiveNumber::count();

        // SMM stats
        $totalSmmOrders   = SmmOrder::count();
        $totalSmmRevenue  = SmmOrder::sum('charge');
        $pendingSmmOrders = SmmOrder::whereIn('status', ['awaiting', 'inprogress'])->count();
        $totalSmmProviders = SmmProvider::count();

        $recentUsers = User::latest()->take(10)->get();

        $settings = Setting::first();

        // Cron commands (curl for crontab; URL is quoted for safety)
        $cronSendOrders   = 'curl -s "' . url('cron/smm/send-orders') . '"';
        $cronSyncStatus   = 'curl -s "' . url('cron/smm/sync-status') . '"';
        $cronSyncServices = 'curl -s "' . url('cron/smm/sync-services') . '"';

        return view('backend.dashboard', compact(
            'title',
            'totalUsers',
            'activeUsers',
            'inactiveUsers',
            'totalUserBalance',
            'totalDeposits',
            'todayDeposits',
            'totalWithdrawn',
            'totalNumbers',
            'totalSmmOrders',
            'totalSmmRevenue',
            'pendingSmmOrders',
            'totalSmmProviders',
            'cronSendOrders',
            'cronSyncStatus',
            'cronSyncServices',
            'recentUsers',
            'settings'
        ));
    }
}
