<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CancellationSurvey;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;
use Inertia\Response;

class CancellationSurveyController extends Controller
{
    public function index(Request $request): Response
    {
        $query = CancellationSurvey::query()
            ->with(['user:id,name,email', 'subscription:id,type']);

        if ($request->filled('reason') && $request->input('reason') !== 'all') {
            $query->where('cancellation_reason', $request->input('reason'));
        }

        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->input('date_from'));
        }

        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->input('date_to'));
        }

        $surveys = $query->orderByDesc('created_at')->paginate(25);

        // Analytics: reason breakdown
        $reasonBreakdown = CancellationSurvey::query()
            ->select('cancellation_reason', DB::raw('COUNT(*) as count'))
            ->groupBy('cancellation_reason')
            ->orderByDesc('count')
            ->get()
            ->map(fn ($row) => [
                'reason' => $row->cancellation_reason,
                'count' => (int) $row->count,
            ])
            ->toArray();

        // Analytics: monthly trend
        $monthlyTrend = CancellationSurvey::query()
            ->select(
                DB::raw("DATE_FORMAT(created_at, '%Y-%m') as month"),
                DB::raw('COUNT(*) as count'),
            )
            ->groupBy('month')
            ->orderBy('month')
            ->limit(12)
            ->get()
            ->map(fn ($row) => [
                'month' => $row->month,
                'count' => (int) $row->count,
            ])
            ->toArray();

        // Summary stats
        $totalSurveys = CancellationSurvey::count();
        $topReason = ! empty($reasonBreakdown) ? $reasonBreakdown[0]['reason'] : 'N/A';
        $wouldReturnCount = CancellationSurvey::whereIn('would_return', ['yes', 'maybe'])->count();
        $wouldReturnRate = $totalSurveys > 0 ? round(($wouldReturnCount / $totalSurveys) * 100, 1) : 0;

        // Available reasons for filter dropdown
        $availableReasons = CancellationSurvey::query()
            ->select('cancellation_reason')
            ->distinct()
            ->orderBy('cancellation_reason')
            ->pluck('cancellation_reason')
            ->toArray();

        return Inertia::render('Admin/CancellationSurveys/Index', [
            'surveys' => $surveys,
            'reasonBreakdown' => $reasonBreakdown,
            'monthlyTrend' => $monthlyTrend,
            'totalSurveys' => $totalSurveys,
            'topReason' => $topReason,
            'wouldReturnRate' => $wouldReturnRate,
            'availableReasons' => $availableReasons,
            'filters' => $request->only(['reason', 'date_from', 'date_to']),
        ]);
    }
}
