<?php

namespace Modules\Dashboard\Http\Controllers\KJC;

use App\Http\Controllers\Controller;
use Modules\KJCAssetEntitlement\Entities\KJCAssetEntitlement;
use Modules\KJCAssetHolding\Entities\KJCAssetHolding;
use Modules\Dashboard\Services\KJC\KJCDashboardService;
use Modules\Dashboard\Repositories\Contracts\KJCDashboardRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class KJCDashboardController extends Controller
{
    protected KJCDashboardService $kjcDashboardService;
    protected KJCDashboardRepositoryInterface $kjcDashboardRepository;

    public function __construct(KJCDashboardService $kjcDashboardService, KJCDashboardRepositoryInterface $kjcDashboardRepository)
    {
        $this->kjcDashboardService = $kjcDashboardService;
        $this->kjcDashboardRepository = $kjcDashboardRepository;
    }

    /**
     * Get KJC entitlement vs holdings pie chart
     */
    public function getEntitlementVsHoldingsPieChart(Request $request): JsonResponse
    {
        try {
            $filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
            $user = $request->user(); // Get authenticated user
            $chartData = $this->kjcDashboardService->getEntitlementVsHoldingsPieChart($filters, $user);

            return response()->json([
                'success' => true,
                'data' => $chartData
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch KJC entitlement vs holdings chart',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get KJC holdings status breakdown pie chart
     */
    public function getHoldingsStatusBreakdownPieChart(Request $request): JsonResponse
    {
        try {
            $filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
            $user = $request->user(); // Get authenticated user
            $chartData = $this->kjcDashboardService->getHoldingsStatusBreakdownPieChart($filters, $user);

            return response()->json([
                'success' => true,
                'data' => $chartData
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch KJC holdings status breakdown chart',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get KJC unit performance chart
     */
    public function getUnitPerformanceChart(Request $request): JsonResponse
    {
        try {
            $filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
            $user = $request->user(); // Get authenticated user
            $chartData = $this->kjcDashboardService->getUnitPerformanceChart($filters, $user);

            return response()->json([
                'success' => true,
                'data' => $chartData
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch KJC unit performance chart',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get KJC monthly trends chart
     */
    public function getMonthlyTrendsChart(Request $request): JsonResponse
    {
        try {
            $filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
            $user = $request->user(); // Get authenticated user
            $chartData = $this->kjcDashboardService->getMonthlyTrendsChart($filters, $user);

            return response()->json([
                'success' => true,
                'data' => $chartData
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch KJC monthly trends chart',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get KJC historical metrics bar chart
     */
    public function getHistoricalMetricsBarChart(Request $request): JsonResponse
    {
        try {
            $filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
            $user = $request->user(); // Get authenticated user
            $chartData = $this->kjcDashboardService->getHistoricalMetricsBarChart($filters, $user);

            return response()->json([
                'success' => true,
                'data' => $chartData
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch KJC historical metrics chart',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get drill-down data for entitlement vs holdings
     */
    public function getEntitlementVsHoldingsDetails(Request $request): JsonResponse
    {
        try {
            $filters = $request->only(['type', 'date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
            
            $type = $filters['type'] ?? 'entitlement';
            
            if ($type === 'entitlement') {
                // Return entitlement details
                $entitlements = KJCAssetEntitlement::with(['kjcSubcategory'])
                    ->paginate(20);
                
                $data = [
                    'title' => 'KJC Asset Entitlements',
                    'filters' => array_merge($filters, ['total_count' => $entitlements->total()]),
                    'items' => $entitlements->items(),
                    'pagination' => [
                        'current_page' => $entitlements->currentPage(),
                        'per_page' => $entitlements->perPage(),
                        'total' => $entitlements->total(),
                        'last_page' => $entitlements->lastPage(),
                        'from' => $entitlements->firstItem(),
                        'to' => $entitlements->lastItem()
                    ]
                ];
            } else {
                // Return holdings details
                $query = KJCAssetHolding::with(['unit', 'kjcCategory', 'kjcSubcategory', 'kjcModel']);
                
                if (isset($filters['date_from'])) {
                    $query->where('created_at', '>=', $filters['date_from']);
                }
                
                if (isset($filters['date_to'])) {
                    $query->where('created_at', '<=', $filters['date_to']);
                }
                
                if (isset($filters['unit_id'])) {
                    $query->where('unit_id', $filters['unit_id']);
                }
                
                $holdings = $query->paginate(20);
                
                $data = [
                    'title' => 'KJC Asset Holdings',
                    'filters' => array_merge($filters, ['total_count' => $holdings->total()]),
                    'items' => $holdings->items(),
                    'pagination' => [
                        'current_page' => $holdings->currentPage(),
                        'per_page' => $holdings->perPage(),
                        'total' => $holdings->total(),
                        'last_page' => $holdings->lastPage(),
                        'from' => $holdings->firstItem(),
                        'to' => $holdings->lastItem()
                    ]
                ];
            }

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch entitlement vs holdings details',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get drill-down data for holdings status
     */
    public function getHoldingsStatusDetails(Request $request): JsonResponse
    {
        try {
            $filters = $request->only(['status', 'date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id']);
            
            $query = KJCAssetHolding::with(['unit', 'kjcCategory', 'kjcSubcategory', 'kjcModel']);
            
            if (isset($filters['status'])) {
                $query->where('status', $filters['status']);
            }
            
            if (isset($filters['date_from'])) {
                $query->where('created_at', '>=', $filters['date_from']);
            }
            
            if (isset($filters['date_to'])) {
                $query->where('created_at', '<=', $filters['date_to']);
            }
            
            if (isset($filters['unit_id'])) {
                $query->where('unit_id', $filters['unit_id']);
            }
            
            $holdings = $query->paginate(20);
            
            // Map status codes to readable names
            $statusNames = [
                'BP' => 'Beroperasi (Operational)',
                'BDG' => 'Baik Diselenggara (Well Maintained)',
                'TBDG' => 'Tidak Baik Diselenggara (Poorly Maintained)'
            ];
            
            $statusName = $statusNames[$filters['status']] ?? $filters['status'];

            return response()->json([
                'success' => true,
                'data' => [
                    'title' => "KJC Assets with Status: {$statusName}",
                    'filters' => array_merge($filters, ['total_count' => $holdings->total()]),
                    'items' => $holdings->items(),
                    'pagination' => [
                        'current_page' => $holdings->currentPage(),
                        'per_page' => $holdings->perPage(),
                        'total' => $holdings->total(),
                        'last_page' => $holdings->lastPage(),
                        'from' => $holdings->firstItem(),
                        'to' => $holdings->lastItem()
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch holdings status details',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get KJC asset details by status (drill-down table, paginated).
     * Status can be 'null' for assets not yet assigned a status (DB column NULL).
     */
    public function getAssetDetailsByStatus(Request $request, string $status): JsonResponse
    {
        try {
            $filters = $request->only(['date_from', 'date_to', 'unit_id', 'camp_id', 'formation_id', 'government_id', 'page', 'per_page']);
            $user = $request->user();

            $status = trim($status);
            $status = $status === 'null' ? '' : $status;

            $details = $this->kjcDashboardRepository->getAssetDetailsByStatus($status, $filters, $user);

            return response()->json([
                'success' => true,
                'data' => $details
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch KJC asset details',
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
