<?php

namespace App\Http\Controllers\Admin;

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

class AdminCustomerController extends Controller
{
    /**
     * Display a listing of customer records based on order history.
     */
    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.customers.index', [
                'customers' => new \Illuminate\Pagination\LengthAwarePaginator([], 0, 10),
                'totalCustomersCount' => 0,
            ]);
        }

        $query = Order::select(
            'customer_name',
            'customer_email',
            'customer_phone',
            DB::raw('COUNT(id) as total_orders'),
            DB::raw('SUM(total_amount) as total_spent'),
            DB::raw('MAX(created_at) as last_order_date')
        )->groupBy('customer_phone', 'customer_name', 'customer_email');

        if ($request->filled('search')) {
            $search = trim($request->input('search'));
            $query->where(function ($q) use ($search) {
                $q->where('customer_name', 'like', "%{$search}%")
                  ->orWhere('customer_email', 'like', "%{$search}%")
                  ->orWhere('customer_phone', 'like', "%{$search}%");
            });
        }

        $customers = $query->orderBy('last_order_date', 'desc')->paginate(10)->withQueryString();
        $totalCustomersCount = Order::distinct('customer_phone')->count('customer_phone');

        return view('admin.customers.index', compact('customers', 'totalCustomersCount'));
    }
}
