<?php

namespace App\Http\Controllers\Manager;

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\Bom;
use App\Models\EmployeeDailyReport;
use Illuminate\Http\Request;

class ManagerDashboardController extends Controller
{
    public function allDashboard()
    {
        // Fetch KPIs
        $totalCustomerMonthly = CustomerVendor::whereMonth('created_at', now()->month)->count();
        $totalCustomerAnnual = CustomerVendor::whereYear('created_at', now()->year)->count();

        // Assuming tasks are related to RouteCardProcess and ManufacturingPlan
        $totalTasks = RouteCardProcess::count();
        $completedTasks = RouteCardProcess::where('actual_end', '!=', null)->count();
        $dayTasksPercent = $totalTasks > 0 ? ($completedTasks / $totalTasks) * 100 : 0;

        $pendingBills = PurchaseOrder::where('status', 'Pending')->count();
        $runningProjects = ManufacturingPlan::where('status', 'In Progress')->count();

        $today = now()->toDateString();
        $employeePresent = EmployeeDailyReport::where('date', $today)->where('first_half', 'Present')->count();
        $employeeLeave = EmployeeLeave::whereDate('leave_from', '<=', $today)
            ->whereDate('leave_to', '>=', $today)
            ->count();

        // BOM Table
        // Replace 'Bom' with your actual BOM model
        $bomList = CustomerVendor::all();

        // Example Pie Chart Data for Machine Planning
        $machinePlanning = [
            ['label' => 'Running', 'value' => 6],
            ['label' => 'Idle', 'value' => 2],
            ['label' => 'Maintenance', 'value' => 1],
        ];

        // Example Bar Chart Data for Monthly Company Revenue
        $monthlyRevenue = [
            ['month' => 'Jan', 'company' => 'ABC Ltd', 'revenue' => 12000],
            ['month' => 'Feb', 'company' => 'XYZ Pvt', 'revenue' => 18500],
            ['month' => 'Mar', 'company' => 'LMN Inc', 'revenue' => 14500],
            // Add more as needed...
        ];

        return view('manager.dashboard.alldashboard', compact(
            'totalCustomerMonthly',
            'totalCustomerAnnual',
            'dayTasksPercent',
            'pendingBills',
            'runningProjects',
            'employeePresent',
            'employeeLeave',
            'bomList',
            'machinePlanning',
            'monthlyRevenue'
        ));
    }
    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('manager.dashboard.employeedashboard', compact(
            'totalEmployees',
            'presentToday',
            'onLeaveToday',
            'absentToday',
            'attendanceMonthly',
            'departmentDist'
        ));
    }

    public function machineDashboard()
    {
        $totalMachines = \App\Models\Machines::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')
            ->take(5);

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

    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('manager.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)->sum('total_amount');

        // Expenses: You may have an Expense model; for now, let's simulate:
        $expenses = \App\Models\TaxInvoice::whereMonth('invoice_date', now()->month)->sum('total_tax_amount'); // Use real Expense model if exists

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

        // Production cost: You can get from Payroll/other table; using expenses as a placeholder
        $productionCost = $expenses;

        // Growth %s (for demo, hardcoded; you can calculate based on previous month)
        $revenueGrowth = "+12.5%";
        $expensesGrowth = "+8.2%";
        $profitGrowth = "+5.3%";
        $prodCostGrowth = "+3.7%";

        // 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) {
            return \App\Models\TaxInvoice::whereMonth('invoice_date', \Carbon\Carbon::parse($month)->month)
                ->sum('total_amount');
        });

        $chartExpenses = $months->map(function ($month) {
            return \App\Models\TaxInvoice::whereMonth('invoice_date', \Carbon\Carbon::parse($month)->month)
                ->sum('total_tax_amount');
        });

        // Pie chart: cost breakdown (for demo, dummy data)
        $costBreakdown = [
            'Raw Material' => 65000,
            'Labor' => 20000,
            'Utilities' => 13500,
            'Other' => 20000,
        ];

        // Financial summary (for demo)
        $summary = [
            ['title' => 'Outstanding Invoices', 'value' => '₹34,200'],
            ['title' => 'Pending Bills', 'value' => '₹12,500'],
            ['title' => 'Net Cash Flow', 'value' => '₹28,800'],
            ['title' => 'Receivables', 'value' => '₹16,700'],
        ];

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

        return view('manager.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 - NOW DYNAMIC
        $totalChecked = \App\Models\QualityControl::count();
        $totalPassed = \App\Models\QualityControl::where('status', 'pass')->count();
        $qualityRate = $totalChecked > 0 ? round(($totalPassed / $totalChecked) * 100, 1) : 100;

        // OEE (static unless you have the 3 OEE metrics)
        $oeeRate = 72;

        // 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 - NOW 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, Production by Line, Alerts (as before)
        $machineStatus = [
            'Running' => \App\Models\ManufacturingPlan::where('status', 'running')->count(),
            'Maintenance' => \App\Models\ManufacturingPlan::where('status', 'maintenance')->count(),
            'Idle' => $totalMachines - $runningPlans,
        ];

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

        $recentAlerts = [
            ['type' => 'Warning', 'message' => 'Machine M1 temperature high', 'time' => '2 min ago'],
            ['type' => 'Error', 'message' => 'Quality check failed on line 2', 'time' => '10 min ago'],
        ];

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