<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Car;
use App\Models\CarOrder;
use App\Models\Wdmethod;
use App\Models\Settings;
use App\Traits\TemplateTrait;
use App\Traits\NotificationTrait;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class CarCheckoutController extends Controller
{
    use TemplateTrait, NotificationTrait;

    /**
     * Show checkout form
     */
    public function checkout(Car $car)
    {
        if ($car->status !== 'available' || $car->quantity < 1) {
            return redirect()->route('cars.index')
                ->with('error', 'This car is no longer available.');
        }

        $paymentMethods = Wdmethod::where('status', 'enabled')->get();
        $user = Auth::user();
        $settings = Settings::where('id', 1)->first();

        return view('user.cars.checkout', compact('car', 'paymentMethods', 'user', 'settings'))
            ->with('title', 'Checkout - ' . $car->name);
    }

    /**
     * Place order — creates order then redirects to payment page
     */
    public function placeOrder(Request $request, Car $car)
    {
        $validator = Validator::make($request->all(), [
            'billing_name' => 'required|string|max:255',
            'billing_email' => 'required|email|max:255',
            'billing_phone' => 'nullable|string|max:50',
            'billing_company' => 'nullable|string|max:255',
            'billing_address' => 'required|string|max:500',
            'billing_city' => 'required|string|max:255',
            'billing_state' => 'nullable|string|max:255',
            'billing_postal_code' => 'nullable|string|max:20',
            'billing_country' => 'required|string|max:255',
            'payment_method' => 'required|string|max:255',
            'quantity' => 'nullable|integer|min:1',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // Check availability
        $quantity = $request->quantity ?? 1;
        if ($car->status !== 'available' || $car->quantity < $quantity) {
            return redirect()->back()->with('error', 'Insufficient stock for this vehicle.');
        }

        // Create order (no payment proof yet — that comes on the payment page)
        $order = CarOrder::create([
            'user_id' => Auth::id(),
            'car_id' => $car->id,
            'quantity' => $quantity,
            'unit_price' => $car->price,
            'amount' => $car->price * $quantity,
            'total_price' => $car->price * $quantity,
            'status' => 'pending',
            'payment_method' => $request->payment_method,
            'payment_status' => 'pending',
            'billing_name' => $request->billing_name,
            'billing_email' => $request->billing_email,
            'billing_phone' => $request->billing_phone,
            'billing_company' => $request->billing_company,
            'billing_address' => $request->billing_address,
            'billing_city' => $request->billing_city,
            'billing_state' => $request->billing_state,
            'billing_postal_code' => $request->billing_postal_code,
            'billing_country' => $request->billing_country,
        ]);

        // Decrement car quantity
        $car->decrementQuantity($quantity);

        // Notify admin
        $this->sendDirectAdminNotification(
            1,
            'New Car Order',
            "New car order #{$order->order_number} placed by " . Auth::user()->name . " for {$car->name}.",
            'info',
            $order->id,
            'car_order'
        );

        // Redirect to payment page to show payment details + proof upload
        return redirect()->route('cars.payment', $order->id)
            ->with('success', 'Order created! Now complete your payment below.');
    }

    /**
     * Show payment details page (like deposit payment page)
     */
    public function payment(CarOrder $order)
    {
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $order->load(['car.photos']);
        $payment_mode = Wdmethod::where('name', $order->payment_method)->first();

        if (!$payment_mode) {
            return redirect()->route('cars.order-details', $order->id)
                ->with('error', 'Payment method not found.');
        }

        return view('user.cars.car-payment', compact('order', 'payment_mode'))
            ->with('title', 'Complete Payment - Order #' . $order->order_number);
    }

    /**
     * Save payment proof for an order
     */
    public function savePaymentProof(Request $request, CarOrder $order)
    {
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $validator = Validator::make($request->all(), [
            'payment_proof' => 'required|image|mimes:jpeg,png,jpg,gif,webp|max:5120',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        // Handle payment proof upload
        $dir = public_path('dash/car-payments');
        if (!\File::isDirectory($dir)) {
            \File::makeDirectory($dir, 0755, true);
        }
        $filename = uniqid() . '.' . $request->file('payment_proof')->getClientOriginalExtension();
        $request->file('payment_proof')->move($dir, $filename);

        $order->update([
            'payment_proof' => 'car-payments/' . $filename,
        ]);

        return redirect()->route('cars.order-details', $order->id)
            ->with('success', 'Payment proof uploaded successfully! Your order #' . $order->order_number . ' is being reviewed.');
    }

    /**
     * List user's car orders
     */
    public function myOrders()
    {
        $orders = CarOrder::forUser(Auth::id())
            ->with(['car.photos'])
            ->orderBy('created_at', 'desc')
            ->get();

        return view('user.cars.my-orders', compact('orders'))
            ->with('title', 'My Car Orders');
    }

    /**
     * View single order details
     */
    public function orderDetails(CarOrder $order)
    {
        // Ensure user can only see their own orders
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $order->load(['car.photos']);

        return view('user.cars.order-details', compact('order'))
            ->with('title', 'Order #' . $order->order_number);
    }

    /**
     * Generate printable HTML invoice
     */
    public function downloadInvoice(CarOrder $order)
    {
        if ($order->user_id !== Auth::id()) {
            abort(403);
        }

        $order->load(['car.photos', 'user']);
        $settings = Settings::where('id', 1)->first();

        return view('user.cars.invoice', compact('order', 'settings'))
            ->with('title', 'Invoice - ' . $order->order_number);
    }
}
