<?php

namespace App\Http\Controllers\Api;

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

class AnalyticsController extends Controller
{
    /**
     * Get fleet and loads analytics dashboard data.
     */
    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        $companyId = $user->company_id;

        // Fleet summary
        $fleet = DB::table('trucks')
            ->where('company_id', $companyId)
            ->selectRaw('
                COUNT(*) as total_trucks,
                SUM(CASE WHEN id NOT IN (SELECT truck_id FROM drivers WHERE truck_id IS NOT NULL) THEN 1 ELSE 0 END) as available_trucks
            ')
            ->first();

        $drivers = DB::table('drivers')
            ->where('company_id', $companyId)
            ->selectRaw('
                COUNT(*) as total_drivers,
                SUM(CASE WHEN truck_id IS NULL THEN 1 ELSE 0 END) as available_drivers
            ')
            ->first();

        // Loads stats
        $loadsStats = DB::table('loads')
            ->where('company_id', $companyId)
            ->selectRaw('
                COUNT(*) as total_loads,
                SUM(gross_rate) as total_revenue,
                AVG(net_profit) as avg_profit_per_load,
                SUM(CASE WHEN status = "pending" THEN 1 ELSE 0 END) as pending_loads,
                SUM(CASE WHEN status = "processed" THEN 1 ELSE 0 END) as processed_loads,
                SUM(CASE WHEN status = "completed" THEN 1 ELSE 0 END) as completed_loads
            ')
            ->first();

        // Recent loads (last 7 days)
        $recentLoads = DB::table('loads')
            ->where('company_id', $companyId)
            ->where('created_at', '>=', now()->subDays(7))
            ->select('load_number', 'gross_rate', 'net_profit', 'status', 'created_at')
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        // Monthly revenue trend (last 6 months)
        $monthlyRevenue = DB::table('loads')
            ->where('company_id', $companyId)
            ->where('status', 'completed')
            ->where('created_at', '>=', now()->subMonths(6))
            ->selectRaw('
                DATE_FORMAT(created_at, "%Y-%m") as month,
                SUM(gross_rate) as revenue,
                COUNT(*) as loads_count
            ')
            ->groupBy('month')
            ->orderBy('month')
            ->get();

        return response()->json([
            'success' => true,
            'data' => [
                'fleet' => [
                    'trucks' => [
                        'total' => (int) $fleet->total_trucks,
                        'available' => (int) $fleet->available_trucks,
                    ],
                    'drivers' => [
                        'total' => (int) $drivers->total_drivers,
                        'available' => (int) $drivers->available_drivers,
                    ],
                ],
                'loads' => [
                    'total' => (int) $loadsStats->total_loads,
                    'total_revenue' => (float) $loadsStats->total_revenue,
                    'avg_profit_per_load' => (float) $loadsStats->avg_profit_per_load,
                    'pending' => (int) $loadsStats->pending_loads,
                    'processed' => (int) $loadsStats->processed_loads,
                    'completed' => (int) $loadsStats->completed_loads,
                ],
                'recent_loads' => $recentLoads,
                'monthly_revenue' => $monthlyRevenue,
            ],
        ], 200);
    }
}

