<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Models\AuditLog;
use Illuminate\Http\Request;

class CustomerAdminController extends Controller
{
    public function index(Request $request)
    {
        $query = Customer::with('user');

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

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $customers = $query->orderBy('created_at', 'desc')->paginate(15)->withQueryString();

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

    public function show(string $id)
    {
        $customer = Customer::with([
            'user',
            'bids.auctionVehicle.auctionHouse',
            'orders.statusHistory',
            'orders.invoices.payments',
        ])->findOrFail($id);

        return view('admin.customers.show', compact('customer'));
    }

    public function updateNotes(Request $request, string $id)
    {
        $customer = Customer::findOrFail($id);
        $customer->update(['internal_notes' => $request->input('internal_notes')]);

        AuditLog::record('admin_updated_customer_notes', $customer);

        return back()->with('success', 'Internal customer CRM notes saved.');
    }

    public function updateStatus(Request $request, string $id)
    {
        $customer = Customer::findOrFail($id);
        $customer->update(['status' => $request->input('status')]);

        AuditLog::record('admin_updated_customer_status', $customer);

        return back()->with('success', 'Customer status updated.');
    }
}
