<?php

namespace MoneyTransfer\Core\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use MoneyTransfer\Core\Models\Transfer;
use MoneyTransfer\Core\Repositories\TransferRepository;
use Illuminate\Support\Facades\DB;

class AnalyticsController extends Controller
{
    protected $transferRepository;

    public function __construct(TransferRepository $transferRepository)
    {
        $this->transferRepository = $transferRepository;
    }

    public function dashboard(Request $request): JsonResponse
    {
        $userId = auth()->id();
        $dateRange = $request->get('date_range', '30d');
        
        $stats = $this->transferRepository->getTransferStats($userId);
        
        // Get date range
        $startDate = $this->getStartDate($dateRange);
        $endDate = now();
        
        // Additional analytics
        $monthlyData = Transfer::byUser($userId)
                              ->whereBetween('created_at', [$startDate, $endDate])
                              ->selectRaw('DATE(created_at) as date, COUNT(*) as count, SUM(total_amount) as total')
                              ->groupBy('date')
                              ->orderBy('date')
                              ->get();

        $currencyDistribution = Transfer::byUser($userId)
                                      ->whereBetween('created_at', [$startDate, $endDate])
                                      ->selectRaw('currency_from, COUNT(*) as count, SUM(total_amount) as total')
                                      ->groupBy('currency_from')
                                      ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'stats' => $stats,
                'monthly_data' => $monthlyData,
                'currency_distribution' => $currencyDistribution,
                'date_range' => [
                    'start' => $startDate->toDateString(),
                    'end' => $endDate->toDateString(),
                ],
            ],
            'message' => 'Dashboard analytics retrieved successfully'
        ]);
    }

    public function reports(Request $request): JsonResponse
    {
        $userId = auth()->id();
        $reportType = $request->get('type', 'transfers');
        $dateFrom = $request->get('date_from');
        $dateTo = $request->get('date_to');

        $query = Transfer::byUser($userId);

        if ($dateFrom && $dateTo) {
            $query->whereBetween('created_at', [$dateFrom, $dateTo]);
        }

        switch ($reportType) {
            case 'revenue':
                $data = $query->selectRaw('DATE(created_at) as date, SUM(fee) as revenue, COUNT(*) as transfers')
                             ->groupBy('date')
                             ->orderBy('date')
                             ->get();
                break;
            
            case 'performance':
                $data = $query->selectRaw('status, COUNT(*) as count, AVG(total_amount) as avg_amount')
                             ->groupBy('status')
                             ->get();
                break;
            
            default: // transfers
                $data = $query->selectRaw('DATE(created_at) as date, COUNT(*) as count, SUM(total_amount) as volume')
                             ->groupBy('date')
                             ->orderBy('date')
                             ->get();
                break;
        }

        return response()->json([
            'success' => true,
            'data' => [
                'report_type' => $reportType,
                'data' => $data,
                'filters' => [
                    'date_from' => $dateFrom,
                    'date_to' => $dateTo,
                ],
            ],
            'message' => 'Report generated successfully'
        ]);
    }

    public function currencyDistribution(Request $request): JsonResponse
    {
        $userId = auth()->id();
        $dateRange = $request->get('date_range', '30d');
        $startDate = $this->getStartDate($dateRange);

        $distribution = Transfer::byUser($userId)
                               ->where('created_at', '>=', $startDate)
                               ->selectRaw('currency_from, COUNT(*) as count, SUM(total_amount) as volume')
                               ->groupBy('currency_from')
                               ->orderBy('volume', 'desc')
                               ->get();

        $totalVolume = $distribution->sum('volume');
        
        $distribution = $distribution->map(function ($item) use ($totalVolume) {
            $item->percentage = $totalVolume > 0 ? round(($item->volume / $totalVolume) * 100, 2) : 0;
            return $item;
        });

        return response()->json([
            'success' => true,
            'data' => [
                'distribution' => $distribution,
                'total_volume' => $totalVolume,
                'period' => $dateRange,
            ],
            'message' => 'Currency distribution retrieved successfully'
        ]);
    }

    public function geographicDistribution(Request $request): JsonResponse
    {
        $userId = auth()->id();
        $dateRange = $request->get('date_range', '30d');
        $startDate = $this->getStartDate($dateRange);

        $distribution = Transfer::byUser($userId)
                               ->where('created_at', '>=', $startDate)
                               ->with('recipient.country')
                               ->get()
                               ->groupBy('recipient.country.name')
                               ->map(function ($transfers, $country) {
                                   return [
                                       'country' => $country,
                                       'count' => $transfers->count(),
                                       'volume' => $transfers->sum('total_amount'),
                                       'percentage' => 0, // Will be calculated
                                   ];
                               })
                               ->values()
                               ->sortByDesc('volume');

        $totalVolume = $distribution->sum('volume');
        
        $distribution = $distribution->map(function ($item) use ($totalVolume) {
            $item['percentage'] = $totalVolume > 0 ? round(($item['volume'] / $totalVolume) * 100, 2) : 0;
            return $item;
        });

        return response()->json([
            'success' => true,
            'data' => [
                'distribution' => $distribution,
                'total_volume' => $totalVolume,
                'period' => $dateRange,
            ],
            'message' => 'Geographic distribution retrieved successfully'
        ]);
    }

    public function transferSuccessRate(Request $request): JsonResponse
    {
        $userId = auth()->id();
        $dateRange = $request->get('date_range', '30d');
        $startDate = $this->getStartDate($dateRange);

        $statuses = Transfer::byUser($userId)
                           ->where('created_at', '>=', $startDate)
                           ->selectRaw('status, COUNT(*) as count')
                           ->groupBy('status')
                           ->get();

        $totalTransfers = $statuses->sum('count');
        
        $successRate = $totalTransfers > 0 
            ? round(($statuses->where('status', 'completed')->first()->count ?? 0) / $totalTransfers * 100, 2)
            : 0;

        return response()->json([
            'success' => true,
            'data' => [
                'statuses' => $statuses,
                'total_transfers' => $totalTransfers,
                'success_rate' => $successRate,
                'period' => $dateRange,
            ],
            'message' => 'Transfer success rate retrieved successfully'
        ]);
    }

    public function averageTransferAmount(Request $request): JsonResponse
    {
        $userId = auth()->id();
        $dateRange = $request->get('date_range', '30d');
        $startDate = $this->getStartDate($dateRange);

        $averages = Transfer::byUser($userId)
                           ->where('created_at', '>=', $startDate)
                           ->selectRaw('currency_from, COUNT(*) as count, AVG(total_amount) as average')
                           ->groupBy('currency_from')
                           ->orderBy('average', 'desc')
                           ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'averages' => $averages,
                'period' => $dateRange,
            ],
            'message' => 'Average transfer amounts retrieved successfully'
        ]);
    }

    private function getStartDate(string $dateRange): \Carbon\Carbon
    {
        return match ($dateRange) {
            '7d' => now()->subDays(7),
            '30d' => now()->subDays(30),
            '90d' => now()->subDays(90),
            '1y' => now()->subYear(),
            default => now()->subDays(30),
        };
    }
} 