<?php

namespace App\Http\Controllers;

use App\Models\Shop;
use App\Models\Payment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{
    /**
     * List all payments (Collections)
     */
    public function index(Request $request)
    {
        $query = Payment::with(['shop:id,name,city', 'distributor:id,name']);
        return response()->json($query->latest()->paginate($request->get('per_page', 10)));
    }

    /**
     * Collect payment from a shop to reduce due balance.
     */
    public function collectPayment(Request $request)
    {
        $request->validate([
            'shop_id' => 'required|exists:shops,id',
            'amount' => 'required|numeric|min:0.01',
            'payment_mode' => 'required|in:Cash,UPI,Bank Transfer',
            'notes' => 'nullable|string',
        ]);

        return DB::transaction(function () use ($request) {
            $shop = Shop::findOrFail($request->shop_id);
            $distributorId = auth()->id() ?? 1;

            // 1. Log Payment
            $payment = Payment::create([
                'shop_id' => $shop->id,
                'distributor_id' => $distributorId,
                'amount_paid' => $request->amount,
                'payment_mode' => $request->payment_mode,
                'notes' => $request->notes,
                'payment_date' => now(),
            ]);

            // 2. Reduce Shop Due
            $shop->reduceDue($request->amount);

            // 3. Notify Admins
            $distributorName = auth()->user()->name ?? 'Distributor';
            $admins = \App\Models\User::where('role', 'admin')->get();
            if ($admins->isEmpty()) {
                $admins = \App\Models\User::where('id', 1)->get(); // Fallback in case role is empty
            }
            \Illuminate\Support\Facades\Notification::send($admins, new \App\Notifications\PaymentCollected($payment, $distributorName, $shop->name, $shop->fresh()->due_balance));

            return response()->json([
                'message' => 'Payment collected successfully',
                'payment' => [
                    'id' => $payment->id,
                    'amount_paid' => $payment->amount_paid,
                    'payment_mode' => $payment->payment_mode,
                    'payment_date' => $payment->payment_date,
                    'new_due_balance' => $shop->fresh()->due_balance,
                    'old_due_balance' => $shop->fresh()->due_balance + $request->amount,
                ],
                'shop' => $shop->fresh()
            ]);
        });
    }

    /**
     * Get payment history for a shop.
     */
    public function getShopPaymentHistory($id)
    {
        $payments = Payment::where('shop_id', $id)->orderBy('payment_date', 'desc')->get();
        return response()->json($payments);
    }
}
