<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\CustomerVendor;
use App\Models\EmployeeDetails;
use App\Models\RouteCard;
use App\Models\RouteCardProcess;
use App\Models\PurchaseOrder;
use App\Models\ManufacturingPlan;
use App\Models\EmployeeAttendance;
use App\Models\EmployeeLeave;
use App\Models\EmployeeDailyReport;
use App\Models\Rfq;
use App\Models\Quotation;
use App\Models\SalesOrder;
use App\Models\TaxInvoice;
use App\Models\PurchaseRFQ;
use App\Models\PurchaseQuotation;
use App\Models\Grn;
use App\Models\SkuMaster;
use App\Models\SkuMovement;
use App\Models\Machines;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class SuperAdminDashboardController extends Controller
{
    public function allDashboard()
    {
        $today = now()->toDateString();
        $currentMonth = now()->month;
        $currentYear = now()->year;

        // === CUSTOMER/VENDOR METRICS ===
        $totalCustomers = CustomerVendor::where('company_role', 'Customer')->orWhere('company_role', 'Both')->count();
        $totalVendors = CustomerVendor::where('company_role', 'Vendor')->orWhere('company_role', 'Both')->count();
        $totalCustomerMonthly = CustomerVendor::whereMonth('created_at', $currentMonth)->whereYear('created_at', $currentYear)->count();
        $totalCustomerAnnual = CustomerVendor::whereYear('created_at', $currentYear)->count();

        // === SALES METRICS ===
        $totalRfqs = Rfq::count();
        $pendingRfqs = Rfq::where('status', 'pending')->count();
        $approvedRfqs = Rfq::where('status', 'approved')->count();

        $totalQuotations = Quotation::count();
        $pendingQuotations = Quotation::where('status', 'pending')->count();
        $approvedQuotations = Quotation::where('status', 'approved')->count();

        $totalSalesOrders = SalesOrder::count();
        $pendingSalesOrders = SalesOrder::where('status', 'pending')->count();
        $approvedSalesOrders = SalesOrder::where('status', 'approved')->count();

        $totalInvoices = TaxInvoice::count();
        $monthlyRevenue = TaxInvoice::whereMonth('invoice_date', $currentMonth)
            ->whereYear('invoice_date', $currentYear)
            ->sum('total_amount');
        $annualRevenue = TaxInvoice::whereYear('invoice_date', $currentYear)->sum('total_amount');

        // === PURCHASE METRICS ===
        $totalPurchaseRfqs = PurchaseRFQ::count();
        $pendingPurchaseRfqs = PurchaseRFQ::where('status', 'pending')->count();

        $totalPurchaseQuotations = PurchaseQuotation::count();
        $totalPurchaseOrders = PurchaseOrder::count();
        $pendingPurchaseOrders = PurchaseOrder::where('status', 'pending')->count();

        $totalGrns = Grn::count();

        // === MANUFACTURING METRICS ===
        $totalRouteCards = RouteCard::count();
        $pendingRouteCards = RouteCard::where('status', 'pending')->count();
        $inProductionRouteCards = RouteCard::where('status', 'in-production')->count();
        $completedRouteCards = RouteCard::where('status', 'completed')->count();

        $totalTasks = RouteCardProcess::count();
        $completedTasks = RouteCardProcess::whereNotNull('actual_end')->count();
        $dayTasksPercent = $totalTasks > 0 ? round(($completedTasks / $totalTasks) * 100, 1) : 0;

        $runningProjects = RouteCard::whereIn('status', ['in-production', 'ready'])->count();

        // === INVENTORY METRICS ===
        $totalSkus = SkuMaster::count();
        $lowStockItems = SkuMaster::whereColumn('current_stock', '<=', 'min_order_level')->count();
        $outOfStockItems = SkuMaster::where('current_stock', 0)->count();
        $totalStockValue = SkuMaster::selectRaw('SUM(current_stock * default_price) as value')->value('value') ?? 0;

        // === MACHINE METRICS ===
        $totalMachines = Machines::count();

        // === EMPLOYEE METRICS ===
        $totalEmployees = EmployeeDetails::count();
        $employeePresent = EmployeeDailyReport::whereDate('date', $today)->distinct('employee_id')->count('employee_id');
        $employeeLeave = EmployeeLeave::where('status', 'approved')
            ->whereDate('leave_from', '<=', $today)
            ->whereDate('leave_to', '>=', $today)
            ->count();

        // === PENDING APPROVALS ===
        $pendingBills = $pendingPurchaseOrders;
        $totalPendingApprovals = $pendingRfqs + $pendingQuotations + $pendingSalesOrders + $pendingPurchaseRfqs + $pendingRouteCards;

        // === CHARTS DATA ===

        // Monthly Sales Trend (Last 6 months)
        $salesTrend = collect(range(5, 0))->map(function ($i) {
            $date = now()->subMonths($i);
            $revenue = TaxInvoice::whereMonth('invoice_date', $date->month)
                ->whereYear('invoice_date', $date->year)
                ->sum('total_amount');
            return [
                'month' => $date->format('M Y'),
                'revenue' => $revenue
            ];
        });

        // Order Status Distribution
        $orderStatusData = [
            'Pending' => $pendingSalesOrders,
            'Approved' => $approvedSalesOrders,
            'Completed' => SalesOrder::where('status', 'completed')->count(),
        ];

        // Recent Activities (Latest 10)
        $recentRfqs = Rfq::latest()->take(3)->get()->map(fn($r) => [
            'type' => 'RFQ',
            'title' => $r->rfq_no,
            'status' => $r->status,
            'date' => $r->created_at,
            'icon' => 'fa-file-alt',
            'color' => 'primary'
        ]);

        $recentQuotations = Quotation::latest()->take(3)->get()->map(fn($q) => [
            'type' => 'Quotation',
            'title' => $q->quotation_no,
            'status' => $q->status,
            'date' => $q->created_at,
            'icon' => 'fa-file-invoice',
            'color' => 'success'
        ]);

        $recentSalesOrders = SalesOrder::latest()->take(3)->get()->map(fn($s) => [
            'type' => 'Sales Order',
            'title' => $s->sales_order_no,
            'status' => $s->status,
            'date' => $s->created_at,
            'icon' => 'fa-shopping-cart',
            'color' => 'info'
        ]);

        $recentActivities = $recentRfqs->concat($recentQuotations)->concat($recentSalesOrders)
            ->sortByDesc('date')->take(10)->values();

        // Top Customers by Revenue
        $topCustomers = TaxInvoice::select('company_id', DB::raw('SUM(total_amount) as total_revenue'))
            ->with('company:id,company')
            ->groupBy('company_id')
            ->orderByDesc('total_revenue')
            ->take(5)
            ->get();

        // Production Status for Pie Chart
        $productionStatus = [
            'Pending' => $pendingRouteCards,
            'In Production' => $inProductionRouteCards,
            'Completed' => $completedRouteCards,
        ];

        return view('superadmin.dashboard.alldashboard', compact(
            // Customer/Vendor
            'totalCustomers',
            'totalVendors',
            'totalCustomerMonthly',
            'totalCustomerAnnual',
            // Sales
            'totalRfqs',
            'pendingRfqs',
            'approvedRfqs',
            'totalQuotations',
            'pendingQuotations',
            'approvedQuotations',
            'totalSalesOrders',
            'pendingSalesOrders',
            'approvedSalesOrders',
            'totalInvoices',
            'monthlyRevenue',
            'annualRevenue',
            // Purchase
            'totalPurchaseRfqs',
            'pendingPurchaseRfqs',
            'totalPurchaseQuotations',
            'totalPurchaseOrders',
            'pendingPurchaseOrders',
            'totalGrns',
            // Manufacturing
            'totalRouteCards',
            'pendingRouteCards',
            'inProductionRouteCards',
            'completedRouteCards',
            'dayTasksPercent',
            'runningProjects',
            // Inventory
            'totalSkus',
            'lowStockItems',
            'outOfStockItems',
            'totalStockValue',
            // Machines
            'totalMachines',
            // Employees
            'totalEmployees',
            'employeePresent',
            'employeeLeave',
            // Pending
            'pendingBills',
            'totalPendingApprovals',
            // Charts
            'salesTrend',
            'orderStatusData',
            'recentActivities',
            'topCustomers',
            'productionStatus'
        ));
    }
    public function employeeDashboard()
    {
        $today = now()->toDateString();

        // Total Employees
        $totalEmployees = \App\Models\EmployeeDetails::count();

        // Present Today (based on EmployeeDailyReport)
        $presentToday = \App\Models\EmployeeDailyReport::whereDate('date', $today)->distinct('employee_id')->count('employee_id');

        // Employees On Leave Today
        $onLeaveToday = \App\Models\EmployeeLeave::where('status', 'approved')
            ->whereDate('leave_from', '<=', $today)
            ->whereDate('leave_to', '>=', $today)
            ->count();

        // Absent Today = Total - Present - On Leave
        $absentToday = $totalEmployees - $presentToday - $onLeaveToday;

        // Monthly Attendance Data for Chart
        $attendanceMonthly = \App\Models\EmployeeDailyReport::selectRaw('MONTH(date) as month, COUNT(DISTINCT employee_id) as present_count')
            ->whereYear('date', now()->year)
            ->groupBy('month')
            ->orderBy('month')
            ->pluck('present_count', 'month')
            ->toArray();

        // Department Distribution for Chart
        $departmentDist = \App\Models\EmployeeDetails::selectRaw('department, COUNT(*) as total')
            ->groupBy('department')
            ->pluck('total', 'department')
            ->toArray();

        // Pass data to view
        return view('superadmin.dashboard.employeedashboard', compact(
            'totalEmployees',
            'presentToday',
            'onLeaveToday',
            'absentToday',
            'attendanceMonthly',
            'departmentDist'
        ));
    }

    public function machineDashboard()
    {
        $allMachines = \App\Models\Machines::all();
        $totalMachines = $allMachines->count();

        // Machines Running Now: Assuming you store current running info in ManufacturingPlan or similar (you may adjust field names as needed)
        $runningNow = \App\Models\ManufacturingPlan::where('status', 'running')
            ->whereDate('start_date', '<=', now())
            ->where(function ($q) {
                $q->whereNull('end_date')->orWhereDate('end_date', '>=', now());
            })
            ->distinct('machine')->count('machine');

        // Under Maintenance: Let's say 'status' = 'maintenance' in ManufacturingPlan or you have a dedicated maintenance table
        $underMaintenance = \App\Models\ManufacturingPlan::where('status', 'maintenance')
            ->whereDate('start_date', '<=', now())
            ->where(function ($q) {
                $q->whereNull('end_date')->orWhereDate('end_date', '>=', now());
            })
            ->count();

        // Issues Today: assuming you store issues in ManufacturingPlan (or you may have a separate MachineIssues table)
        $issuesToday = \App\Models\ManufacturingPlan::where('status', 'issue')
            ->whereDate('plan_date', now())
            ->count();

        // Production Output Last 7 Days (dummy: count of plans per day, or replace with your real output logic)
        $productionLast7 = \App\Models\ManufacturingPlan::selectRaw('DATE(plan_date) as date, COUNT(*) as output')
            ->whereDate('plan_date', '>=', now()->subDays(6))
            ->groupBy('date')
            ->orderBy('date')
            ->pluck('output', 'date')
            ->toArray();

        // Machine Status Distribution (Running, Maintenance, Idle, etc.)
        $machineStatus = [
            'Running' => $runningNow,
            'Maintenance' => $underMaintenance,
            'Idle' => max($totalMachines - $runningNow - $underMaintenance, 0),
        ];

        // Current Operators on Shift (Assuming operator is stored in ManufacturingPlan, adapt as needed)
        $currentOperators = \App\Models\ManufacturingPlan::where('status', 'running')
            ->whereDate('plan_date', now())
            ->with('operator:id,name,designation,profile_picture') // adjust relationship as per your models
            ->get()
            ->map(function ($plan) {
                return [
                    'name' => optional($plan->operator)->name ?? 'N/A',
                    'role' => optional($plan->operator)->designation ?? 'Operator',
                    'status' => 'Available', // Replace with actual status if you have
                    'profile_picture' => optional($plan->operator)->profile_picture ?? 'https://umbreyengineering.com/indus/public/img/undraw_profile.svg',
                ];
            })
            ->unique('name')
            ->unique('name')
            ->take(5);

        // Active Processes (Real-time)
        $activeProcesses = \App\Models\RouteCardProcess::where('status', 'in_progress')
            ->with('routeCard') // Assuming relation exists
            ->get()
            ->groupBy('machine');

        return view('superadmin.dashboard.machinedashboard', compact(
            'totalMachines',
            'runningNow',
            'underMaintenance',
            'issuesToday',
            'productionLast7',
            'machineStatus',
            'currentOperators',
            'activeProcesses',
            'allMachines'
        ));
    }

    public function stockDashboard()
    {
        // Total items = all SKUs
        $totalItems = \App\Models\SkuMaster::count();

        // Low stock: SKUs where current_stock <= min_order_level
        $lowStock = \App\Models\SkuMaster::whereColumn('current_stock', '<=', 'min_order_level')->count();

        // Out of stock: SKUs where current_stock == 0
        $outOfStock = \App\Models\SkuMaster::where('current_stock', 0)->count();

        // Stock movement for the chart: Last 30 days (for example)
        $movementData = \App\Models\SkuMovement::selectRaw('DATE(date) as dt, SUM(CASE WHEN type="IN" THEN quantity ELSE -quantity END) as qty')
            ->whereDate('date', '>=', now()->subDays(30))
            ->groupBy('dt')
            ->orderBy('dt')
            ->pluck('qty', 'dt')
            ->toArray();

        // Distribution: pie by category (current stock sum per category)
        $distribution = \App\Models\SkuMaster::selectRaw('category, SUM(current_stock) as total')
            ->groupBy('category')
            ->pluck('total', 'category')
            ->toArray();

        // Stock summary can be passed as array or built in Blade

        return view('superadmin.dashboard.stockdashboard', compact(
            'totalItems',
            'lowStock',
            'outOfStock',
            'movementData',
            'distribution'
        ));
    }

    public function accountDashboard()
    {
        // Revenue: sum of all invoice total_amounts for this month
        $revenue = \App\Models\TaxInvoice::whereMonth('invoice_date', now()->month)
            ->whereYear('invoice_date', now()->year)
            ->sum('total_amount');

        // Previous month revenue for growth calculation
        $prevMonthRevenue = \App\Models\TaxInvoice::whereMonth('invoice_date', now()->subMonth()->month)
            ->whereYear('invoice_date', now()->subMonth()->year)
            ->sum('total_amount');

        // Expenses: sum of purchase orders for this month
        $expenses = \App\Models\PurchaseOrder::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('grand_total');

        // Previous month expenses
        $prevMonthExpenses = \App\Models\PurchaseOrder::whereMonth('created_at', now()->subMonth()->month)
            ->whereYear('created_at', now()->subMonth()->year)
            ->sum('grand_total');

        // Gross profit = Revenue - Expenses
        $grossProfit = $revenue - $expenses;
        $prevMonthProfit = $prevMonthRevenue - $prevMonthExpenses;

        // Production cost from employee payroll
        $productionCost = \App\Models\EmployeeSalaryDetail::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('net_salary');
        $prevMonthProdCost = \App\Models\EmployeeSalaryDetail::whereMonth('created_at', now()->subMonth()->month)
            ->whereYear('created_at', now()->subMonth()->year)
            ->sum('net_salary');

        // Calculate growth percentages dynamically
        $revenueGrowth = $prevMonthRevenue > 0
            ? (($revenue - $prevMonthRevenue) / $prevMonthRevenue * 100)
            : 0;
        $revenueGrowth = ($revenueGrowth >= 0 ? '+' : '') . number_format($revenueGrowth, 1) . '%';

        $expensesGrowth = $prevMonthExpenses > 0
            ? (($expenses - $prevMonthExpenses) / $prevMonthExpenses * 100)
            : 0;
        $expensesGrowth = ($expensesGrowth >= 0 ? '+' : '') . number_format($expensesGrowth, 1) . '%';

        $profitGrowth = $prevMonthProfit != 0
            ? (($grossProfit - $prevMonthProfit) / abs($prevMonthProfit) * 100)
            : 0;
        $profitGrowth = ($profitGrowth >= 0 ? '+' : '') . number_format($profitGrowth, 1) . '%';

        $prodCostGrowth = $prevMonthProdCost > 0
            ? (($productionCost - $prevMonthProdCost) / $prevMonthProdCost * 100)
            : 0;
        $prodCostGrowth = ($prodCostGrowth >= 0 ? '+' : '') . number_format($prodCostGrowth, 1) . '%';

        // Chart data: Revenue vs Expenses over last 6 months
        $months = collect(range(0, 5))->map(function ($i) {
            return now()->subMonths($i)->format('M Y');
        })->reverse()->values();

        $chartRevenue = $months->map(function ($month) {
            $date = \Carbon\Carbon::parse($month);
            return \App\Models\TaxInvoice::whereMonth('invoice_date', $date->month)
                ->whereYear('invoice_date', $date->year)
                ->sum('total_amount');
        });

        $chartExpenses = $months->map(function ($month) {
            $date = \Carbon\Carbon::parse($month);
            return \App\Models\PurchaseOrder::whereMonth('created_at', $date->month)
                ->whereYear('created_at', $date->year)
                ->sum('grand_total');
        });

        // Cost breakdown from actual data
        $rawMaterialCost = \App\Models\PurchaseOrder::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('grand_total');
        $laborCost = \App\Models\EmployeeSalaryDetail::whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('net_salary');
        $taxAmount = \App\Models\TaxInvoice::whereMonth('invoice_date', now()->month)
            ->whereYear('invoice_date', now()->year)
            ->sum('total_tax_amount');

        $costBreakdown = [
            'Raw Material' => $rawMaterialCost,
            'Labor' => $laborCost,
            'Tax & Duties' => $taxAmount,
        ];
        // Remove zero values
        $costBreakdown = array_filter($costBreakdown, fn($v) => $v > 0);
        if (empty($costBreakdown)) {
            $costBreakdown = ['No Data' => 0];
        }

        // Financial summary from actual data
        $outstandingInvoices = \App\Models\TaxInvoice::sum('total_amount');
        $pendingPurchaseAmount = \App\Models\PurchaseOrder::where('status', 'pending')->sum('grand_total');
        $totalReceivables = \App\Models\TaxInvoice::whereMonth('invoice_date', now()->month)
            ->whereYear('invoice_date', now()->year)
            ->sum('total_amount');
        $netCashFlow = $revenue - $expenses;

        $summary = [
            ['title' => 'Outstanding Invoices', 'value' => '₹' . number_format($outstandingInvoices)],
            ['title' => 'Pending Bills', 'value' => '₹' . number_format($pendingPurchaseAmount)],
            ['title' => 'Net Cash Flow', 'value' => '₹' . number_format($netCashFlow)],
            ['title' => 'Receivables', 'value' => '₹' . number_format($totalReceivables)],
        ];

        // Recent Invoices (latest 5)
        $pendingInvoices = \App\Models\TaxInvoice::where('total_amount', '>', 0)
            ->orderBy('invoice_date', 'desc')->take(5)->get();

        return view('superadmin.dashboard.accountdashboard', compact(
            'revenue',
            'expenses',
            'grossProfit',
            'productionCost',
            'revenueGrowth',
            'expensesGrowth',
            'profitGrowth',
            'prodCostGrowth',
            'months',
            'chartRevenue',
            'chartExpenses',
            'costBreakdown',
            'summary',
            'pendingInvoices'
        ));
    }

    public function manufacturingDashboard()
    {
        // Total Production (example from previous logic)
        $totalProduction = \App\Models\ManufacturingPlan::count();

        // Machine Utilization (as before)
        $totalMachines = \App\Models\Machines::count();
        $runningPlans = \App\Models\ManufacturingPlan::where('status', 'running')->count();
        $machineUtilization = $totalMachines > 0 ? round(($runningPlans / $totalMachines) * 100) : 0;

        // Quality Rate - DYNAMIC
        $totalChecked = \App\Models\QualityControl::count();
        $totalPassed = \App\Models\QualityControl::where('status', 'pass')->count();
        $qualityRate = $totalChecked > 0 ? round(($totalPassed / $totalChecked) * 100, 1) : 100;

        // OEE Rate - Calculate dynamically
        // OEE = Availability × Performance × Quality
        // Availability = Running time / Planned time (using machine utilization as proxy)
        // Performance = Actual output / Expected output (using completed vs total plans)
        // Quality = Good units / Total units (using quality rate)
        $availability = $machineUtilization;
        $completedPlans = \App\Models\ManufacturingPlan::where('status', 'completed')->count();
        $performance = $totalProduction > 0 ? round(($completedPlans / $totalProduction) * 100) : 0;
        $oeeRate = round(($availability * $performance * $qualityRate) / 10000, 1);

        // Production Trend
        $productionTrend = \App\Models\ManufacturingPlan::selectRaw('DATE(plan_date) as day, COUNT(*) as output')
            ->whereDate('plan_date', '>=', now()->subDays(6))
            ->groupBy('day')->orderBy('day')->pluck('output', 'day')->toArray();

        // Defect Trend - DYNAMIC
        $defectTrend = \App\Models\QualityControl::selectRaw('DATE(created_at) as day, COUNT(*) as defects')
            ->where('status', 'fail')
            ->whereDate('created_at', '>=', now()->subDays(6))
            ->groupBy('day')
            ->orderBy('day')
            ->pluck('defects', 'day')
            ->toArray();

        // Machine Status
        $machineStatus = [
            'Running' => \App\Models\ManufacturingPlan::where('status', 'running')->count(),
            'Maintenance' => \App\Models\ManufacturingPlan::where('status', 'maintenance')->count(),
            'Idle' => max($totalMachines - $runningPlans, 0),
        ];

        $productionByLine = \App\Models\ManufacturingPlan::selectRaw('machine, COUNT(*) as total')
            ->whereNotNull('machine')
            ->where('machine', '!=', '')
            ->groupBy('machine')->pluck('total', 'machine')->toArray();

        // Recent Alerts - DYNAMIC from actual data
        $recentAlerts = collect();

        // Get recent QC failures
        $qcFailures = \App\Models\QualityControl::where('status', 'fail')
            ->whereDate('created_at', '>=', now()->subDays(7))
            ->orderBy('created_at', 'desc')
            ->take(3)
            ->get()
            ->map(function ($qc) {
                return [
                    'type' => 'Error',
                    'message' => 'Quality check failed - ' . ($qc->remarks ?? 'QC ID: ' . $qc->id),
                    'time' => $qc->created_at->diffForHumans(),
                ];
            });
        $recentAlerts = $recentAlerts->concat($qcFailures);

        // Get low stock SKU alerts
        $lowStockAlerts = \App\Models\SkuMaster::whereColumn('current_stock', '<=', 'min_order_level')
            ->where('current_stock', '>', 0)
            ->take(2)
            ->get()
            ->map(function ($sku) {
                return [
                    'type' => 'Warning',
                    'message' => 'Low stock alert: ' . ($sku->sku_code ?? $sku->description),
                    'time' => 'Current stock: ' . $sku->current_stock,
                ];
            });
        $recentAlerts = $recentAlerts->concat($lowStockAlerts);

        // Get machines under maintenance
        $maintenanceAlerts = \App\Models\ManufacturingPlan::where('status', 'maintenance')
            ->whereDate('updated_at', '>=', now()->subDays(7))
            ->take(2)
            ->get()
            ->map(function ($plan) {
                return [
                    'type' => 'Warning',
                    'message' => 'Machine under maintenance: ' . ($plan->machine ?? 'N/A'),
                    'time' => $plan->updated_at->diffForHumans(),
                ];
            });
        $recentAlerts = $recentAlerts->concat($maintenanceAlerts);

        // Take only 5 most recent alerts
        $recentAlerts = $recentAlerts->take(5)->values()->toArray();

        return view('superadmin.dashboard.manufacturingdashboard', compact(
            'totalProduction',
            'machineUtilization',
            'qualityRate',
            'oeeRate',
            'productionTrend',
            'defectTrend',
            'machineStatus',
            'productionByLine',
            'recentAlerts'
        ));
    }
}
