<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AuctionVehicle;
use App\Models\AuctionHouse;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;

class AuctionAdminController extends Controller
{
    public function index(Request $request)
    {
        $query = AuctionVehicle::with('auctionHouse', 'bids');

        if ($request->filled('auction_house_id')) {
            $query->where('auction_house_id', $request->auction_house_id);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('lot_number', 'like', "%{$search}%")
                  ->orWhere('chassis_number', 'like', "%{$search}%")
                  ->orWhere('make', 'like', "%{$search}%")
                  ->orWhere('model', 'like', "%{$search}%");
            });
        }

        $vehicles = $query->orderBy('auction_ends_at', 'asc')->paginate(15)->withQueryString();
        $houses = AuctionHouse::where('is_active', true)->get();

        return view('admin.auctions.index', compact('vehicles', 'houses'));
    }

    public function syncNow()
    {
        Artisan::call('auction:sync');
        $output = Artisan::output();

        AuditLog::record('admin_triggered_auction_sync', null, null, ['output' => $output]);

        return back()->with('success', 'Japan Auction sync executed successfully: ' . trim($output));
    }
}
