<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class AdminOrderController extends Controller
{
    /**
     * Display listing of customer orders with filtering, search, and pagination.
     */
    public function index(Request $request)
    {
        if (!Schema::hasTable('orders')) {
            session()->now('error', "Database table 'orders' does not exist yet. Please run 'php artisan migrate' in your terminal.");

            return view('admin.orders.index', [
                'orders' => new \Illuminate\Pagination\LengthAwarePaginator([], 0, 10),
                'totalOrders' => 0,
                'pendingOrders' => 0,
                'processingOrders' => 0,
                'shippedOrders' => 0,
                'deliveredOrders' => 0,
                'cancelledOrders' => 0,
            ]);
        }

        $query = Order::with('items');

        // Search Keyword (Order Number, Customer Name, Email, Phone)
        if ($request->filled('search')) {
            $search = trim($request->input('search'));
            $query->where(function ($q) use ($search) {
                $q->where('order_number', 'like', "%{$search}%")
                  ->orWhere('customer_name', 'like', "%{$search}%")
                  ->orWhere('customer_email', 'like', "%{$search}%")
                  ->orWhere('customer_phone', 'like', "%{$search}%");
            });
        }

        // Order Status Filter
        if ($request->filled('order_status')) {
            $query->where('order_status', $request->input('order_status'));
        }

        // Payment Status Filter
        if ($request->filled('payment_status')) {
            $query->where('payment_status', $request->input('payment_status'));
        }

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

        // Real Summary Metrics
        $totalOrders = Order::count();
        $pendingOrders = Order::where('order_status', 'pending')->count();
        $processingOrders = Order::where('order_status', 'processing')->count();
        $shippedOrders = Order::where('order_status', 'shipped')->count();
        $deliveredOrders = Order::where('order_status', 'delivered')->count();
        $cancelledOrders = Order::where('order_status', 'cancelled')->count();

        return view('admin.orders.index', compact(
            'orders',
            'totalOrders',
            'pendingOrders',
            'processingOrders',
            'shippedOrders',
            'deliveredOrders',
            'cancelledOrders'
        ));
    }

    /**
     * Display detailed order view.
     */
    public function show(Order $order)
    {
        $order->load(['items.product']);
        return view('admin.orders.show', compact('order'));
    }

    /**
     * Update order and payment status.
     */
    public function updateStatus(Request $request, Order $order)
    {
        $request->validate([
            'order_status' => ['required', 'in:pending,processing,shipped,delivered,cancelled'],
            'payment_status' => ['required', 'in:pending,paid,failed,refunded'],
        ]);

        $order->update([
            'order_status' => $request->input('order_status'),
            'payment_status' => $request->input('payment_status'),
        ]);

        return back()->with('success', "Order #{$order->order_number} status updated successfully.");
    }

    /**
     * Delete order record.
     */
    public function destroy(Order $order)
    {
        $orderNumber = $order->order_number;
        $order->delete();

        return redirect()->route('admin.orders.index')
            ->with('success', "Order #{$orderNumber} deleted successfully.");
    }
}
