<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use App\Models\Bid;
use App\Models\BidHistory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class BidController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();
        $query = Bid::with('auctionVehicle.auctionHouse')
            ->where('user_id', $user->id);

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

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

        return view('customer.bids', compact('bids'));
    }

    public function show(string $id)
    {
        $bid = Bid::with('auctionVehicle.auctionHouse', 'history.user', 'order')
            ->where('user_id', Auth::id())
            ->where('id', $id)
            ->firstOrFail();

        return view('customer.bid-show', compact('bid'));
    }

    public function cancel(string $id)
    {
        $bid = Bid::where('user_id', Auth::id())
            ->where('id', $id)
            ->where('status', 'pending')
            ->firstOrFail();

        $bid->update(['status' => 'cancelled']);

        BidHistory::create([
            'bid_id' => $bid->id,
            'user_id' => Auth::id(),
            'action' => 'cancelled_by_customer',
            'from_status' => 'pending',
            'to_status' => 'cancelled',
            'notes' => 'Customer cancelled bid authorization prior to admin approval.',
            'ip_address' => request()->ip(),
        ]);

        return back()->with('success', 'Your bid authorization has been cancelled.');
    }
}
