<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Dispute;
use App\Models\DisputeMessage;
use App\Models\Order;
use App\Services\NotificationService;
use Illuminate\Support\Facades\DB;

class DisputeController extends Controller
{
    public function index(Request $request)
    {
        $query = Dispute::where('user_id', auth()->id())->with(['order']);

        if ($request->filled('status')) {
            $query->where('status', $request->input('status'));
        }
        if ($request->filled('type')) {
            $query->where('type', $request->input('type'));
        }
        if ($request->filled('from')) {
            $query->whereDate('created_at', '>=', $request->input('from'));
        }
        if ($request->filled('to')) {
            $query->whereDate('created_at', '<=', $request->input('to'));
        }
        if ($request->filled('q')) {
            $search = $request->input('q');
            $query->where(function ($q) use ($search) {
                $q->where('subject', 'like', "%{$search}%")
                    ->orWhere('ticket_number', 'like', "%{$search}%")
                    ->orWhere('order_id', 'like', "%{$search}%");
            });
        }

        $query->orderBy('created_at', 'desc');

        if ($request->input('export') === 'csv') {
            $rows = $query->get();
            return response()->streamDownload(function () use ($rows) {
                $out = fopen('php://output', 'w');
                fputcsv($out, ['ID', 'Ticket', 'Sujet', 'Commande', 'Type', 'Statut', 'Date']);
                foreach ($rows as $d) {
                    fputcsv($out, [
                        $d->id,
                        $d->ticket_number,
                        $d->subject,
                        $d->order_id,
                        $d->type,
                        $d->status,
                        optional($d->created_at)->format('d/m/Y H:i'),
                    ]);
                }
                fclose($out);
            }, 'litiges.csv', ['Content-Type' => 'text/csv']);
        }

        if ($request->input('export') === 'pdf') {
            $rows = $query->get();
            $html = view('exports.disputes', compact('rows'))->render();
            return response($html)
                ->header('Content-Type', 'text/html')
                ->header('Content-Disposition', 'attachment; filename="litiges.html"');
        }
        
        $disputes = $query->paginate(15);
        
        return view('member.disputes.index', compact('disputes'));
    }

    public function create()
    {
        $orders = Order::where('user_id', auth()->id())
            ->where('status', 'delivered')
            ->orderBy('created_at', 'desc')
            ->get();
        
        return view('member.disputes.create', compact('orders'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'order_id' => 'required|exists:orders,id',
            'subject' => 'required|string|max:255',
            'description' => 'required|string',
            'type' => 'required|in:product_issue,delivery_issue,refund_request,fraud,other',
        ]);

        $order = Order::where('id', $request->order_id)
            ->where('user_id', auth()->id())
            ->first();
        
        if (!$order) {
            return back()->with('error', 'Cette commande ne vous appartient pas.');
        }

        $dispute = Dispute::create([
            'user_id' => auth()->id(),
            'order_id' => $request->order_id,
            'subject' => $request->subject,
            'description' => $request->description,
            'type' => $request->type,
            'status' => 'open',
            'priority' => 'medium',
        ]);

        // Notification de création de litige
        NotificationService::disputeCreated(auth()->id(), $dispute->ticket_number ?? 'TKT-'.$dispute->id, $request->subject);

        return redirect()->route('member.disputes.show', $dispute)
            ->with('success', 'Litige créé avec succès');
    }

    public function show(Dispute $dispute)
    {
        if ($dispute->user_id !== auth()->id()) {
            abort(403);
        }
        
        $dispute->load(['order', 'messages', 'assignedTo']);
        
        return view('member.disputes.show', compact('dispute'));
    }

    public function addMessage(Request $request, Dispute $dispute)
    {
        if ($dispute->user_id !== auth()->id()) {
            abort(403);
        }

        $request->validate([
            'message' => 'required|string',
        ]);

        DisputeMessage::create([
            'dispute_id' => $dispute->id,
            'user_id' => auth()->id(),
            'message' => $request->message,
            'is_admin' => false,
        ]);

        return back()->with('success', 'Message envoyé');
    }
}
