<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PassengerExtraServiceRequest;
use App\Services\PromotionalWheelService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class PassengerExtraServiceRequestController extends Controller
{
    public function index(): View
    {
        $requests = PassengerExtraServiceRequest::query()
            ->with(['user', 'service'])
            ->orderByDesc('created_at')
            ->paginate(40);

        return view('admin.passenger_extra_service_requests.index', compact('requests'));
    }

    public function updateStatus(Request $request, int $id): RedirectResponse
    {
        $request->validate([
            'status' => 'required|in:pending,confirmed,completed,cancelled',
            'admin_notes' => 'nullable|string|max:2000',
        ]);

        $row = PassengerExtraServiceRequest::findOrFail($id);
        $old = $row->status;
        $new = $request->string('status')->toString();

        $row->admin_notes = $request->input('admin_notes', $row->admin_notes);
        $row->status = $new;

        if ($new === 'completed' && $old !== 'completed') {
            $row->completed_at = now();
        }
        if ($new !== 'completed') {
            $row->completed_at = null;
        }

        $row->save();

        if ($new === 'completed' && $old !== 'completed') {
            try {
                $fee = (float) ($row->fee_snapshot ?? 0);
                PromotionalWheelService::onOrderCompleted('extra_service', (int) $row->id, $fee);
            } catch (\Throwable $e) {
                \Log::error('PromotionalWheelService extra_service: '.$e->getMessage());
            }
        }

        return redirect()->route('admin.passenger-extra-service-requests.index')
            ->with('success', 'تم تحديث حالة الطلب');
    }
}
