<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Order;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class OrderController extends Controller
{
    public function index(Request $request): Response
    {
        $query = Order::query()
            ->with(['user:id,name,email', 'plan:id,name,service_type,price,billing_cycle']);

        // Search by order number or customer name/email
        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search): void {
                $q->where('order_number', 'like', "%{$search}%")
                    ->orWhereHas('user', function ($uq) use ($search): void {
                        $uq->where('name', 'like', "%{$search}%")
                            ->orWhere('email', 'like', "%{$search}%");
                    });
            });
        }

        // Filter by status
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }

        $orders = $query->latest()->paginate(25)->withQueryString();

        return Inertia::render('Admin/Orders/Index', [
            'orders' => $orders,
            'filters' => [
                'search' => $request->input('search', ''),
                'status' => $request->input('status', ''),
            ],
        ]);
    }

    public function show(Order $order): Response
    {
        $order->load([
            'user:id,name,email,status',
            'plan:id,name,service_type,price,billing_cycle',
            'invoice:id,number,total,status',
            'service:id,hostname,status,ipv4_address',
        ]);

        return Inertia::render('Admin/Orders/Show', [
            'order' => $order,
        ]);
    }

    public function process(Order $order): RedirectResponse
    {
        $order->update(['status' => 'processing']);

        AuditLog::create([
            'user_id' => $order->user_id,
            'admin_id' => auth()->id(),
            'action' => 'process_order',
            'resource_type' => 'order',
            'resource_id' => $order->id,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);

        return redirect()->back()->with('success', "Order {$order->order_number} is now processing.");
    }

    public function complete(Order $order): RedirectResponse
    {
        $order->update([
            'status' => 'completed',
            'completed_at' => now(),
        ]);

        AuditLog::create([
            'user_id' => $order->user_id,
            'admin_id' => auth()->id(),
            'action' => 'complete_order',
            'resource_type' => 'order',
            'resource_id' => $order->id,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);

        return redirect()->back()->with('success', "Order {$order->order_number} has been completed.");
    }

    public function cancel(Order $order): RedirectResponse
    {
        $order->update([
            'status' => 'cancelled',
            'cancelled_at' => now(),
        ]);

        AuditLog::create([
            'user_id' => $order->user_id,
            'admin_id' => auth()->id(),
            'action' => 'cancel_order',
            'resource_type' => 'order',
            'resource_id' => $order->id,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);

        return redirect()->back()->with('success', "Order {$order->order_number} has been cancelled.");
    }

    public function updateNotes(Request $request, Order $order): RedirectResponse
    {
        $validated = $request->validate([
            'admin_notes' => ['nullable', 'string', 'max:1000'],
        ]);

        $order->update(['admin_notes' => $validated['admin_notes']]);

        AuditLog::create([
            'user_id' => $order->user_id,
            'admin_id' => auth()->id(),
            'action' => 'update_order_notes',
            'resource_type' => 'order',
            'resource_id' => $order->id,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);

        return redirect()->back()->with('success', 'Admin notes updated.');
    }
}
