<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{
    public function index()
    {
        $orders = Order::with(['user', 'product'])->latest()->paginate(15);
        return view('admin.orders.index', compact('orders'));
    }

    public function show(Order $order)
    {
        $order->load(['user', 'product', 'paymentProof']);
        return view('admin.orders.show', compact('order'));
    }

    public function update(Request $request, Order $order)
    {
        $validated = $request->validate([
            'status' => 'required|in:pending,paid,cancelled',
        ]);

        $order->status = $validated['status'];
        
        if ($validated['status'] === 'paid' && !$order->paid_at) {
            $order->paid_at = now();
        } elseif ($validated['status'] !== 'paid') {
            $order->paid_at = null;
        }

        $order->save();

        return back()->with('success', 'Status pesanan berhasil diperbarui menjadi ' . strtoupper($validated['status']));
    }

    public function destroy(Order $order)
    {
        if ($order->status === 'paid') {
            return back()->with('error', 'Pesanan yang sudah lunas tidak dapat dihapus.');
        }

        $order->delete();
        return redirect()->route('admin.orders.index')->with('success', 'Pesanan berhasil dihapus.');
    }
}
