<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\License;
use App\Models\KbArticle;
use App\Models\Ticket;
use App\Models\Invoice;
use App\Models\User;
use App\Models\LicenseLog;
use Illuminate\Http\Request;
use Carbon\Carbon;

class DashboardController extends Controller
{
    public function index()
    {
        $stats = [
            'products' => Product::count(),
            'customers' => User::count(),
            'licenses_active' => License::where('status', 'active')->count(),
            'tickets_open' => Ticket::whereIn('status', ['open','pending'])->count(),
            'kb_articles' => KbArticle::count(),
        ];

        // Invoice monetary statistics
        $invoiceTotalCount = Invoice::count();
        $invoiceTotalAmount = (float) Invoice::sum('amount');
        $invoicePaidAmount = (float) Invoice::where('status', 'paid')->sum('amount');
    $invoicePaidCount = Invoice::where('status', 'paid')->count();
        $invoiceDueSoonAmount = (float) Invoice::where('status', 'pending')->where('due_date', '<=', now()->addDays(7))->sum('amount');
        // Unpaid includes pending, overdue and cancelled
        $invoiceUnpaidAmount = (float) Invoice::where('status', '!=', 'paid')->sum('amount');
    // Cancelled invoices
    $invoiceCancelledCount = Invoice::where('status', 'cancelled')->count();
    $invoiceCancelledAmount = (float) Invoice::where('status', 'cancelled')->sum('amount');

        $stats['invoices_count'] = $invoiceTotalCount;
        $stats['invoices_total_amount'] = $invoiceTotalAmount;
        $stats['invoices_paid_amount'] = $invoicePaidAmount;
    $stats['invoices_paid_count'] = $invoicePaidCount;
        $stats['invoices_due_soon_amount'] = $invoiceDueSoonAmount;
        $stats['invoices_unpaid_amount'] = $invoiceUnpaidAmount;
    $stats['invoices_cancelled_count'] = $invoiceCancelledCount;
    $stats['invoices_cancelled_amount'] = $invoiceCancelledAmount;

        // API Statistics
        $stats['api_requests_today'] = LicenseLog::whereDate('created_at', today())->count();
        $stats['api_requests_this_month'] = LicenseLog::whereMonth('created_at', now()->month)->count();
        $stats['api_success_rate'] = $this->calculateApiSuccessRate();
        $stats['api_errors_today'] = $this->getApiErrorsToday();
        $stats['api_errors_this_month'] = $this->getApiErrorsThisMonth();

        $latestTickets = Ticket::latest()->with('user')->limit(5)->get();
        $latestLicenses = License::latest()->with('product', 'user')->limit(5)->get();
        // 🔔 Notifications (ONLY for logged-in user)
        $notifications = auth()->check()
            ? auth()->user()->notifications()->latest()->limit(10)->get()
            : collect();

        $unreadCount = auth()->check()
            ? auth()->user()->unreadNotifications()->count()
            : 0;

        return view('admin.dashboard', compact('stats', 'latestTickets', 'latestLicenses','notifications', 'unreadCount'));
    }

    /**
     * Get system overview chart data
     */
    public function getSystemOverviewData()
    {
        try {
            $activeLicenses = License::where('status', 'active')->count();
            $expiredLicenses = License::where('status', 'expired')->count();
            $pendingRequests = Ticket::whereIn('status', ['open','pending'])->count();
            $totalProducts = Product::count();

            return response()->json([
                'labels' => ['Active Licenses', 'Expired Licenses', 'Pending Requests', 'Total Products'],
                'data' => [$activeLicenses, $expiredLicenses, $pendingRequests, $totalProducts]
            ]);
        } catch (\Exception $e) {
            // Log the error for debugging
            // System overview data error handled gracefully
            
            // Return fallback data
            return response()->json([
                'labels' => ['Active Licenses', 'Expired Licenses', 'Pending Requests', 'Total Products'],
                'data' => [0, 0, 0, 0]
            ]);
        }
    }

    /**
     * Get license distribution chart data
     */
    public function getLicenseDistributionData()
    {
        try {
            // Use actual enum values defined in the licenses table: regular / extended
            $regularLicenses = License::where('license_type', 'regular')->count();
            $extendedLicenses = License::where('license_type', 'extended')->count();

            return response()->json([
                'labels' => ['Regular', 'Extended'],
                'data' => [$regularLicenses, $extendedLicenses]
            ]);
        } catch (\Exception $e) {
            // Log the error for debugging
            // License distribution data error handled gracefully
            
            // Return fallback data
            return response()->json([
                'labels' => ['Regular', 'Extended'],
                'data' => [0, 0]
            ]);
        }
    }

    /**
     * Get revenue chart data
     */
    public function getRevenueData(Request $request)
    {
        try {
            $period = $request->get('period', 'monthly');
            $year = $request->get('year', date('Y'));

            if ($period === 'monthly') {
                $data = [];
                $labels = [];

                for ($month = 1; $month <= 12; $month++) {
                    $startDate = Carbon::create($year, $month, 1)->startOfMonth();
                    $endDate = Carbon::create($year, $month, 1)->endOfMonth();

                    // Calculate revenue from licenses created in this month
                    $monthlyRevenue = License::join('products', 'licenses.product_id', '=', 'products.id')
                        ->whereBetween('licenses.created_at', [$startDate, $endDate])
                        ->sum('products.price');

                    $data[] = (float) $monthlyRevenue;
                    $labels[] = Carbon::create($year, $month, 1)->format('M');
                }
            } elseif ($period === 'quarterly') {
                $data = [];
                $labels = ['Q1', 'Q2', 'Q3', 'Q4'];

                for ($quarter = 1; $quarter <= 4; $quarter++) {
                    $startMonth = ($quarter - 1) * 3 + 1;
                    $endMonth = $quarter * 3;

                    $startDate = Carbon::create($year, $startMonth, 1)->startOfMonth();
                    $endDate = Carbon::create($year, $endMonth, 1)->endOfMonth();

                    $quarterlyRevenue = License::join('products', 'licenses.product_id', '=', 'products.id')
                        ->whereBetween('licenses.created_at', [$startDate, $endDate])
                        ->sum('products.price');

                    $data[] = (float) $quarterlyRevenue;
                }
            } else { // yearly
                $currentYear = date('Y');
                $data = [];
                $labels = [];

                for ($y = $currentYear - 4; $y <= $currentYear; $y++) {
                    $startDate = Carbon::create($y, 1, 1)->startOfYear();
                    $endDate = Carbon::create($y, 12, 31)->endOfYear();

                    $yearlyRevenue = License::join('products', 'licenses.product_id', '=', 'products.id')
                        ->whereBetween('licenses.created_at', [$startDate, $endDate])
                        ->sum('products.price');

                    $data[] = (float) $yearlyRevenue;
                    $labels[] = $y;
                }
            }

            return response()->json([
                'labels' => $labels,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            // Log the error for debugging
            // Revenue data error handled gracefully
            
            // Return fallback data
            return response()->json([
                'labels' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                'data' => [0, 0, 0, 0, 0, 0]
            ]);
        }
    }

    /**
     * Get activity timeline chart data
     */
    public function getActivityTimelineData()
    {
        try {
            $today = Carbon::today();
            $data = [];
            $labels = [];

            // Get activity data for the last 7 days
            for ($i = 6; $i >= 0; $i--) {
                $date = $today->copy()->subDays($i);
                $startOfDay = $date->copy()->startOfDay();
                $endOfDay = $date->copy()->endOfDay();

                // Sum total activity counts for the day (tickets created + licenses created)
                $ticketsCount = Ticket::whereBetween('created_at', [$startOfDay, $endOfDay])->count();
                $licensesCount = License::whereBetween('created_at', [$startOfDay, $endOfDay])->count();
                $dailyTotal = $ticketsCount + $licensesCount;

                $data[] = $dailyTotal;
                $labels[] = $date->format('M j');
            }

            return response()->json([
                'labels' => $labels,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            // Log the error for debugging
            // Activity timeline data error handled gracefully
            
            // Return fallback data
            return response()->json([
                'labels' => ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
                'data' => [0, 0, 0, 0, 0, 0, 0]
            ]);
        }
    }

    /**
     * Get dashboard statistics
     */
    public function getStats()
    {
        try {
            $stats = [
                'products' => Product::count(),
                'customers' => User::count(),
                'licenses_active' => License::where('status', 'active')->count(),
                'licenses_expired' => License::where('status', 'expired')->count(),
                'tickets_open' => Ticket::whereIn('status', ['open','pending'])->count(),
                'tickets_closed' => Ticket::where('status', 'closed')->count(),
                'kb_articles' => KbArticle::count(),
            ];

            return response()->json($stats);
        } catch (\Exception $e) {
            // Log the error for debugging
            // Dashboard stats error handled gracefully
            
            // Return fallback data
            return response()->json([
                'products' => 0,
                'customers' => 0,
                'licenses_active' => 0,
                'licenses_expired' => 0,
                'tickets_open' => 0,
                'tickets_closed' => 0,
                'kb_articles' => 0,
            ]);
        }
    }

    /**
     * Calculate API success rate
     */
    private function calculateApiSuccessRate(): float
    {
        $totalRequests = LicenseLog::count();
        if ($totalRequests === 0) {
            return 0.0;
        }
        
        $successfulRequests = LicenseLog::where('status', 'success')->count();
        return round(($successfulRequests / $totalRequests) * 100, 2);
    }

    /**
     * Get API errors today from Laravel logs
     */
    private function getApiErrorsToday(): int
    {
        $logFile = storage_path('logs/laravel.log');
        if (!file_exists($logFile)) {
            return 0;
        }

        $today = now()->format('Y-m-d');
        $errorCount = 0;
        
        $handle = fopen($logFile, 'r');
        if ($handle) {
            while (($line = fgets($handle)) !== false) {
                if (strpos($line, $today) !== false && 
                    strpos($line, 'License verification error') !== false) {
                    $errorCount++;
                }
            }
            fclose($handle);
        }
        
        return $errorCount;
    }

    /**
     * Get API errors this month from Laravel logs
     */
    private function getApiErrorsThisMonth(): int
    {
        $logFile = storage_path('logs/laravel.log');
        if (!file_exists($logFile)) {
            return 0;
        }

        $month = now()->format('Y-m');
        $errorCount = 0;
        
        $handle = fopen($logFile, 'r');
        if ($handle) {
            while (($line = fgets($handle)) !== false) {
                if (strpos($line, $month) !== false && 
                    strpos($line, 'License verification error') !== false) {
                    $errorCount++;
                }
            }
            fclose($handle);
        }
        
        return $errorCount;
    }

    /**
     * Get API requests chart data
     */
    public function getApiRequestsData(Request $request)
    {
        try {
            $period = $request->get('period', 'daily');
            $days = $request->get('days', 7);
            
            $data = [];
            $labels = [];
            $successData = [];
            $failedData = [];

            if ($period === 'daily') {
                for ($i = $days - 1; $i >= 0; $i--) {
                    $date = now()->subDays($i);
                    $startOfDay = $date->copy()->startOfDay();
                    $endOfDay = $date->copy()->endOfDay();

                    $totalRequests = LicenseLog::whereBetween('created_at', [$startOfDay, $endOfDay])->count();
                    $successRequests = LicenseLog::whereBetween('created_at', [$startOfDay, $endOfDay])
                        ->where('status', 'success')->count();
                    $failedRequests = LicenseLog::whereBetween('created_at', [$startOfDay, $endOfDay])
                        ->where('status', 'failed')->count();

                    $data[] = $totalRequests;
                    $successData[] = $successRequests;
                    $failedData[] = $failedRequests;
                    $labels[] = $date->format('M j');
                }
            } elseif ($period === 'hourly') {
                for ($i = 23; $i >= 0; $i--) {
                    $hour = now()->subHours($i);
                    $startOfHour = $hour->copy()->startOfHour();
                    $endOfHour = $hour->copy()->endOfHour();

                    $totalRequests = LicenseLog::whereBetween('created_at', [$startOfHour, $endOfHour])->count();
                    $successRequests = LicenseLog::whereBetween('created_at', [$startOfHour, $endOfHour])
                        ->where('status', 'success')->count();
                    $failedRequests = LicenseLog::whereBetween('created_at', [$startOfHour, $endOfHour])
                        ->where('status', 'failed')->count();

                    $data[] = $totalRequests;
                    $successData[] = $successRequests;
                    $failedData[] = $failedRequests;
                    $labels[] = $hour->format('H:i');
                }
            }

            return response()->json([
                'labels' => $labels,
                'datasets' => [
                    [
                        'label' => 'Total Requests',
                        'data' => $data,
                        'borderColor' => '#3B82F6',
                        'backgroundColor' => 'rgba(59, 130, 246, 0.1)',
                        'fill' => true
                    ],
                    [
                        'label' => 'Successful',
                        'data' => $successData,
                        'borderColor' => '#10B981',
                        'backgroundColor' => 'rgba(16, 185, 129, 0.1)',
                        'fill' => true
                    ],
                    [
                        'label' => 'Failed',
                        'data' => $failedData,
                        'borderColor' => '#EF4444',
                        'backgroundColor' => 'rgba(239, 68, 68, 0.1)',
                        'fill' => true
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'labels' => [],
                'datasets' => []
            ]);
        }
    }

    /**
     * Get API performance metrics
     */
    public function getApiPerformanceData()
    {
        try {
            $today = now()->startOfDay();
            $yesterday = now()->subDay()->startOfDay();
            
            // Today's metrics
            $todayRequests = LicenseLog::whereDate('created_at', today())->count();
            $todaySuccess = LicenseLog::whereDate('created_at', today())->where('status', 'success')->count();
            $todayFailed = LicenseLog::whereDate('created_at', today())->where('status', 'failed')->count();
            
            // Yesterday's metrics
            $yesterdayRequests = LicenseLog::whereDate('created_at', $yesterday)->count();
            $yesterdaySuccess = LicenseLog::whereDate('created_at', $yesterday)->where('status', 'success')->count();
            $yesterdayFailed = LicenseLog::whereDate('created_at', $yesterday)->where('status', 'failed')->count();
            
            // Top domains
            $topDomains = LicenseLog::selectRaw('domain, COUNT(*) as count')
                ->where('created_at', '>=', now()->subDays(7))
                ->groupBy('domain')
                ->orderBy('count', 'desc')
                ->limit(5)
                ->get();

            return response()->json([
                'today' => [
                    'total' => $todayRequests,
                    'success' => $todaySuccess,
                    'failed' => $todayFailed,
                    'success_rate' => $todayRequests > 0 ? round(($todaySuccess / $todayRequests) * 100, 2) : 0
                ],
                'yesterday' => [
                    'total' => $yesterdayRequests,
                    'success' => $yesterdaySuccess,
                    'failed' => $yesterdayFailed,
                    'success_rate' => $yesterdayRequests > 0 ? round(($yesterdaySuccess / $yesterdayRequests) * 100, 2) : 0
                ],
                'top_domains' => $topDomains
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'today' => ['total' => 0, 'success' => 0, 'failed' => 0, 'success_rate' => 0],
                'yesterday' => ['total' => 0, 'success' => 0, 'failed' => 0, 'success_rate' => 0],
                'top_domains' => []
            ]);
        }
    }

    /**
     * Clear all application caches
     */
    public function clearCache()
    {
        // Clear application cache
        \Artisan::call('cache:clear');
        
        // Clear config cache
        \Artisan::call('config:clear');
        
        // Clear route cache
        \Artisan::call('route:clear');
        
        // Clear view cache
        \Artisan::call('view:clear');
        
        // Clear compiled classes
        \Artisan::call('clear-compiled');
        
        // Clear license-specific caches if any
        \Cache::flush(); // Clear all cache keys
        
        return redirect()->back()->with('success', 'All caches cleared successfully!');
    }
}