<?php

namespace App\Http\Controllers\Admin\Finance\Settlement;

use App\Http\Controllers\Controller;
use App\Models\MerchantDispute;
use App\Models\MerchantInvoice;
use App\Models\MerchantPayment;
use App\Models\MerchantDeduction;
use App\Models\User;
use Illuminate\Http\Request;

class DisputeController extends Controller
{
    public function __construct()
    {
        $this->middleware('can:finance.view')->only(['index', 'show']);
        $this->middleware('can:finance.add')->only(['create', 'store']);
        $this->middleware('can:finance.edit')->only(['edit', 'update', 'assign', 'resolve', 'close', 'escalate']);
        $this->middleware('can:finance.delete')->only(['destroy']);
    }
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = MerchantDispute::with('merchant', 'assignedTo');

        // Filter by merchant
        if ($request->has('merchant_id')) {
            $query->where('merchant_id', $request->merchant_id);
        }

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

        // Filter by priority
        if ($request->has('priority')) {
            $query->where('priority', $request->priority);
        }

        // Filter by assigned staff
        if ($request->has('assigned_to')) {
            $query->where('assigned_to', $request->assigned_to);
        }

        $disputes = $query->latest()->paginate(20);
        $merchants = User::where('role', 'seller')->get();
        $staff = User::whereIn('role', ['admin', 'super-admin', 'finance'])->get();

        $stats = [
            'total_open' => MerchantDispute::where('status', 'open')->count(),
            'total_in_review' => MerchantDispute::where('status', 'in_review')->count(),
            'total_urgent' => MerchantDispute::where('priority', 'urgent')->count(),
            'resolved_this_month' => MerchantDispute::where('status', 'resolved')
                ->whereMonth('resolved_at', now()->month)
                ->count(),
        ];

        return view('admin.finance.settlements.disputes.index', compact('disputes', 'merchants', 'staff', 'stats'));
    }
    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $merchants = User::where('role', 'seller')->get();
        return view('admin.finance.settlements.disputes.create', compact('merchants'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'merchant_id' => 'required|exists:users,id',
            'dispute_type' => 'required|string|max:255',
            'description' => 'required|string',
            'disputed_amount' => 'nullable|numeric|min:0',
            'priority' => 'required|in:low,medium,high,urgent',
            'assigned_to' => 'nullable|exists:users,id',
        ]);

        MerchantDispute::create(array_merge($validated, ['status' => 'open']));

        return redirect()->route('finance.settlements.disputes.index')
            ->with('success', 'Dispute created successfully!');
    }

    /**
     * Display the specified resource.
     */
    public function show(MerchantDispute $dispute)
    {
        $dispute->load('merchant', 'invoice', 'payment', 'deduction', 'assignedTo', 'resolvedBy');
        return view('admin.finance.settlements.disputes.show', compact('dispute'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(MerchantDispute $dispute)
    {
        $merchants = User::where('role', 'seller')->get();
        $invoices = MerchantInvoice::all();
        $payments = MerchantPayment::all();
        $deductions = MerchantDeduction::all();
        $staff = User::whereIn('role', ['admin', 'super-admin', 'finance'])->get();

        return view('admin.finance.settlements.disputes.edit', compact(
            'dispute', 'merchants', 'invoices', 'payments', 'deductions', 'staff'
        ));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, MerchantDispute $dispute)
    {
        $validated = $request->validate([
            'merchant_id' => 'required|exists:users,id',
            'invoice_id' => 'nullable|exists:merchant_invoices,id',
            'payment_id' => 'nullable|exists:merchant_payments,id',
            'deduction_id' => 'nullable|exists:merchant_deductions,id',
            'dispute_type' => 'required|in:invoice_amount,payment_delay,deduction_query,service_issue,billing_error,other',
            'subject' => 'required|string|max:255',
            'description' => 'required|string',
            'disputed_amount' => 'nullable|numeric|min:0',
            'priority' => 'required|in:low,medium,high,urgent',
            'status' => 'required|in:open,in_review,resolved,closed,escalated',
            'assigned_to' => 'nullable|exists:users,id',
            'resolution' => 'nullable|string',
        ]);

        $dispute->update($validated);

        return redirect()->route('finance.settlements.disputes.index')
            ->with('success', 'Dispute updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(MerchantDispute $dispute)
    {
        $dispute->delete();

        return redirect()->route('finance.settlements.disputes.index')
            ->with('success', 'Dispute deleted successfully!');
    }

    /**
     * Assign dispute to staff member
     */
    public function assign(Request $request, MerchantDispute $dispute)
    {
        $validated = $request->validate([
            'assigned_to' => 'required|exists:users,id',
        ]);

        $dispute->update([
            'assigned_to' => $validated['assigned_to'],
            'status' => 'in_review',
        ]);

        return back()->with('success', 'Dispute assigned successfully!');
    }

    /**
     * Resolve dispute
     */
    public function resolve(Request $request, MerchantDispute $dispute)
    {
        $validated = $request->validate([
            'resolution' => 'required|string',
        ]);

        $dispute->update([
            'status' => 'resolved',
            'resolution' => $validated['resolution'],
            'resolved_by' => auth()->id(),
            'resolved_at' => now(),
        ]);

        return back()->with('success', 'Dispute resolved successfully!');
    }

    /**
     * Close dispute
     */
    public function close(MerchantDispute $dispute)
    {
        $dispute->update(['status' => 'closed']);

        return back()->with('success', 'Dispute closed!');
    }

    /**
     * Escalate dispute
     */
    public function escalate(MerchantDispute $dispute)
    {
        $dispute->update([
            'status' => 'escalated',
            'priority' => 'urgent',
        ]);

        return back()->with('success', 'Dispute escalated!');
    }
}
