<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Invoice;
use App\Models\PaymentTransaction;
use App\Models\Service;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Laravel\Cashier\Subscription;

class AdminAnalyticsController extends Controller
{
    /**
     * Dashboard analytics data (MRR, ARR, churn, customer count, etc.).
     */
    public function index(Request $request): JsonResponse
    {
        $totalCustomers = User::role('customer')->count();

        // MRR: prefer recurring_amount, fall back to plan_prices
        $mrr = (float) (Subscription::query()
            ->where('subscriptions.stripe_status', 'active')
            ->whereNotNull('subscriptions.plan_id')
            ->leftJoin('plan_prices', function ($join): void {
                $join->on('subscriptions.plan_id', '=', 'plan_prices.plan_id')
                    ->on('subscriptions.billing_cycle', '=', 'plan_prices.billing_cycle');
            })
            ->selectRaw('SUM(CASE
                WHEN subscriptions.recurring_amount IS NOT NULL THEN
                    CASE subscriptions.billing_cycle
                        WHEN "monthly" THEN subscriptions.recurring_amount
                        WHEN "quarterly" THEN subscriptions.recurring_amount / 3
                        WHEN "semi_annual" THEN subscriptions.recurring_amount / 6
                        WHEN "annual" THEN subscriptions.recurring_amount / 12
                        ELSE subscriptions.recurring_amount
                    END
                ELSE
                    CASE subscriptions.billing_cycle
                        WHEN "monthly" THEN plan_prices.price
                        WHEN "quarterly" THEN plan_prices.price / 3
                        WHEN "semi_annual" THEN plan_prices.price / 6
                        WHEN "annual" THEN plan_prices.price / 12
                        ELSE plan_prices.price
                    END
            END) as mrr')
            ->value('mrr') ?? 0);

        // ARR (Annual Recurring Revenue)
        $arr = $mrr * 12;

        // Total revenue: sum of paid invoice totals
        $totalRevenue = (float) Invoice::query()
            ->where('status', 'paid')
            ->sum('total');

        $activeServices = Service::query()
            ->where('status', 'active')
            ->count();

        // Pending invoices
        $pendingInvoicesCount = Invoice::query()
            ->where('status', 'pending')
            ->count();

        $pendingInvoicesAmount = (float) Invoice::query()
            ->where('status', 'pending')
            ->sum('total');

        // Overdue invoices
        $overdueCount = Invoice::query()
            ->where('status', 'overdue')
            ->count();

        $overdueAmount = (float) Invoice::query()
            ->where('status', 'overdue')
            ->sum('total');

        // New customers this month
        $newCustomersThisMonth = User::role('customer')
            ->where('created_at', '>=', now()->startOfMonth())
            ->count();

        // Revenue this month
        $revenueThisMonth = (float) Invoice::query()
            ->where('status', 'paid')
            ->where('paid_at', '>=', now()->startOfMonth())
            ->sum('total');

        // Monthly Revenue Trend (last 12 months)
        $revenueByMonth = PaymentTransaction::query()
            ->where('status', 'succeeded')
            ->where('created_at', '>=', now()->subMonths(12))
            ->selectRaw("DATE_FORMAT(created_at, '%Y-%m') as month, SUM(amount) as total, COUNT(*) as transactions, ROUND(AVG(amount), 2) as avg_amount")
            ->groupBy('month')
            ->orderBy('month')
            ->get()
            ->map(fn ($row) => [
                'month' => $row->month,
                'total' => (float) $row->total,
                'transactions' => (int) $row->transactions,
                'avg_amount' => (float) $row->avg_amount,
            ]);

        // Customer Growth (last 12 months - new signups per month)
        $customerGrowth = User::role('customer')
            ->where('created_at', '>=', now()->subMonths(12))
            ->selectRaw("DATE_FORMAT(created_at, '%Y-%m') as month, COUNT(*) as count")
            ->groupBy('month')
            ->orderBy('month')
            ->get()
            ->map(fn ($row) => ['month' => $row->month, 'count' => (int) $row->count]);

        // Churn Rate (subscriptions cancelled vs total in last 6 months)
        $churnData = [];
        for ($i = 5; $i >= 0; $i--) {
            $monthStart = now()->subMonths($i)->startOfMonth();
            $monthEnd = now()->subMonths($i)->endOfMonth();

            $totalAtStart = Subscription::query()
                ->where('created_at', '<', $monthStart)
                ->where(function ($query) use ($monthStart): void {
                    $query->whereNull('cancelled_at')
                        ->orWhere('cancelled_at', '>', $monthStart);
                })
                ->count();

            $cancelled = Subscription::query()
                ->whereBetween('cancelled_at', [$monthStart, $monthEnd])
                ->count();

            $churnData[] = [
                'month' => $monthStart->format('Y-m'),
                'rate' => $totalAtStart > 0 ? round(($cancelled / $totalAtStart) * 100, 1) : 0,
                'cancelled' => $cancelled,
            ];
        }

        // Revenue by service type
        $revenueByServiceType = Invoice::query()
            ->where('invoices.status', 'paid')
            ->join('subscriptions', 'invoices.subscription_id', '=', 'subscriptions.id')
            ->join('plans', 'subscriptions.plan_id', '=', 'plans.id')
            ->select('plans.service_type', DB::raw('SUM(invoices.total) as revenue'), DB::raw('COUNT(invoices.id) as invoice_count'))
            ->groupBy('plans.service_type')
            ->orderByDesc('revenue')
            ->get();

        AuditLog::create([
            'admin_id' => $request->user()->id,
            'action' => 'api_view_analytics',
            'resource_type' => 'analytics',
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return response()->json([
            'data' => [
                'total_customers' => $totalCustomers,
                'new_customers_this_month' => $newCustomersThisMonth,
                'mrr' => $mrr,
                'arr' => $arr,
                'total_revenue' => $totalRevenue,
                'revenue_this_month' => $revenueThisMonth,
                'active_services' => $activeServices,
                'pending_invoices' => [
                    'count' => $pendingInvoicesCount,
                    'amount' => $pendingInvoicesAmount,
                ],
                'overdue_invoices' => [
                    'count' => $overdueCount,
                    'amount' => $overdueAmount,
                ],
                'revenue_by_month' => $revenueByMonth,
                'customer_growth' => $customerGrowth,
                'churn_data' => $churnData,
                'revenue_by_service_type' => $revenueByServiceType,
            ],
        ]);
    }
}
