<?php

namespace App\Http\Controllers;

use App\Models\ConsultationSetting;
use App\Models\FacebookIntegration;
use App\Models\OperationsOrder;
use App\Models\OperationsTask;
use App\Models\OperationsTaskActivity;
use App\Models\OperationsTaskComment;
use App\Models\Service;
use App\Models\ServiceSubscription;
use App\Models\User;
use App\Services\EmployeeCommissionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class OperationsController extends Controller
{
    private function sectionPermissionResourceKey(string $section): ?string
    {
        $sections = $this->getOperationsSections();
        if (! isset($sections[$section]['title_key'])) {
            return null;
        }

        return (string) $sections[$section]['title_key'];
    }

    private function userCanViewSection(?string $resourceKey): bool
    {
        $user = Auth::user();
        if (! $user instanceof User || ! $resourceKey) {
            return false;
        }

        if (str_starts_with($resourceKey, 'operations.sections.') && $user->hasPermission('operations.services.view')) {
            return true;
        }

        return $user->hasPermission($resourceKey.'.view');
    }

    private function operationsSectionResourceForServiceType(?string $serviceType): ?string
    {
        if (! $serviceType) {
            return null;
        }

        foreach ($this->getOperationsSections() as $config) {
            $serviceTypes = $config['service_types'] ?? [];
            if (! is_array($serviceTypes)) {
                continue;
            }

            if (in_array($serviceType, $serviceTypes, true)) {
                return (string) ($config['title_key'] ?? null);
            }
        }

        return null;
    }

    private function userCanOperateOnServiceType(?string $serviceType, string $action): bool
    {
        $user = Auth::user();
        if (! $user instanceof User) {
            return false;
        }

        $sectionResource = $this->operationsSectionResourceForServiceType($serviceType);
        if ($sectionResource && $user->hasPermission($sectionResource.'.'.$action)) {
            return true;
        }

        $legacy = [
            'view' => ['operations.tasks.view', 'operations.services.view'],
            'create' => ['operations.tasks.create'],
            'update' => ['operations.tasks.update'],
            'delete' => ['operations.tasks.delete'],
        ];

        foreach (($legacy[$action] ?? []) as $perm) {
            if ($user->hasPermission($perm)) {
                return true;
            }
        }

        return false;
    }

    public function __construct()
    {
        $this->middleware('permission:operations.services.view|operations.sections.consultations.view|operations.sections.ads.view|operations.sections.custom_app.view|operations.sections.custom_website.view|operations.sections.wordpress.view|operations.sections.domains_emails.view')->only(['index', 'section']);
        $this->middleware('permission:operations.products.view')->only(['products']);

        $this->middleware('permission:operations.tasks.view|operations.services.view|operations.sections.consultations.view|operations.sections.ads.view|operations.sections.custom_app.view|operations.sections.custom_website.view|operations.sections.wordpress.view|operations.sections.domains_emails.view')->only(['show', 'showCustomerKanban', 'getTaskDetails']);
        $this->middleware('permission:operations.tasks.create|operations.sections.consultations.create|operations.sections.ads.create|operations.sections.custom_app.create|operations.sections.custom_website.create|operations.sections.wordpress.create|operations.sections.domains_emails.create')->only(['storeTask']);
        $this->middleware('permission:operations.tasks.update|operations.sections.consultations.update|operations.sections.ads.update|operations.sections.custom_app.update|operations.sections.custom_website.update|operations.sections.wordpress.update|operations.sections.domains_emails.update')->only(['updateTaskStatus', 'addTaskComment']);
    }

    private function buildWhatsAppUrlForTask(OperationsTask $task): ?string
    {
        $task->loadMissing(['item.order.subscription.customer', 'item.order.subscription.payments', 'item.order.subscription.service']);

        $subscription = $task->item?->order?->subscription;
        $allowedServiceTypes = ['wordpress_templates', 'domains_emails', 'web_development', 'app_development', 'ads_creation'];
        if (! $subscription || ! $subscription->service || ! in_array($subscription->service->type, $allowedServiceTypes, true)) {
            return null;
        }

        $allowedStatuses = ['working', 'qa', 'done', 'completed'];
        if (! in_array($task->status, $allowedStatuses, true)) {
            return null;
        }

        $phone = preg_replace('/[^0-9]/', '', $subscription->whatsapp ?? $subscription->phone ?? '');
        if (! $phone) {
            return null;
        }

        if (str_starts_with($phone, '0')) {
            $phone = '964'.substr($phone, 1);
        } elseif (! str_starts_with($phone, '964')) {
            $phone = '964'.$phone;
        }

        $stageKey = $task->status === 'done' ? 'done' : $task->status;
        $message = __('whatsapp.wp_templates.message', [
            'invoice' => $subscription->invoice_number ?? '',
            'customer' => $subscription->customer_name ?? '',
            'business' => $subscription->business_name ?? '',
            'task' => $task->title ?? '',
            'stage' => __('status.'.$stageKey),
        ]);

        if ($task->status === 'qa') {
            $total = (($subscription->price ?? 0) - ($subscription->discount ?? 0));
            $paid = $subscription->payments->sum('amount');
            $remaining = max(0, $total - $paid);
            $message .= "\n\n".__('whatsapp.wp_templates.qa_extra', [
                'total' => number_format($total, 0),
                'remaining' => number_format($remaining, 0),
            ]);
        }

        return 'https://wa.me/'.$phone.'?text='.urlencode($message);
    }

    private function getServiceTypes()
    {
        return [
            'one_time_service' => __('service_types.one_time_service'),
            'monthly_subscription_limited' => __('service_types.monthly_subscription_limited'),
            'monthly_subscription_open' => __('service_types.monthly_subscription_open'),
            'ads_creation' => __('service_types.ads_creation'),
            'web_development' => __('service_types.web_development'),
            'app_development' => __('service_types.app_development'),
            'domains_emails' => __('service_types.domains_emails'),
            'wordpress_templates' => __('service_types.wordpress_templates'),
        ];
    }

    private function getOperationsSections(): array
    {
        return [
            'consultations' => [
                'title_key' => 'operations.sections.consultations',
                'service_types' => [
                    'one_time_service',
                    'monthly_subscription_limited',
                    'monthly_subscription_open',
                ],
            ],
            'ads' => [
                'title_key' => 'operations.sections.ads',
                'service_types' => ['ads_creation'],
            ],
            'custom-app' => [
                'title_key' => 'operations.sections.custom_app',
                'service_types' => ['app_development'],
            ],
            'custom-website' => [
                'title_key' => 'operations.sections.custom_website',
                'service_types' => ['web_development'],
            ],
            'wordpress' => [
                'title_key' => 'operations.sections.wordpress',
                'service_types' => ['wordpress_templates'],
            ],
            'domains-emails' => [
                'title_key' => 'operations.sections.domains_emails',
                'service_types' => ['domains_emails'],
            ],
        ];
    }

    private function shouldShowSubscriptionInOperations(ServiceSubscription $subscription): bool
    {
        $serviceType = $subscription->service?->type;
        if (! in_array($serviceType, ['monthly_subscription_open', 'monthly_subscription_limited', 'one_time_service'], true)) {
            return true;
        }

        $hasNewer = ServiceSubscription::query()
            ->where('service_id', $subscription->service_id)
            ->where('customer_id', $subscription->customer_id)
            ->where('id', '>', $subscription->id)
            ->exists();
        if ($hasNewer) {
            return false;
        }

        if (in_array($serviceType, ['one_time_service', 'monthly_subscription_limited'], true) && $subscription->is_expired) {
            $subscription->loadMissing('order.items.tasks');
            $tasks = $subscription->order?->items ? $subscription->order->items->flatMap->tasks : collect();
            $latestDoneAt = $tasks
                ->where('status', 'done')
                ->map(fn ($task) => $task->completed_at ?? $task->updated_at ?? $task->created_at)
                ->filter()
                ->sort()
                ->last();
            if ($latestDoneAt) {
                return now()->lt($latestDoneAt->copy()->addDay());
            }
        }

        $endDate = $subscription->subscription_end_date;
        if (! $endDate) {
            return true;
        }

        return now()->lt($endDate->copy()->addDay());
    }

    public function index()
    {
        foreach (array_keys($this->getOperationsSections()) as $section) {
            $resourceKey = $this->sectionPermissionResourceKey($section);
            if ($this->userCanViewSection($resourceKey)) {
                return redirect()->route('operations.sections.'.str_replace('-', '_', $section));
            }
        }

        abort(403);
    }

    public function section(string $section)
    {
        $sections = $this->getOperationsSections();
        abort_unless(isset($sections[$section]), 404);

        $sectionConfig = $sections[$section];
        abort_unless($this->userCanViewSection($this->sectionPermissionResourceKey($section)), 403);
        $types = $this->getServiceTypes();

        $title = __($sectionConfig['title_key']);

        $services = Service::query()
            ->whereIn('type', $sectionConfig['service_types'])
            ->latest()
            ->get();

        return view('operations.section', compact('services', 'types', 'section', 'title'));
    }

    public function show($id)
    {
        $service = Service::findOrFail($id);
        abort_unless($this->userCanOperateOnServiceType($service->type, 'view'), 403);

        $search = trim((string) request()->query('q', ''));
        $parts = $this->smartSearchParts($search);
        $search = $parts['search'];
        $searchRaw = $parts['searchRaw'];
        $searchDigits = $parts['searchDigits'];
        $terms = $parts['terms'];

        // Fetch subscriptions (customers) for this service
        $subscriptionsQuery = $service->subscriptions()
            ->with(['customer', 'service', 'order.items.tasks', 'workEmployee'])
            ->latest();

        if ($search !== '') {
            $subscriptionsQuery->where(function ($q) use ($search, $searchRaw, $searchDigits, $terms) {
                $q->where('invoice_number', 'like', '%'.$search.'%')
                    ->orWhereHas('customer', function ($cq) use ($searchRaw, $searchDigits, $terms) {
                        $cq->where(function ($textQ) use ($terms) {
                            $textQ->where(function ($nameQ) use ($terms) {
                                foreach ($terms as $t) {
                                    $nameQ->where('name', 'like', '%'.$t.'%');
                                }
                            })->orWhere(function ($bizQ) use ($terms) {
                                foreach ($terms as $t) {
                                    $bizQ->where('business_name', 'like', '%'.$t.'%');
                                }
                            });
                        })->orWhere('phone', 'like', '%'.$searchRaw.'%')
                            ->orWhere('whatsapp', 'like', '%'.$searchRaw.'%');

                        if ($searchDigits !== '') {
                            $cq->orWhere('phone', 'like', '%'.$searchDigits.'%')
                                ->orWhere('whatsapp', 'like', '%'.$searchDigits.'%');
                        }
                    });
            });
        }

        $subscriptions = $subscriptionsQuery
            ->get()
            ->each(function (ServiceSubscription $subscription) {
                $serviceType = (string) ($subscription->service?->type ?? '');
                if (! in_array($serviceType, ['monthly_subscription_open', 'monthly_subscription_limited', 'one_time_service'], true)) {
                    return;
                }

                $latestRenewal = $subscription->renewals()
                    ->latest('created_at')
                    ->first(['id', 'invoice_number', 'created_at']);
                if (! $latestRenewal) {
                    return;
                }

                $orderCreatedAt = $subscription->order?->created_at;
                if (! $orderCreatedAt || $orderCreatedAt->lt($latestRenewal->created_at)) {
                    $newOrder = OperationsOrder::create([
                        'service_subscription_id' => $subscription->id,
                        'customer_name' => $subscription->customer_name,
                        'phone' => $subscription->phone,
                        'created_by' => Auth::id(),
                    ]);
                    $subscription->setRelation('order', $newOrder);
                }

                if ($subscription->invoice_number !== $latestRenewal->invoice_number) {
                    $invoiceTaken = ServiceSubscription::query()
                        ->where('invoice_number', $latestRenewal->invoice_number)
                        ->where('id', '!=', $subscription->id)
                        ->exists();
                    if (! $invoiceTaken) {
                        $subscription->update(['invoice_number' => $latestRenewal->invoice_number]);
                        $subscription->invoice_number = $latestRenewal->invoice_number;
                    }
                }
            })
            ->filter(fn (ServiceSubscription $subscription) => $this->shouldShowSubscriptionInOperations($subscription))
            ->values();

        return view('operations.show', compact('service', 'subscriptions', 'search'));
    }

    public function showCustomerKanban($serviceId, $subscriptionId, EmployeeCommissionService $commissionService)
    {
        $service = Service::findOrFail($serviceId);
        $subscription = ServiceSubscription::with(['customer', 'service', 'order.items.tasks', 'order.items.tasks.comments', 'order.items.tasks.activities'])->findOrFail($subscriptionId);
        abort_unless($this->userCanOperateOnServiceType($service->type, 'view'), 403);

        $serviceType = (string) ($subscription->service?->type ?? '');
        if (in_array($serviceType, ['monthly_subscription_open', 'monthly_subscription_limited', 'one_time_service'], true)) {
            $latestRenewal = $subscription->renewals()
                ->latest('created_at')
                ->first(['id', 'invoice_number', 'created_at']);
            if ($latestRenewal) {
                $orderCreatedAt = $subscription->order?->created_at;
                if (! $orderCreatedAt || $orderCreatedAt->lt($latestRenewal->created_at)) {
                    $newOrder = OperationsOrder::create([
                        'service_subscription_id' => $subscription->id,
                        'customer_name' => $subscription->customer_name,
                        'phone' => $subscription->phone,
                        'created_by' => Auth::id(),
                    ]);
                    $subscription->setRelation('order', $newOrder);
                }

                if ($subscription->invoice_number !== $latestRenewal->invoice_number) {
                    $invoiceTaken = ServiceSubscription::query()
                        ->where('invoice_number', $latestRenewal->invoice_number)
                        ->where('id', '!=', $subscription->id)
                        ->exists();
                    if (! $invoiceTaken) {
                        $subscription->update(['invoice_number' => $latestRenewal->invoice_number]);
                        $subscription->invoice_number = $latestRenewal->invoice_number;
                    }
                }
            }
        }

        // Check if subscription has an order, if not create one (mostly for data integrity)
        if (! $subscription->order) {
            // We'll create it when adding the first task if it doesn't exist,
            // but here we just handle the view.
        }

        // Get all tasks for this subscription
        $tasks = collect();
        if ($subscription->order) {
            foreach ($subscription->order->items as $item) {
                foreach ($item->tasks as $task) {
                    // Manually load relationships for task to avoid N+1 if not eager loaded properly above
                    $task->load(['comments.user', 'activities.user', 'item.order.subscription.payments']);
                    $tasks->push($task);
                }
            }
        }

        if (! $subscription->work_employee_id) {
            $firstTask = $tasks->sortBy('created_at')->first();
            $workUserId = (int) ($firstTask?->started_by_user_id ?: $firstTask?->completed_by_user_id ?: 0);
            $employee = $workUserId ? \App\Models\Employee::query()->where('user_id', $workUserId)->first() : null;
            if ($employee) {
                $subscription->update(['work_employee_id' => $employee->id]);
            }
        }

        if (! $subscription->sales_employee_id) {
            $employeeId = \App\Models\Employee::query()->where('user_id', $subscription->created_by)->value('id');
            if ($employeeId) {
                $subscription->update(['sales_employee_id' => $employeeId]);
            }
        }

        // Group tasks by status
        $pendingTasks = $tasks->where('status', 'pending')->sortBy('order_column');
        $workingTasks = $tasks->where('status', 'working')->sortBy('order_column');
        $qaTasks = $tasks->where('status', 'qa')->sortBy('order_column');
        $doneTasks = $tasks->where('status', 'done')->sortBy('order_column');

        $commissionService->createConsultationsWorkCommissionIfEligible($subscription);
        $commissionService->createSalesCommissionForSubscription($subscription, (int) $subscription->created_by);

        $facebookIntegration = null;
        if (in_array($service->type, ['monthly_subscription_open', 'monthly_subscription_limited', 'one_time_service'], true) && $subscription->customer_id) {
            $facebookIntegration = FacebookIntegration::query()
                ->where('customer_id', $subscription->customer_id)
                ->first();

            if (! $facebookIntegration) {
                $facebookIntegration = FacebookIntegration::query()->create([
                    'customer_id' => $subscription->customer_id,
                    'service_type' => $service->type,
                    'assigned_employee_id' => Auth::id(),
                    'connection_status' => 'pending_connection',
                ]);
            } else {
                $user = Auth::user();
                if ($user && ! $user->is_admin && (int) $facebookIntegration->assigned_employee_id !== (int) $user->id && ! $facebookIntegration->access_token) {
                    $facebookIntegration->update(['assigned_employee_id' => $user->id]);
                }
            }
        }

        $consultationsCampaignManagementEnabled = true;
        if (Schema::hasTable('consultation_settings')) {
            $settings = ConsultationSetting::query()->firstOrCreate(['id' => 1], ['campaign_management_enabled' => true]);
            $consultationsCampaignManagementEnabled = (bool) $settings->campaign_management_enabled;
        }

        return view('operations.kanban', compact('service', 'subscription', 'pendingTasks', 'workingTasks', 'qaTasks', 'doneTasks', 'facebookIntegration', 'consultationsCampaignManagementEnabled'));
    }

    public function storeTask(Request $request)
    {
        $request->validate([
            'subscription_id' => 'required|exists:service_subscriptions,id',
        ]);

        $subscription = \App\Models\ServiceSubscription::with('order')->findOrFail($request->subscription_id);
        abort_unless($this->userCanOperateOnServiceType($subscription->service?->type, 'create'), 403);

        // Check for Monthly Subscription Open specific logic
        if ($subscription->service->type === 'monthly_subscription_open') {
            if ($subscription->is_expired) {
                return response()->json(['error' => 'Subscription expired'], 403);
            }
        }

        // Check for Monthly Subscription Limited specific logic
        if ($subscription->service->type === 'monthly_subscription_limited') {
            if ($subscription->is_expired) {
                return response()->json(['error' => 'Subscription expired'], 403);
            }

            // Check card limit (max 3)
            $currentCardCount = $subscription->order ? $subscription->order->items()->count() : 0;
            if ($currentCardCount >= 3) {
                return response()->json(['error' => 'Card limit reached (3 max)'], 403);
            }
        }

        // Check for One Time Service specific logic
        if ($subscription->service->type === 'one_time_service') {
            $maxCards = max(1, (int) ($subscription->consultations_count ?? 1));
            $currentCardCount = $subscription->order ? $subscription->order->items()->count() : 0;
            if ($currentCardCount >= $maxCards) {
                return response()->json(['error' => "Card limit reached ({$maxCards} max)"], 403);
            }
        }

        DB::transaction(function () use ($subscription) {
            // Ensure Order exists
            $order = $subscription->order;
            if (! $order) {
                $order = OperationsOrder::create([
                    'service_subscription_id' => $subscription->id,
                    'customer_name' => $subscription->customer_name,
                    'phone' => $subscription->phone,
                    'created_by' => Auth::id(),
                ]);
            }

            $existingCount = $order->items()->count();

            if ($existingCount === 0 && ! $subscription->work_employee_id) {
                $employee = \App\Models\Employee::query()->where('user_id', Auth::id())->first();
                if ($employee) {
                    $subscription->update(['work_employee_id' => $employee->id]);
                }
            }

            // Determine the next card number
            $nextNumber = $existingCount + 1;
            $itemName = "Card #{$nextNumber}";

            // Create Item
            $item = $order->items()->create([
                'item_name' => $itemName,
                'qty' => 1,
                'status' => 'pending',
                'order_id' => $order->id,
            ]);

            // Create Task
            $task = $item->tasks()->create([
                'title' => $itemName,
                'status' => 'pending',
                'order_column' => 0,
                'started_by_user_id' => Auth::id(),
                'started_at' => now(),
            ]);

            // Log creation activity
            OperationsTaskActivity::create([
                'task_id' => $task->id,
                'user_id' => Auth::id(),
                'activity_type' => 'created',
                'description' => 'Card created',
            ]);
        });

        return response()->json(['success' => true]);
    }

    public function updateTaskStatus(Request $request, EmployeeCommissionService $commissionService)
    {
        $request->validate([
            'task_id' => 'required|exists:operations_tasks,id',
            'status' => 'required|in:pending,working,qa,done',
            'order_column' => 'nullable|integer',
        ]);

        $task = OperationsTask::findOrFail($request->task_id);
        $task->loadMissing(['item.order.subscription.service']);
        abort_unless($this->userCanOperateOnServiceType($task->item?->order?->subscription?->service?->type, 'update'), 403);
        $oldStatus = $task->status;
        $newStatus = $request->status;

        $now = now();
        $updateData = [
            'status' => $newStatus,
            'order_column' => $request->order_column ?? 0,
        ];

        if ($oldStatus === 'pending' && $newStatus !== 'pending' && ! $task->started_by_user_id) {
            $updateData['started_by_user_id'] = Auth::id();
            $updateData['started_at'] = $now;
        }

        if ($newStatus === 'done' && ! $task->completed_at) {
            $updateData['completed_by_user_id'] = Auth::id();
            $updateData['completed_at'] = $now;
        }

        $task->update($updateData);

        $subscription = $task->item?->order?->subscription;
        if ($subscription && ! $subscription->work_employee_id) {
            $task->loadMissing(['item.order.subscription.order.items.tasks']);
            $tasks = $subscription->order?->items
                ? $subscription->order->items->flatMap->tasks
                : collect();
            $firstTask = $tasks->sortBy('created_at')->first();
            if ($firstTask && (int) $firstTask->id === (int) $task->id) {
                $employee = \App\Models\Employee::query()->where('user_id', Auth::id())->first();
                if ($employee) {
                    $subscription->update(['work_employee_id' => $employee->id]);
                }
            }
        }

        // Also update the parent item status if needed (optional logic)
        // For now, we just track the task.

        // Log activity
        if ($oldStatus !== $newStatus) {
            OperationsTaskActivity::create([
                'task_id' => $task->id,
                'user_id' => Auth::id(),
                'activity_type' => 'status_change',
                'description' => 'Moved from '.__('status.'.$oldStatus).' to '.__('status.'.$newStatus),
            ]);
        }

        if ($oldStatus !== 'done' && $newStatus === 'done') {
            $serviceType = $subscription?->service?->type;

            if (in_array($serviceType, ['one_time_service', 'monthly_subscription_limited', 'monthly_subscription_open'], true)) {
                if ($subscription) {
                    $commissionService->createConsultationsWorkCommissionIfEligible($subscription);
                }
            } else {
                $commissionService->createWorkCommissionForTaskCompletion($task, (int) Auth::id());
            }

            if ($serviceType === 'monthly_subscription_limited' && $subscription && $subscription->hasCompletedLimitedCards()) {
                $today = now()->toDateString();
                $currentRenewalDueDate = $subscription->renewal_due_date
                    ? date('Y-m-d', strtotime((string) $subscription->renewal_due_date))
                    : null;

                if (! $currentRenewalDueDate || $currentRenewalDueDate > $today) {
                    $subscription->update(['renewal_due_date' => $today]);
                }
            }
        }

        $whatsappUrl = $this->buildWhatsAppUrlForTask($task);

        return response()->json([
            'success' => true,
            'whatsapp_url' => $whatsappUrl,
            'whatsapp_label' => __('whatsapp.send_message'),
        ]);
    }

    public function getTaskDetails($id)
    {
        $task = OperationsTask::with(['comments.user', 'activities.user', 'item.order.subscription', 'item.order.subscription.order.items.tasks'])->findOrFail($id);
        $task->loadMissing(['item.order.subscription.service', 'item.order.subscription.workEmployee', 'item.order.subscription.salesEmployee', 'item.order.subscription.order.items.tasks']);
        abort_unless($this->userCanOperateOnServiceType($task->item?->order?->subscription?->service?->type, 'view'), 403);

        $subscription = $task->item?->order?->subscription;
        $workEmployee = null;
        if ($subscription) {
            $employee = $subscription->workEmployee;
            if (! $employee) {
                $tasks = $subscription->order?->items
                    ? $subscription->order->items->flatMap->tasks
                    : collect();
                $firstTask = $tasks->sortBy('created_at')->first();
                $workUserId = (int) ($firstTask?->started_by_user_id ?: $firstTask?->completed_by_user_id ?: 0);
                $employee = $workUserId ? \App\Models\Employee::query()->where('user_id', $workUserId)->first() : null;
            }

            if ($employee) {
                $workEmployee = [
                    'id' => $employee->id,
                    'name' => $employee->full_name,
                ];
            }
        }

        $salesEmployee = null;
        if ($subscription) {
            $employee = $subscription->salesEmployee ?: \App\Models\Employee::query()->find($subscription->sales_employee_id);
            if (! $employee) {
                $employee = \App\Models\Employee::query()->where('user_id', $subscription->created_by)->first();
            }

            if ($employee) {
                $salesEmployee = [
                    'id' => $employee->id,
                    'name' => $employee->full_name,
                ];
            }
        }

        $employeesList = null;
        if (Auth::user()?->is_admin) {
            $employeesList = \App\Models\Employee::query()
                ->where('is_active', true)
                ->orderBy('full_name')
                ->get(['id', 'full_name'])
                ->map(fn ($e) => ['id' => $e->id, 'name' => $e->full_name]);
        }

        return response()->json([
            'task' => $task,
            'subscription_id' => $subscription?->id,
            'work_employee' => $workEmployee,
            'work_employee_override_id' => $subscription?->work_employee_id,
            'sales_employee' => $salesEmployee,
            'sales_employee_override_id' => $subscription?->sales_employee_id,
            'can_edit_work_employee' => (bool) (Auth::user()?->is_admin),
            'can_edit_sales_employee' => (bool) (Auth::user()?->is_admin),
            'employees' => $employeesList,
            'comments' => $task->comments->map(function ($comment) {
                return [
                    'id' => $comment->id,
                    'user_name' => $comment->user->name,
                    'comment' => $comment->comment,
                    'created_at' => $comment->created_at->translatedFormat('Y-m-d h:i A'),
                ];
            }),
            'activities' => $task->activities->map(function ($activity) {
                return [
                    'id' => $activity->id,
                    'description' => $activity->description,
                    'user_name' => $activity->user ? $activity->user->name : 'System',
                    'created_at' => $activity->created_at->translatedFormat('Y-m-d h:i A'),
                ];
            }),
        ]);
    }

    public function updateSubscriptionWorkEmployee(Request $request, ServiceSubscription $subscription, EmployeeCommissionService $commissionService)
    {
        abort_unless(Auth::user()?->is_admin, 403);

        $request->validate([
            'employee_id' => 'nullable|exists:employees,id',
        ]);

        $employeeId = $request->input('employee_id');
        if (! $employeeId) {
            $subscription->loadMissing(['order.items.tasks']);
            $tasks = $subscription->order?->items
                ? $subscription->order->items->flatMap->tasks
                : collect();
            $firstTask = $tasks->sortBy('created_at')->first();
            $workUserId = (int) ($firstTask?->started_by_user_id ?: $firstTask?->completed_by_user_id ?: 0);
            $employeeId = $workUserId
                ? \App\Models\Employee::query()->where('user_id', $workUserId)->value('id')
                : null;
        }

        $subscription->update([
            'work_employee_id' => $employeeId,
        ]);

        $commission = $commissionService->createConsultationsWorkCommissionIfEligible($subscription);
        $workEmployee = $subscription->fresh()->workEmployee;

        return response()->json([
            'success' => true,
            'work_employee' => $workEmployee ? ['id' => $workEmployee->id, 'name' => $workEmployee->full_name] : null,
            'commission_updated' => (bool) $commission,
        ]);
    }

    public function updateSubscriptionSalesEmployee(Request $request, ServiceSubscription $subscription, EmployeeCommissionService $commissionService)
    {
        abort_unless(Auth::user()?->is_admin, 403);

        $request->validate([
            'employee_id' => 'nullable|exists:employees,id',
        ]);

        $employeeId = $request->input('employee_id');
        if (! $employeeId) {
            $employeeId = \App\Models\Employee::query()->where('user_id', $subscription->created_by)->value('id');
        }

        $subscription->update([
            'sales_employee_id' => $employeeId,
        ]);

        $commission = $commissionService->createSalesCommissionForSubscription($subscription, (int) $subscription->created_by);
        $salesEmployee = $subscription->fresh()->salesEmployee;

        return response()->json([
            'success' => true,
            'sales_employee' => $salesEmployee ? ['id' => $salesEmployee->id, 'name' => $salesEmployee->full_name] : null,
            'commission_updated' => (bool) $commission,
        ]);
    }

    public function addTaskComment(Request $request)
    {
        $request->validate([
            'task_id' => 'required|exists:operations_tasks,id',
            'comment' => 'required|string',
        ]);

        $task = OperationsTask::query()->with(['item.order.subscription.service'])->findOrFail($request->task_id);
        abort_unless($this->userCanOperateOnServiceType($task->item?->order?->subscription?->service?->type, 'update'), 403);

        $comment = OperationsTaskComment::create([
            'task_id' => $request->task_id,
            'user_id' => Auth::id(),
            'comment' => $request->comment,
        ]);

        // Log activity
        OperationsTaskActivity::create([
            'task_id' => $request->task_id,
            'user_id' => Auth::id(),
            'activity_type' => 'comment_added',
            'description' => 'Added a comment',
        ]);

        return response()->json([
            'success' => true,
            'comment' => [
                'id' => $comment->id,
                'user_name' => Auth::user()->name,
                'comment' => $comment->comment,
                'created_at' => $comment->created_at->translatedFormat('Y-m-d h:i A'),
            ],
        ]);
    }

    public function products()
    {
        // Placeholder for products
        return view('operations.products');
    }
}
