<?php

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

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

class PaymentController extends Controller
{
    public function __construct()
    {
        $this->middleware('can:finance.view')->only(['index', 'show', 'pendingReport']);
        $this->middleware('can:finance.add')->only(['create', 'store']);
        $this->middleware('can:finance.edit')->only(['edit', 'update', 'approve', 'reject']);
        $this->middleware('can:finance.delete')->only(['destroy']);
    }
    public function index(Request $request)
    {
        $query = \App\Models\MerchantPayment::with('merchant');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('merchant_id')) {
            $query->where('merchant_id', $request->merchant_id);
        }
        if ($request->filled('start_date')) {
            $query->whereDate('payment_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('payment_date', '<=', $request->end_date);
        }

        $payments = $query->latest()->paginate(15);
        $merchants = \App\Models\User::where('role', 'seller')->get();

        $stats = [
            'total_pending' => \App\Models\MerchantPayment::where('status', 'pending')->sum('amount'),
            'total_completed' => \App\Models\MerchantPayment::where('status', 'completed')->sum('amount'),
            'total_today' => \App\Models\MerchantPayment::whereDate('payment_date', today())->sum('amount'),
            'count_pending' => \App\Models\MerchantPayment::where('status', 'pending')->count(),
        ];

        return view('admin.finance.settlements.payments.index', compact('payments', 'merchants', 'stats'));
    }

    public function create()
    {
        $merchants = User::where('role', 'seller')->get();
        $pendingInvoices = MerchantInvoice::whereIn('status', ['sent', 'overdue'])->get();
        return view('admin.finance.settlements.payments.create', compact('merchants', 'pendingInvoices'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'merchant_id' => 'required|exists:users,id',
            'amount' => 'required|numeric|min:0',
            'payment_date' => 'required|date',
            'payment_method' => 'required|in:bank_transfer,cash,cheque,online',
            'reference_number' => 'nullable|string|max:255|unique:merchant_payments,reference_number',
            'notes' => 'nullable|string',
        ]);

        \App\Models\MerchantPayment::create(array_merge($validated, [
            'payment_number' => 'PAY-' . time(),
            'status' => 'pending',
        ]));

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

    public function show(MerchantPayment $payment)
    {
        $payment->load('merchant');
        return view('admin.finance.settlements.payments.show', compact('payment'));
    }

    public function edit(MerchantPayment $payment)
    {
        $merchants = User::where('role', 'merchant')->get();
        return view('admin.finance.settlements.payments.edit', compact('payment', 'merchants'));
    }

    public function update(Request $request, MerchantPayment $payment)
    {
        $validated = $request->validate([
            'merchant_id' => 'required|exists:users,id',
            'amount' => 'required|numeric|min:0',
            'payment_date' => 'required|date',
            'payment_method' => 'required|in:bank_transfer,cash,cheque,online',
            'reference_number' => 'nullable|string|max:255|unique:merchant_payments,reference_number,' . $payment->id,
            'status' => 'required|in:pending,completed,failed,cancelled',
            'notes' => 'nullable|string',
        ]);

        $payment->update($validated);

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

    public function destroy(MerchantPayment $payment)
    {
        $payment->delete();

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

    public function approve(MerchantPayment $payment)
    {
        $payment->update(['status' => 'completed']);

        return back()->with('success', 'Payment approved successfully!');
    }

    public function reject(MerchantPayment $payment)
    {
        $payment->update(['status' => 'failed']);

        return back()->with('success', 'Payment rejected!');
    }

    public function pendingReport()
    {
        $pendingInvoices = MerchantInvoice::where('status', '!=', 'paid')->with('merchant')->get();
        $pendingPayments = MerchantPayment::where('status', 'pending')->with('merchant')->get();

        $stats = [
            'total_pending_invoices' => $pendingInvoices->sum('total_amount'),
            'total_pending_payments' => $pendingPayments->sum('amount'),
            'overdue_invoices' => MerchantInvoice::where('status', 'overdue')->count(),
            'pending_count' => $pendingInvoices->count(),
        ];

        return view('admin.finance.settlements.pending-report', compact('pendingInvoices', 'pendingPayments', 'stats'));
    }
}
