<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AnalyticsController extends Controller
{
    /**
     * GET /api/analytics/overview
     */
    public function overview(Request $request)
    {
        $tenant = $request->input('_tenant') ?? $request->user()->tenant;
        $period = $request->query('period', '30d');

        $from = match ($period) {
            '7d'  => now()->subDays(7),
            '30d' => now()->subDays(30),
            '90d' => now()->subDays(90),
            '1y'  => now()->subYear(),
            default => now()->subDays(30),
        };

        // Totals
        $totals = DB::table('phone_results')
            ->where('tenant_id', $tenant->id)
            ->where('created_at', '>=', $from)
            ->selectRaw('
                COUNT(*) as total,
                SUM(CASE WHEN is_valid = 1 THEN 1 ELSE 0 END) as valid,
                SUM(CASE WHEN is_duplicate = 1 THEN 1 ELSE 0 END) as duplicate
            ')
            ->first();

        $total         = (int) $totals->total;
        $validRate     = $total > 0 ? round(($totals->valid / $total) * 100, 2) : 0;
        $duplicateRate = $total > 0 ? round(($totals->duplicate / $total) * 100, 2) : 0;

        // Top countries
        $countries = DB::table('phone_results')
            ->where('tenant_id', $tenant->id)
            ->where('created_at', '>=', $from)
            ->whereNotNull('country_code')
            ->selectRaw('country_code, country_name, COUNT(*) as count')
            ->groupBy('country_code', 'country_name')
            ->orderByDesc('count')
            ->limit(10)
            ->get()
            ->map(fn($row) => [
                'country_code' => $row->country_code,
                'country_name' => $row->country_name,
                'count'        => (int) $row->count,
                'percentage'   => $total > 0 ? round(($row->count / $total) * 100, 2) : 0,
            ]);

        // Number type breakdown
        $typeBreakdown = DB::table('phone_results')
            ->where('tenant_id', $tenant->id)
            ->where('created_at', '>=', $from)
            ->selectRaw('number_type, COUNT(*) as count')
            ->groupBy('number_type')
            ->get()
            ->pluck('count', 'number_type');

        // Risk distribution
        $risk = DB::table('phone_results')
            ->where('tenant_id', $tenant->id)
            ->where('created_at', '>=', $from)
            ->selectRaw('
                SUM(CASE WHEN risk_score < 30 THEN 1 ELSE 0 END) as low,
                SUM(CASE WHEN risk_score >= 30 AND risk_score < 60 THEN 1 ELSE 0 END) as medium,
                SUM(CASE WHEN risk_score >= 60 THEN 1 ELSE 0 END) as high
            ')
            ->first();

        // API usage
        $apiUsage = DB::table('api_keys')
            ->where('tenant_id', $tenant->id)
            ->selectRaw('COALESCE(SUM(usage_count), 0) as total_calls')
            ->value('total_calls');

        return response()->json([
            'total_processed'    => $total,
            'valid_rate'         => $validRate,
            'duplicate_rate'     => $duplicateRate,
            'top_countries'      => $countries,
            'number_type_breakdown' => [
                'mobile'   => (int) ($typeBreakdown['mobile'] ?? 0),
                'landline' => (int) ($typeBreakdown['landline'] ?? 0),
                'unknown'  => (int) ($typeBreakdown['unknown'] ?? 0),
            ],
            'risk_distribution' => [
                'low'    => (int) ($risk->low ?? 0),
                'medium' => (int) ($risk->medium ?? 0),
                'high'   => (int) ($risk->high ?? 0),
            ],
            'api_usage' => [
                'total_calls'  => (int) $apiUsage,
                'this_month'   => 0, // TODO: monthly tracking
                'limit'        => null,
            ],
        ]);
    }

    /**
     * GET /api/analytics/countries
     */
    public function countries(Request $request)
    {
        $tenant = $request->input('_tenant') ?? $request->user()->tenant;

        $total = DB::table('phone_results')->where('tenant_id', $tenant->id)->count();

        $countries = DB::table('phone_results')
            ->where('tenant_id', $tenant->id)
            ->whereNotNull('country_code')
            ->selectRaw('country_code, country_name, COUNT(*) as count')
            ->groupBy('country_code', 'country_name')
            ->orderByDesc('count')
            ->get()
            ->map(fn($row) => [
                'country_code' => $row->country_code,
                'country_name' => $row->country_name,
                'count'        => (int) $row->count,
                'percentage'   => $total > 0 ? round(($row->count / $total) * 100, 2) : 0,
            ]);

        return response()->json($countries);
    }

    /**
     * GET /api/analytics/trends
     */
    public function trends(Request $request)
    {
        $tenant = $request->input('_tenant') ?? $request->user()->tenant;
        $period = $request->query('period', '30d');

        $from = match ($period) {
            '7d'  => now()->subDays(7),
            '30d' => now()->subDays(30),
            '90d' => now()->subDays(90),
            default => now()->subDays(30),
        };

        $data = DB::table('uploads')
            ->where('tenant_id', $tenant->id)
            ->where('status', 'completed')
            ->where('created_at', '>=', $from)
            ->selectRaw('
                DATE(created_at) as date,
                COALESCE(SUM(total_numbers), 0) as processed,
                COALESCE(SUM(valid_count), 0) as valid,
                COALESCE(SUM(invalid_count), 0) as invalid
            ')
            ->groupByRaw('DATE(created_at)')
            ->orderBy('date')
            ->get()
            ->map(fn($row) => [
                'date'      => $row->date,
                'processed' => (int) $row->processed,
                'valid'     => (int) $row->valid,
                'invalid'   => (int) $row->invalid,
            ]);

        return response()->json($data);
    }
}
