<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Subscription;
use App\Models\Tenant;
use App\Models\User;
use App\Models\AdminNotification;
use App\Models\ChatSession;
use App\Models\ChatMessage;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReportController extends Controller
{
    public function index()
    {
        return view('admin.reports.index');
    }

    public function payments(Request $request)
    {
        $startDate = $request->input('start_date', Carbon::now()->startOfMonth());
        $endDate = $request->input('end_date', Carbon::now()->endOfMonth());
        $status = $request->input('status', 'all');
        $gateway = $request->input('gateway', 'all');

        $query = Subscription::with(['tenant', 'plan'])
            ->whereBetween('created_at', [$startDate, $endDate]);

        if ($status !== 'all') {
            $query->where('payment_status', $status);
        }

        if ($gateway !== 'all') {
            $query->where('payment_gateway', $gateway);
        }

        $subscriptions = $query->orderBy('created_at', 'desc')->paginate(20);

        // Calculate statistics
        $totalRevenue = $query->sum('amount');
        $paidCount = (clone $query)->where('payment_status', 'paid')->count();
        $pendingCount = (clone $query)->where('payment_status', 'pending')->count();
        $failedCount = (clone $query)->where('payment_status', 'failed')->count();

        // Gateway breakdown
        $gatewayStats = Subscription::whereBetween('created_at', [$startDate, $endDate])
            ->selectRaw('payment_gateway, COUNT(*) as count, SUM(amount) as total')
            ->groupBy('payment_gateway')
            ->get();

        return view('admin.reports.payments', compact(
            'subscriptions',
            'totalRevenue',
            'paidCount',
            'pendingCount',
            'failedCount',
            'gatewayStats',
            'startDate',
            'endDate',
            'status',
            'gateway'
        ));
    }

    public function customers(Request $request)
    {
        $search = $request->input('search');
        $status = $request->input('status', 'all');

        $tenants = Tenant::with(['subscription.plan', 'users'])
            ->when($search, function($query, $search) {
                $query->where('name', 'like', "%{$search}%")
                      ->orWhere('email', 'like', "%{$search}%");
            })
            ->when($status !== 'all', function($query, $status) {
                if ($status === 'active') {
                    $query->whereHas('subscription', function($subQuery) {
                        $subQuery->where('status', 'active')
                               ->where('ends_at', '>', now());
                    });
                } elseif ($status === 'expired') {
                    $query->whereHas('subscription', function($subQuery) {
                        $subQuery->where('ends_at', '<', now());
                    });
                } elseif ($status === 'trial') {
                    $query->whereHas('subscription', function($subQuery) {
                        $subQuery->where('status', 'trialing');
                    });
                }
            })
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        // Customer statistics
        $totalTenants = Tenant::count();
        $activeTenants = Tenant::whereHas('subscription', function($query) {
            $query->where('status', 'active')->where('ends_at', '>', now());
        })->count();
        $expiredTenants = Tenant::whereHas('subscription', function($query) {
            $query->where('ends_at', '<', now());
        })->count();
        $trialTenants = Tenant::whereHas('subscription', function($query) {
            $query->where('status', 'trialing');
        })->count();

        return view('admin.reports.customers', compact(
            'tenants',
            'totalTenants',
            'activeTenants',
            'expiredTenants',
            'trialTenants',
            'search',
            'status'
        ));
    }

    public function transactions(Request $request)
    {
        $startDate = $request->input('start_date', Carbon::now()->startOfMonth());
        $endDate = $request->input('end_date', Carbon::now()->endOfMonth());
        $tenantId = $request->input('tenant_id', 'all');
        $gateway = $request->input('gateway', 'all');

        $query = Subscription::with(['tenant', 'plan'])
            ->whereBetween('created_at', [$startDate, $endDate])
            ->whereNotNull('transaction_id');

        if ($tenantId !== 'all') {
            $query->where('tenant_id', $tenantId);
        }

        if ($gateway !== 'all') {
            $query->where('payment_gateway', $gateway);
        }

        $transactions = $query->orderBy('created_at', 'desc')->paginate(20);

        // Get all tenants for filter dropdown
        $tenants = Tenant::orderBy('name')->get();

        return view('admin.reports.transactions', compact(
            'transactions',
            'tenants',
            'startDate',
            'endDate',
            'tenantId',
            'gateway'
        ));
    }

    public function customerDetails($id)
    {
        $tenant = Tenant::with([
            'subscription.plan',
            'users',
            'subscriptions' => function($query) {
                $query->orderBy('created_at', 'desc');
            }
        ])->findOrFail($id);

        // Get customer's transactions
        $transactions = Subscription::where('tenant_id', $id)
            ->with('plan')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return view('admin.reports.customer-details', compact('tenant', 'transactions'));
    }

    public function analytics()
    {
        // Revenue analytics for last 12 months
        $revenueData = Subscription::selectRaw('DATE_FORMAT(created_at, "%Y-%m") as month, SUM(amount) as revenue, COUNT(*) as count')
            ->where('created_at', '>=', Carbon::now()->subYear())
            ->where('payment_status', 'paid')
            ->groupBy('month')
            ->orderBy('month')
            ->get();

        // New customers per month
        $customerData = Tenant::selectRaw('DATE_FORMAT(created_at, "%Y-%m") as month, COUNT(*) as count')
            ->where('created_at', '>=', Carbon::now()->subYear())
            ->groupBy('month')
            ->orderBy('month')
            ->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')
            ->groupBy('plan_id', 'plans.name')
            ->orderBy('count', 'desc')
            ->get();

        // Gateway usage
        $gatewayData = Subscription::selectRaw('payment_gateway, COUNT(*) as count, SUM(amount) as revenue')
            ->where('payment_status', 'paid')
            ->groupBy('payment_gateway')
            ->get();

        // Calculate analytics summary
        $totalRevenue = Subscription::where('payment_status', 'paid')->sum('amount');
        $newCustomers = Tenant::where('created_at', '>=', Carbon::now()->subMonth())->count();
        $conversionRate = $customerData->sum('count') > 0 ? round(($revenueData->sum('count') / $customerData->sum('count')) * 100, 1) : 0;
        $avgSubscription = $totalRevenue > 0 ? $totalRevenue / Subscription::where('payment_status', 'paid')->count() : 0;

        // Calculate growth rates
        $lastMonthRevenue = Subscription::where('payment_status', 'paid')
            ->where('created_at', '>=', Carbon::now()->subMonth())
            ->where('created_at', '<', Carbon::now())
            ->sum('amount');
        $previousMonthRevenue = Subscription::where('payment_status', 'paid')
            ->where('created_at', '>=', Carbon::now()->subMonths(2))
            ->where('created_at', '<', Carbon::now()->subMonth())
            ->sum('amount');
        $revenueGrowth = $previousMonthRevenue > 0 ? (($lastMonthRevenue - $previousMonthRevenue) / $previousMonthRevenue) * 100 : 0;

        $lastMonthCustomers = Tenant::where('created_at', '>=', Carbon::now()->subMonth())
            ->where('created_at', '<', Carbon::now())
            ->count();
        $previousMonthCustomers = Tenant::where('created_at', '>=', Carbon::now()->subMonths(2))
            ->where('created_at', '<', Carbon::now()->subMonth())
            ->count();
        $customerGrowth = $previousMonthCustomers > 0 ? (($lastMonthCustomers - $previousMonthCustomers) / $previousMonthCustomers) * 100 : 0;

        $analytics = [
            'totalRevenue' => $totalRevenue,
            'newCustomers' => $newCustomers,
            'conversionRate' => $conversionRate,
            'avgSubscription' => $avgSubscription,
            'revenueGrowth' => $revenueGrowth,
            'customerGrowth' => $customerGrowth,
            'conversionGrowth' => 0, // Placeholder for future implementation
            'popularPlans' => $planData->map(function($plan) {
                return [
                    'name' => $plan->plan_name,
                    'subscriptions' => $plan->count,
                    'revenue' => $plan->revenue
                ];
            })->toArray(),
            'gatewayStats' => $gatewayData->mapWithKeys(function($gateway) {
                return [
                    $gateway->payment_gateway => [
                        'count' => $gateway->count,
                        'amount' => $gateway->revenue,
                        'percentage' => $totalRevenue > 0 ? ($gateway->revenue / $totalRevenue) * 100 : 0
                    ]
                ];
            })->toArray(),
            'recentActivity' => [] // Placeholder for future implementation
        ];

        return view('admin.reports.analytics', compact(
            'analytics',
            'revenueData',
            'customerData',
            'planData',
            'gatewayData'
        ));
    }
}
