<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    /**
     * Show checkout/payment page
     */
    public function checkout($orderId)
    {
        $order = Order::with(['product.game', 'flashSale'])
            ->where('order_id', $orderId)
            ->firstOrFail();

        // Check if order is expired
        if ($order->isExpired()) {
            $order->update(['status' => 'expired']);
            return redirect()
                ->route('order.status', $orderId)
                ->with('error', 'Pesanan telah kadaluarsa');
        }

        // If already paid, redirect to status
        if ($order->status !== 'pending') {
            return redirect()->route('order.status', $orderId);
        }

        return view('orders.checkout', compact('order'));
    }

    /**
     * Process payment confirmation (for development/manual)
     */
    public function confirmPayment(Request $request, $orderId)
    {
        $order = Order::where('order_id', $orderId)->firstOrFail();

        // Check if can be paid
        if (!$order->canBePaid()) {
            return back()->with('error', 'Pesanan tidak dapat dibayar');
        }

        $validated = $request->validate([
            'payment_method' => 'required|in:manual,qris,ewallet,bank_transfer',
            'payment_proof' => 'nullable|image|max:2048',
        ]);

        $paymentProof = null;
        if ($request->hasFile('payment_proof')) {
            $paymentProof = $request->file('payment_proof')->store('payment-proofs', 'public');
        }

        // Mark as paid (in development mode, auto-process)
        $order->markAsPaid($validated['payment_method'], $paymentProof);

        // Auto complete for development
        if (config('app.env') === 'local' || config('app.debug')) {
            $order->markAsProcessing();
            // Simulate processing delay
            $order->markAsCompleted();
        }

        return redirect()
            ->route('order.status', $orderId)
            ->with('success', 'Pembayaran berhasil dikonfirmasi!');
    }

    /**
     * Show order status/tracking page
     */
    public function status($orderId)
    {
        $order = Order::with(['product.game', 'flashSale'])
            ->where('order_id', $orderId)
            ->firstOrFail();

        // Update expired status if needed
        if ($order->isExpired() && $order->status === 'pending') {
            $order->update(['status' => 'expired']);
        }

        return view('orders.status', compact('order'));
    }

    /**
     * Track order by order ID (search form)
     */
    public function track(Request $request)
    {
        $orderId = $request->get('order_id');

        if ($orderId) {
            $order = Order::where('order_id', $orderId)->first();

            if ($order) {
                return redirect()->route('order.status', $order->order_id);
            }

            return back()->with('error', 'Order ID tidak ditemukan');
        }

        return view('orders.track');
    }

    /**
     * API: Get order status (for AJAX)
     */
    public function getStatus($orderId)
    {
        $order = Order::where('order_id', $orderId)->first();

        if (!$order) {
            return response()->json(['error' => 'Order not found'], 404);
        }

        // Update expired status if needed
        if ($order->isExpired() && $order->status === 'pending') {
            $order->update(['status' => 'expired']);
        }

        return response()->json([
            'order_id' => $order->order_id,
            'status' => $order->status,
            'status_label' => $order->getStatusLabel(),
            'status_class' => $order->getStatusClass(),
            'can_be_paid' => $order->canBePaid(),
            'time_remaining' => $order->getPaymentTimeRemaining(),
        ]);
    }
}
