<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderCancellationRequest;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        // ✅ KHUSUS ROLE FINISHING
        if (method_exists($user, 'hasRole') && $user->hasRole('Finishing')) {
            return view('pages.finishing.dashboard', $this->getFinishingDashboard($request));
        }

        // Role-based dashboard data (TIDAK DIUBAH)
        $data = match (true) {
            $user->isDeveloper() => $this->getDeveloperDashboard(),
            $user->isOwner() => $this->getOwnerDashboard(),
            $user->isSPV() => $this->getSPVDashboard(),
            $user->isDesigner() => $this->getDesignerDashboard($user),
            $user->isKasir() => $this->getKasirDashboard($user, $request),
            $user->isOperator() => $this->getOperatorDashboard(),
            $user->isAdministrasi() => $this->getAdministrasiDashboard($user),
            default => $this->getDesignerDashboard($user),
        };

        return view('pages.dashboard', $data);
    }

    /**
     * ✅ Dashboard khusus FINISHING (anti-500)
     * - mode: per_invoice / per_item (per_item tetap aman kosong kalau belum siap)
     * - filter: category=all|versant|indoor|outdoor
     * - search: invoice/customer/file/note
     */
    protected function getFinishingDashboard(Request $request): array
    {
        $viewMode = $request->input('mode', 'per_invoice');
        $search   = $request->input('search');
        $category = $request->input('category', 'all');

        $allowed = ['all', 'versant', 'indoor', 'outdoor'];
        if (!in_array($category, $allowed, true)) {
            $category = 'all';
        }

        // Default aman buat blade
        $finishingOrders = collect();
        $completedOrders = collect();
        $finisherMap = []; // id => name (operator finishing)

        try {
            if ($viewMode === 'per_invoice') {
                $q = Order::with(['designer', 'operator', 'activeItems'])
                    ->notCancelled();

                // 1) Kalau ada scopeFinishing -> pakai
                if (method_exists(Order::class, 'scopeFinishing')) {
                    $q->finishing();
                } else {
                    // 2) Kalau tidak ada, coba beberapa nama kolom status (anti unknown column)
                    $statusCols = [
                        'production_status',
                        'production_stage',
                        'status_produksi',
                        'status',
                        'progress_status',
                        'state',
                    ];

                    $applied = false;

                    foreach ($statusCols as $col) {
                        try {
                            (clone $q)->whereIn($col, ['finishing', 'Finishing', 'FINISHING'])->limit(1)->get();
                            $q->whereIn($col, ['finishing', 'Finishing', 'FINISHING']);
                            $applied = true;
                            break;
                        } catch (\Throwable $e) {
                            continue;
                        }
                    }

                    if (!$applied && method_exists(Order::class, 'scopeInProgress')) {
                        $q->inProgress();
                    }
                }

                // Filter kategori (fallback: product_name LIKE)
                if ($category !== 'all') {
                    $q->whereHas('activeItems', function ($qi) use ($category) {
                        $qi->where('product_name', 'like', '%' . $category . '%');
                    });
                }

                // Search
                if ($search) {
                    $q->where(function ($qq) use ($search) {
                        $qq->where('invoice_number', 'like', "%{$search}%")
                            ->orWhere('customer_name', 'like', "%{$search}%")
                            ->orWhereHas('activeItems', function ($qi) use ($search) {
                                $qi->where('file_name', 'like', "%{$search}%")
                                    ->orWhere('product_name', 'like', "%{$search}%")
                                    ->orWhere('finishing_note', 'like', "%{$search}%");
                            });
                    });
                }

                $finishingOrders = $q->oldest()->get();

                /**
                 * ✅ FIX UTAMA:
                 * Laporan "Selesai Hari Ini" harus berdasarkan finished_at,
                 * bukan created_at (today()).
                 */
                $completedOrders = Order::with(['activeItems', 'operator', 'finishingOperator'])
                    ->notCancelled()
                    ->completed()
                    ->whereDate('finished_at', today())
                    ->latest('finished_at')
                    ->take(80)
                    ->get();

                // finisherMap (biar blade lama tetap aman)
                $finisherIdColCandidates = ['finishing_operator_id', 'finisher_id', 'finishing_user_id', 'finisher_user_id'];
                $finisherCol = null;

                foreach ($finisherIdColCandidates as $col) {
                    try {
                        Order::query()->select($col)->limit(1)->get();
                        $finisherCol = $col;
                        break;
                    } catch (\Throwable $e) {
                        continue;
                    }
                }

                if ($finisherCol) {
                    $ids = $completedOrders->pluck($finisherCol)->filter()->unique()->values();
                    if ($ids->count() > 0) {
                        $finisherMap = User::whereIn('id', $ids)->pluck('name', 'id')->toArray();
                    }
                }
            }
        } catch (\Throwable $e) {
            report($e);
            $finishingOrders = collect();
            $completedOrders = collect();
            $finisherMap = [];
        }

        return [
            'title' => 'Finishing',
            'viewMode' => $viewMode,
            'search' => $search,
            'category' => $category,

            'finishingOrders' => $finishingOrders,
            'completedOrders' => $completedOrders,

            // dipakai untuk blade lama
            'finisherMap' => $finisherMap,

            // mode per_item belum dipakai
            'finishingItems' => collect(),
            'completedItems' => collect(),
        ];
    }
    public function readyOrdersApi()
    {
    $orders = Order::where('status', 'ready')
        ->latest()
        ->take(30)
        ->get();

    return response()->json($orders);
    }
    // ======================= KODE KAMU ASLI (TIDAK DIUBAH) =======================

    protected function getDeveloperDashboard(): array
    {
        return [
            'title' => 'Developer Dashboard',
            'stats' => [
                'total_orders' => Order::count(),
                'orders_today' => Order::today()->count(),
                'unpaid_orders' => Order::unpaid()->count(),
                'in_progress' => Order::inProgress()->count(),
                'completed_today' => Order::today()->completed()->count(),
                'revenue_today' => Order::today()->paid()->sum('total_price'),
                'revenue_month' => Order::whereMonth('created_at', now()->month)->paid()->sum('total_price'),
                'ready_for_pickup' => Order::completed()->notPickedUp()->count(),
                'receivables_total' => Order::whereIn('payment_status', [Order::PAYMENT_UNPAID, Order::PAYMENT_PARTIAL])->sum(DB::raw('total_price - paid_amount')),
            ],
            'recent_orders' => Order::with(['designer', 'cashier'])
                ->latest()
                ->take(10)
                ->get(),
            'users' => User::orderBy('role')->get(),
            'ready_for_pickup_orders' => Order::with(['designer', 'operator'])
                ->completed()
                ->notPickedUp()
                ->latest('finished_at')
                ->take(5)
                ->get(),
        ];
    }

    protected function getSPVDashboard(): array
    {
        return [
            'title' => 'SVP Dashboard',
            'stats' => [
                'pending_cancellations' => OrderCancellationRequest::pending()->count(),
                'orders_today' => Order::today()->count(),
                'in_progress' => Order::inProgress()->count(),
                'ready_for_pickup' => Order::completed()->notPickedUp()->count(),
            ],
            'pending_cancellations' => OrderCancellationRequest::with(['order', 'orderItem', 'requester'])
                ->pending()
                ->latest()
                ->take(5)
                ->get(),
            'recent_orders' => Order::with(['designer', 'cashier'])
                ->latest()
                ->take(10)
                ->get(),
        ];
    }

    protected function getOwnerDashboard(): array
    {
        $startOfMonth = now()->startOfMonth();
        $endOfMonth = now()->endOfMonth();

        return [
            'title' => 'Owner Dashboard',
            'stats' => [
                'revenue_today' => Order::today()->paid()->sum('total_price'),
                'revenue_month' => Order::dateRange($startOfMonth, $endOfMonth)->paid()->sum('total_price'),
                'orders_today' => Order::today()->count(),
                'orders_month' => Order::dateRange($startOfMonth, $endOfMonth)->count(),
                'completed_today' => Order::today()->completed()->count(),
                'completed_month' => Order::dateRange($startOfMonth, $endOfMonth)->completed()->count(),
                'ready_for_pickup' => Order::completed()->notPickedUp()->count(),
                'receivables_total' => Order::whereIn('payment_status', [Order::PAYMENT_UNPAID, Order::PAYMENT_PARTIAL])->sum(DB::raw('total_price - paid_amount')),
            ],
            'daily_revenue' => Order::paid()
                ->whereMonth('created_at', now()->month)
                ->select(DB::raw('DATE(paid_at) as date'), DB::raw('SUM(total_price) as total'))
                ->groupBy('date')
                ->orderBy('date')
                ->get(),
        ];
    }

    protected function getDesignerDashboard(User $user): array
    {
        return [
            'title' => 'Designer Dashboard',
            'stats' => [
                'my_orders_today' => Order::today()->where('designer_id', $user->id)->count(),
                'pending_spk' => Order::where('designer_id', $user->id)
                    ->paid()
                    ->where('spk_printed', false)
                    ->count(),
                'all_orders_today' => Order::today()->count(),
                'ready_for_pickup' => Order::completed()->notPickedUp()->count(),
            ],
            'my_orders' => Order::with(['designer'])
                ->where('designer_id', $user->id)
                ->today()
                ->latest()
                ->get(),
            'paid_orders' => Order::with(['designer'])
                ->paid()
                ->where('spk_printed', false)
                ->latest()
                ->take(10)
                ->get(),
        ];
    }

    protected function getKasirDashboard(User $user, Request $request): array
    {
        $pickupSearch = $request->input('pickup_search');

        $readyForPickupQuery = Order::with(['designer', 'operator'])
            ->completed()
            ->notPickedUp()
            ->when($pickupSearch, function ($query, $search) {
                $query->where(function ($q) use ($search) {
                    $q->where('invoice_number', 'like', "%{$search}%")
                      ->orWhere('customer_name', 'like', "%{$search}%");
                });
            })
            ->latest('finished_at');

        return [
            'title' => 'Kasir Dashboard',
            'stats' => [
                'unpaid_orders' => Order::unpaid()->count(),
                'partial_orders' => Order::where('payment_status', Order::PAYMENT_PARTIAL)->count(),
                'paid_today' => Order::today()->paid()->count(),
                'revenue_today' => Order::today()->paid()->sum('total_price'),
            ],
            'unpaid_orders' => Order::with(['designer'])
                ->unpaid()
                ->latest()
                ->get(),
            'partial_orders' => Order::with(['designer', 'payments'])
                ->where('payment_status', Order::PAYMENT_PARTIAL)
                ->latest()
                ->get(),
            'ready_for_pickup_orders' => $readyForPickupQuery->paginate(30, ['*'], 'pickup_page')->withQueryString(),
        ];
    }

    protected function getOperatorDashboard(): array
    {
        return [
            'title' => 'Operator Dashboard',
            'stats' => [
                'pending' => Order::notCancelled()->paid()->pending()->count(),
                'in_progress' => Order::notCancelled()->inProgress()->count(),
                'completed_today' => Order::notCancelled()->today()->completed()->count(),
                'ready_for_pickup' => Order::notCancelled()->today()->completed()->notPickedUp()->count(),
            ],
            'pending_orders' => Order::with(['designer'])
                ->notCancelled()
                ->paid()
                ->pending()
                ->oldest()
                ->get(),
            'in_progress_orders' => Order::with(['designer', 'operator'])
                ->notCancelled()
                ->inProgress()
                ->oldest()
                ->get(),
            'completed_orders' => Order::with(['designer', 'operator'])
                ->notCancelled()
                ->today()
                ->completed()
                ->latest('finished_at')
                ->take(10)
                ->get(),
        ];
    }

    protected function getAdministrasiDashboard(User $user): array
    {
        return [
            'title' => 'Administrasi Dashboard',
            'stats' => [
                'orders_today' => Order::today()->count(),
                'unpaid_orders' => Order::unpaid()->count(),
                'in_progress' => Order::inProgress()->count(),
                'revenue_today' => Order::today()->paid()->sum('total_price'),
                'ready_for_pickup' => Order::completed()->notPickedUp()->count(),
            ],
            'recent_orders' => Order::with(['designer', 'cashier'])
                ->latest()
                ->take(10)
                ->get(),
        ];
    }
}