<?php

namespace App\Http\Controllers\Developer;

use App\Http\Controllers\Admin\ReportController as AdminReportController;
use App\Models\Subscription;
use App\Models\Tenant;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ReportController extends AdminReportController
{
    public function analytics()
    {
        // Reuse logic from parent but return developer view
        // Note: We might need to recalculate or pass data if the parent method is complex
        
        $period = request('period', '30');
        $startDate = Carbon::now()->subDays($period);

        // Revenue analytics
        $revenueData = Subscription::selectRaw('DATE_FORMAT(created_at, "%Y-%m-%d") as date, SUM(amount) as revenue')
            ->where('created_at', '>=', $startDate)
            ->where('payment_status', 'paid')
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        // New customers
        $customerData = Tenant::selectRaw('DATE_FORMAT(created_at, "%Y-%m-%d") as date, COUNT(*) as count')
            ->where('created_at', '>=', $startDate)
            ->groupBy('date')
            ->orderBy('date')
            ->get();

        // Plan popularity
        $planData = Subscription::selectRaw('plans.name as plan_name, COUNT(*) as count, SUM(amount) as revenue')
            ->join('plans', 'subscriptions.plan_id', '=', 'plans.id')
            ->where('payment_status', 'paid')
            ->where('subscriptions.created_at', '>=', $startDate)
            ->groupBy('plan_id', 'plans.name')
            ->orderBy('count', 'desc')
            ->get();

        // Simplified analytics for the view
        $analytics = [
            'totalRevenue' => Subscription::where('payment_status', 'paid')->where('created_at', '>=', $startDate)->sum('amount'),
            'newCustomers' => Tenant::where('created_at', '>=', $startDate)->count(),
            'revenueGrowth' => 5.4, // Placeholder
            'customerGrowth' => 12.1, // Placeholder
            'conversionRate' => 3.2, // Placeholder
            'conversionGrowth' => 0.5, // Placeholder
            'avgSubscription' => Subscription::where('payment_status', 'paid')->where('created_at', '>=', $startDate)->avg('amount') ?? 0,
            'subscriptionGrowth' => 2.1, // Placeholder
        ];

        return view('developer.reports.analytics', compact('revenueData', 'customerData', 'planData', 'analytics', 'period'));
    }
}
