<?php

namespace App\Http\Controllers\Api\Admin;

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

class CustomerController extends Controller
{
    /**
     * List all customers.
     */
    public function index(Request $request)
    {
        $query = Customer::query();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        // Sort
        $sortField = $request->get('sort', 'created_at');
        $sortDirection = $request->get('direction', 'desc');
        $allowedSorts = ['created_at', 'name', 'total_orders', 'total_spent', 'last_order_at'];
        if (in_array($sortField, $allowedSorts)) {
            $query->orderBy($sortField, $sortDirection === 'asc' ? 'asc' : 'desc');
        }

        return response()->json($query->paginate($request->get('per_page', 20)));
    }

    /**
     * Show single customer.
     */
    public function show(Customer $customer)
    {
        $customer->loadCount(['orders', 'wishlists', 'reviews']);

        return response()->json(['data' => $customer]);
    }

    /**
     * Customer's orders.
     */
    public function orders(Request $request, Customer $customer)
    {
        $orders = $customer->orders()
            ->with(['items.product.images'])
            ->orderBy('created_at', 'desc')
            ->paginate($request->get('per_page', 10));

        return response()->json($orders);
    }

    /**
     * Customer statistics.
     */
    public function stats(Customer $customer)
    {
        $ordersByStatus = $customer->orders()
            ->select('status', DB::raw('COUNT(*) as count'), DB::raw('SUM(total) as total'))
            ->groupBy('status')
            ->get();

        $monthlySpending = $customer->orders()
            ->where('status', '!=', 'cancelled')
            ->where('created_at', '>=', now()->subMonths(12))
            ->select(
                DB::raw('YEAR(created_at) as year'),
                DB::raw('MONTH(created_at) as month'),
                DB::raw('SUM(total) as total'),
                DB::raw('COUNT(*) as orders_count')
            )
            ->groupBy('year', 'month')
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

        $topProducts = DB::table('order_items')
            ->join('orders', 'order_items.order_id', '=', 'orders.id')
            ->where('orders.customer_id', $customer->id)
            ->where('orders.status', '!=', 'cancelled')
            ->select(
                'order_items.product_name_ar',
                'order_items.product_name_en',
                DB::raw('SUM(order_items.quantity) as total_quantity'),
                DB::raw('SUM(order_items.total) as total_spent')
            )
            ->groupBy('order_items.product_name_ar', 'order_items.product_name_en')
            ->orderBy('total_spent', 'desc')
            ->limit(10)
            ->get();

        return response()->json([
            'data' => [
                'total_orders' => $customer->total_orders,
                'total_spent' => $customer->total_spent,
                'last_order_at' => $customer->last_order_at,
                'orders_by_status' => $ordersByStatus,
                'monthly_spending' => $monthlySpending,
                'top_products' => $topProducts,
            ],
        ]);
    }
}
