<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bid;
use App\Models\BidHistory;
use App\Models\AuditLog;
use App\Services\Auction\AuctionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class BidAdminController extends Controller
{
    protected AuctionService $auctionService;

    public function __construct(AuctionService $auctionService)
    {
        $this->auctionService = $auctionService;
    }

    public function index(Request $request)
    {
        $query = Bid::with('user.customer', 'auctionVehicle.auctionHouse');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('bid_code', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($uq) use ($search) {
                      $uq->where('name', 'like', "%{$search}%")
                         ->orWhere('phone', 'like', "%{$search}%");
                  })
                  ->orWhereHas('auctionVehicle', function ($vq) use ($search) {
                      $vq->where('lot_number', 'like', "%{$search}%")
                         ->orWhere('model', 'like', "%{$search}%");
                  });
            });
        }

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

        $stats = [
            'total' => Bid::count(),
            'pending' => Bid::where('status', 'pending')->count(),
            'approved' => Bid::where('status', 'approved')->count(),
            'submitted' => Bid::where('status', 'submitted')->count(),
            'won' => Bid::where('status', 'won')->count(),
            'lost' => Bid::where('status', 'lost')->count(),
        ];

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

    public function show(string $id)
    {
        $bid = Bid::with('user.customer', 'auctionVehicle.auctionHouse', 'history.user', 'order.invoices')
            ->findOrFail($id);

        return view('admin.bids.show', compact('bid'));
    }

    public function approveAndSend(Request $request, string $id)
    {
        $bid = Bid::findOrFail($id);
        $notes = $request->input('notes');

        $result = $this->auctionService->approveAndSendToJapan($bid, Auth::user(), $notes);

        if (!$result['success']) {
            return back()->with('error', $result['message']);
        }

        AuditLog::record('admin_approved_bid', $bid, null, ['status' => $bid->fresh()->status]);

        return back()->with('success', 'Bid verified, approved, and dispatched to Japan Live Auction API floor!');
    }

    public function reject(Request $request, string $id)
    {
        $bid = Bid::findOrFail($id);
        $reason = $request->input('reason', 'Bid declined per company verification policy.');

        $bid->update([
            'status' => 'rejected',
            'reviewed_by' => Auth::id(),
            'reviewed_at' => now(),
            'admin_notes' => $reason,
        ]);

        BidHistory::create([
            'bid_id' => $bid->id,
            'user_id' => Auth::id(),
            'action' => 'rejected',
            'from_status' => $bid->getOriginal('status'),
            'to_status' => 'rejected',
            'notes' => $reason,
            'ip_address' => $request->ip(),
        ]);

        AuditLog::record('admin_rejected_bid', $bid);

        return back()->with('success', 'Bid has been marked as rejected.');
    }

    public function markWon(Request $request, string $id)
    {
        $bid = Bid::findOrFail($id);
        $hammerPrice = (float) $request->input('won_hammer_price_jpy', $bid->max_bid_jpy);
        $notes = $request->input('notes');

        $order = $this->auctionService->markBidAsWon($bid, $hammerPrice, $notes);

        AuditLog::record('auction_won_order_created', $order);

        return redirect()->route('admin.orders.show', $order->id)
            ->with('success', "Auction Won! Hammer price ¥" . number_format($hammerPrice, 0) . " recorded and Order #{$order->order_number} created with live import tracking.");
    }

    public function markLost(Request $request, string $id)
    {
        $bid = Bid::findOrFail($id);
        $reason = $request->input('reason', 'Floor hammer price exceeded client maximum ceiling.');

        $this->auctionService->markBidAsLost($bid, $reason);

        AuditLog::record('auction_marked_lost', $bid);

        return back()->with('success', 'Auction vehicle marked as lost. Customer notified.');
    }
}
