<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\OrderCancellationRequest;
use Illuminate\Http\Request;

class OrderCancellationController extends Controller
{
    /**
     * Request cancellation for an entire order.
     */
    public function requestCancelOrder(Request $request, Order $order)
    {
        $validated = $request->validate([
            'reason' => ['required', 'string', 'max:1000'],
        ]);

        // Guard: order must be cancellable
        if (!$order->canBeCancelled()) {
            return redirect()->back()->with('error', 'Order ini tidak dapat dibatalkan.');
        }

        // Guard: no pending request already
        if ($order->hasPendingCancellationRequest()) {
            return redirect()->back()->with('error', 'Sudah ada request pembatalan order yang menunggu approval.');
        }

        $user = $request->user();

        // Create cancellation request
        $cancelRequest = OrderCancellationRequest::create([
            'order_id' => $order->id,
            'order_item_id' => null,
            'type' => OrderCancellationRequest::TYPE_ORDER,
            'requested_by' => $user->id,
            'reason' => $validated['reason'],
            'status' => OrderCancellationRequest::STATUS_PENDING,
        ]);

        // Auto-approve if user is Owner/Developer/SPV
        if ($user->canApproveCancellations()) {
            $cancelRequest->approve($user, 'Auto-approved');
            return redirect()->back()->with('success', 'Order berhasil dibatalkan.');
        }

        return redirect()->back()->with('success', 'Request pembatalan order berhasil dikirim. Menunggu approval dari supervisor.');
    }

    /**
     * Request cancellation for a specific order item.
     */
    public function requestCancelItem(Request $request, OrderItem $orderItem)
    {
        $validated = $request->validate([
            'reason' => ['required', 'string', 'max:1000'],
        ]);

        // Guard: item must be cancellable
        if (!$orderItem->canBeCancelled()) {
            return redirect()->back()->with('error', 'Item ini tidak dapat dibatalkan.');
        }

        // Guard: no pending request already
        if ($orderItem->hasPendingCancellationRequest()) {
            return redirect()->back()->with('error', 'Sudah ada request pembatalan item yang menunggu approval.');
        }

        $user = $request->user();

        // Create cancellation request
        $cancelRequest = OrderCancellationRequest::create([
            'order_id' => $orderItem->order_id,
            'order_item_id' => $orderItem->id,
            'type' => OrderCancellationRequest::TYPE_ITEM,
            'requested_by' => $user->id,
            'reason' => $validated['reason'],
            'status' => OrderCancellationRequest::STATUS_PENDING,
        ]);

        // Auto-approve if user is Owner/Developer/SPV
        if ($user->canApproveCancellations()) {
            $cancelRequest->approve($user, 'Auto-approved');
            return redirect()->back()->with('success', 'Item berhasil dibatalkan.');
        }

        return redirect()->back()->with('success', 'Request pembatalan item berhasil dikirim. Menunggu approval dari supervisor.');
    }

    /**
     * List all cancellation requests (for approval page).
     */
    public function index(Request $request)
    {
        $query = OrderCancellationRequest::with(['order', 'orderItem', 'requester', 'reviewer'])
            ->latest();

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        } else {
            // Default: show pending
            $query->where('status', OrderCancellationRequest::STATUS_PENDING);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->whereHas('order', function ($q) use ($search) {
                $q->where('invoice_number', 'like', "%{$search}%")
                    ->orWhere('customer_name', 'like', "%{$search}%");
            });
        }

        $cancellations = $query->paginate(15)->withQueryString();

        return view('pages.cancellations.index', [
            'title' => 'Approval Pembatalan',
            'cancellations' => $cancellations,
        ]);
    }

    /**
     * Approve a cancellation request.
     */
    public function approve(Request $request, OrderCancellationRequest $cancellationRequest)
    {
        if (!$cancellationRequest->isPending()) {
            return redirect()->back()->with('error', 'Request ini sudah diproses.');
        }

        $cancellationRequest->approve($request->user(), $request->input('notes'));

        return redirect()->back()->with('success', 'Pembatalan berhasil disetujui.');
    }

    /**
     * Reject a cancellation request.
     */
    public function reject(Request $request, OrderCancellationRequest $cancellationRequest)
    {
        $validated = $request->validate([
            'review_notes' => ['required', 'string', 'max:1000'],
        ]);

        if (!$cancellationRequest->isPending()) {
            return redirect()->back()->with('error', 'Request ini sudah diproses.');
        }

        $cancellationRequest->reject($request->user(), $validated['review_notes']);

        return redirect()->back()->with('success', 'Request pembatalan ditolak.');
    }
}
