<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\User;
use App\Models\Withdrawal;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Devrabiul\ToastMagic\Facades\ToastMagic;


class DashboardController extends Controller
{
    public function dashboard()
    {
        $today = Carbon::today();
        $tomorrow = Carbon::tomorrow();

        $data = Cache::remember('dashboard_stats', 1800, function () use ($today, $tomorrow) {
            $statsQuery = User::selectRaw("
            COUNT(id) as totalStudents,
            COUNT(CASE WHEN verified_at IS NOT NULL THEN 1 END) as totalConverted
        ")
                ->where('role', 'student');

            // Get totalStudents and totalConverted
            $stats = $statsQuery->first();

            // Add todayConverted separately
            $todayConverted = User::where('role', 'student')
                ->whereNotNull('verified_at')
                ->whereBetween('created_at', [$today, $tomorrow])
                ->count();

            $stats->todayConverted = $todayConverted;

            $withdraws = Withdrawal::selectRaw("
            SUM(CASE WHEN status = 'approved' THEN amount END) as total,
            SUM(CASE WHEN status = 'pending' THEN amount END) as pending
        ")->first();

            return [
                'stats' => $stats,
                'withdraws' => $withdraws,
            ];
        });
        return view('backend.dashboard', $data);
    }

    public function settings()
    {
        return view('backend.settings');
    }

    public function updateSettings(Request $request)
    {
        $data = $request->except('_token');

        foreach ($data as $key => $value) {
            if ($request->hasFile($key)) {
                $file = updateImg($request->file($key), 'logos', $value);
                $value = $file;
            }

            Setting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }

        // Clear and re-cache the settings
        Cache::forget('settings');

        ToastMagic::success("Settings have been updated");
        return redirect()->back();
    }
}
