<?php

namespace App\Http\Controllers\Admin;

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

class OrderController extends Controller
{
    /**
     * Display order list
     */
    public function index(Request $request)
    {
        $query = Order::with(['product.game', 'flashSale']);

        // Filter by status
        if ($request->has('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        // Search by order ID or WhatsApp
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q
                    ->where('order_id', 'like', "%{$search}%")
                    ->orWhere('whatsapp', 'like', "%{$search}%")
                    ->orWhere('game_user_id', 'like', "%{$search}%");
            });
        }

        $orders = $query->orderBy('created_at', 'desc')->paginate(20);

        // Get counts for tabs
        $counts = [
            'all' => Order::count(),
            'pending' => Order::where('status', 'pending')->count(),
            'paid' => Order::where('status', 'paid')->count(),
            'processing' => Order::where('status', 'processing')->count(),
            'completed' => Order::where('status', 'completed')->count(),
            'failed' => Order::whereIn('status', ['failed', 'expired', 'refunded'])->count(),
        ];

        return view('admin.orders.index', compact('orders', 'counts'));
    }

    /**
     * Show order detail
     */
    public function show(Order $order)
    {
        $order->load(['product.game', 'flashSale']);
        return view('admin.orders.show', compact('order'));
    }

    /**
     * Update order status
     */
    public function updateStatus(Request $request, Order $order)
    {
        $validated = $request->validate([
            'status' => 'required|in:pending,paid,processing,completed,failed,refunded,expired',
            'admin_notes' => 'nullable|string|max:1000',
        ]);

        $order->update([
            'status' => $validated['status'],
            'admin_notes' => $validated['admin_notes'] ?? $order->admin_notes,
        ]);

        // Update timestamps based on status
        if ($validated['status'] === 'paid' && !$order->paid_at) {
            $order->update(['paid_at' => now()]);
        }
        if ($validated['status'] === 'completed' && !$order->completed_at) {
            $order->update(['completed_at' => now()]);
        }

        return back()->with('success', 'Status pesanan berhasil diupdate');
    }

    /**
     * Bulk update orders
     */
    public function bulkUpdate(Request $request)
    {
        $validated = $request->validate([
            'order_ids' => 'required|array',
            'order_ids.*' => 'exists:orders,id',
            'action' => 'required|in:mark_paid,mark_processing,mark_completed,mark_failed',
        ]);

        $statusMap = [
            'mark_paid' => 'paid',
            'mark_processing' => 'processing',
            'mark_completed' => 'completed',
            'mark_failed' => 'failed',
        ];

        $status = $statusMap[$validated['action']];
        $count = 0;

        foreach ($validated['order_ids'] as $orderId) {
            $order = Order::find($orderId);
            if ($order) {
                $order->update(['status' => $status]);

                if ($status === 'paid' && !$order->paid_at) {
                    $order->update(['paid_at' => now()]);
                }
                if ($status === 'completed' && !$order->completed_at) {
                    $order->update(['completed_at' => now()]);
                }

                $count++;
            }
        }

        return back()->with('success', "{$count} pesanan berhasil diupdate");
    }

    /**
     * Delete order
     */
    public function destroy(Order $order)
    {
        $order->delete();
        return redirect()->route('admin.orders.index')->with('success', 'Pesanan berhasil dihapus');
    }
}
