<?php

namespace App\Http\Controllers\Verifier;

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

class DeliveryController extends Controller
{
    public function index(Request $request)
    {
        $query = Order::with(['seller.user', 'user', 'items.product']);
        
        if ($request->status === 'pending') {
            $query->where('delivery_proof_status', 'submitted');
        } elseif ($request->status === 'approved') {
            $query->where('delivery_proof_status', 'approved');
        } elseif ($request->status === 'rejected') {
            $query->where('delivery_proof_status', 'rejected');
        } else {
            $query->whereNotNull('delivery_proof');
        }
        
        $orders = $query->orderByRaw("CASE 
            WHEN delivery_proof_status = 'submitted' THEN 1 
            WHEN delivery_proof_status = 'rejected' THEN 2 
            ELSE 3 END")
            ->orderBy('delivery_proof_submitted_at', 'desc')
            ->paginate(20);
        
        return view('verifier.delivery.index', compact('orders'));
    }

    public function show(Order $order)
    {
        $order->load(['seller.user', 'user', 'items.product', 'dispute', 'deliveryConfirmedBy']);
        
        return view('verifier.delivery.show', compact('order'));
    }

    public function confirmDelivery(Order $order)
    {
        $order->update([
            'status' => 'delivered',
            'delivered_at' => now(),
            'delivery_proof_status' => 'approved',
            'delivery_confirmed_at' => now(),
            'delivery_confirmed_by' => auth()->id(),
        ]);
        
        return back()->with('success', 'Livraison confirmee. Le paiement sera libere au vendeur.');
    }

    public function rejectProof(Request $request, Order $order)
    {
        $request->validate([
            'reason' => 'required|string|max:500',
        ]);
        
        $order->update([
            'delivery_proof_status' => 'rejected',
            'delivery_proof_notes' => $request->reason,
        ]);
        
        return back()->with('success', 'Preuve de livraison rejetee. Le vendeur doit en soumettre une nouvelle.');
    }

    public function flagIssue(Request $request, Order $order)
    {
        $request->validate([
            'issue' => 'required|string|max:500',
        ]);
        
        $order->update([
            'delivery_proof_notes' => 'SIGNALE: ' . $request->issue,
        ]);
        
        return back()->with('success', 'Probleme signale a l\'administrateur.');
    }
}
