<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use App\Models\Offerwall;
use App\Models\OfferwallClick;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class ActivityController extends Controller
{
    public function bulk(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'selected' => ['required', 'array', 'min:1'],
            'selected.*' => ['integer', 'exists:offerwall_clicks,id'],
            'action' => ['required', 'in:delete'],
        ]);

        $deleted = OfferwallClick::whereKey($validated['selected'])->delete();

        return back()->with('success', $deleted.' selected activity '.($deleted === 1 ? 'record was' : 'records were').' deleted.');
    }

    public function index()
    {
        $from = now()->subDays(14);

        $clicks = OfferwallClick::with(['user', 'offerwall', 'providerOffer'])
            ->latest()
            ->paginate(20);

        $providerClicks = OfferwallClick::query()
            ->select('provider_name', DB::raw('count(*) as clicks'))
            ->where('created_at', '>=', $from)
            ->groupBy('provider_name')
            ->orderByDesc('clicks')
            ->limit(10)
            ->get();

        $providerCompletions = Lead::query()
            ->select('company', DB::raw('count(*) as completions'), DB::raw('sum(points) as points'), DB::raw('sum(payout) as payout'))
            ->where('created_at', '>=', $from)
            ->groupBy('company')
            ->orderByDesc('completions')
            ->limit(10)
            ->get()
            ->keyBy('company');

        $providerStats = $providerClicks->map(function ($row) use ($providerCompletions) {
            $completed = $providerCompletions->get($row->provider_name);
            $completions = (int) optional($completed)->completions;

            return [
                'name' => $row->provider_name,
                'clicks' => (int) $row->clicks,
                'completions' => $completions,
                'conversion' => $row->clicks ? round(($completions / $row->clicks) * 100, 1) : 0,
                'points' => (float) optional($completed)->points,
                'payout' => (float) optional($completed)->payout,
            ];
        });

        $topCompletedOffers = Lead::query()
            ->select('company', 'offer_name', DB::raw('count(*) as completions'), DB::raw('sum(points) as points'))
            ->where('created_at', '>=', $from)
            ->groupBy('company', 'offer_name')
            ->orderByDesc('completions')
            ->limit(12)
            ->get();

        $topClickedOffers = OfferwallClick::query()
            ->select('provider_offer_id', 'provider_name', 'offer_name', DB::raw('count(*) as clicks'))
            ->where('created_at', '>=', $from)
            ->whereNotNull('offer_name')
            ->groupBy('provider_offer_id', 'provider_name', 'offer_name')
            ->orderByDesc('clicks')
            ->limit(12)
            ->get();

        $totals = [
            'clicks' => OfferwallClick::where('created_at', '>=', $from)->count(),
            'completions' => Lead::where('created_at', '>=', $from)->count(),
            'active_offerwalls' => Offerwall::where('is_active', true)->count(),
            'conversion' => 0,
        ];

        $totals['conversion'] = $totals['clicks'] ? round(($totals['completions'] / $totals['clicks']) * 100, 1) : 0;

        return view('admin.activity', compact('clicks', 'providerStats', 'topCompletedOffers', 'topClickedOffers', 'totals'));
    }
}
