<?php

namespace App\Http\Controllers;

use App\Models\ResellerPayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ResellerPaymentController extends Controller
{
    public function index(Request $request)
    {
        $status = $request->status ?? 'pending';

        $query = ResellerPayment::with('reseller', 'resellerOrder');

        if ($status !== 'all') {
            $query->where('status', $status);
        }

        $payments = $query->get();

        $headers = ['Reseller', 'Order', 'Total Tagihan', 'Terbayar', 'Sisa', 'Status', 'Aksi'];

        $rows = $payments->map(function ($p) {
            $remaining = $p->amount_due - $p->amount_paid;
            return [
                'cols' => [
                    $p->reseller->name ?? '-',
                    $p->resellerOrder->invoice_number ?? '-',
                    'Rp ' . number_format($p->amount_due, 0, ',', '.'),
                    'Rp ' . number_format($p->amount_paid, 0, ',', '.'),
                    'Rp ' . number_format($remaining, 0, ',', '.'),
                    ucfirst($p->status),
                ],
                'actions' => view('components.action-button', [
                    'id' => $p->id,
                    'resource' => 'reseller-payments'
                ])->render(),
            ];
        });

        return view('reseller_payments.index', compact('headers', 'rows', 'status'));
    }

    public function create()
    {
        abort(404);
    }

    public function store(Request $request)
    {
        abort(404);
    }

    public function show(ResellerPayment $resellerPayment)
    {
        $resellerPayment->load('reseller', 'resellerOrder', 'histories');

        $remaining = $resellerPayment->amount_due - $resellerPayment->amount_paid;

        return view('reseller_payments.show', compact('resellerPayment', 'remaining'));
    }

    public function edit(ResellerPayment $resellerPayment)
    {
        $resellerPayment->load('reseller', 'resellerOrder');

        $remaining = $resellerPayment->amount_due - $resellerPayment->amount_paid;

        return view('reseller_payments.edit', compact('resellerPayment', 'remaining'));
    }

    public function update(Request $request, ResellerPayment $resellerPayment)
    {
        $request->validate([
            'amount' => 'required|numeric|min:1',
            'payment_date' => 'required|date',
        ]);

        $remaining = $resellerPayment->amount_due - $resellerPayment->amount_paid;

        $paymentAmount = min($request->input('amount'), $remaining);

        DB::transaction(function() use ($resellerPayment, $paymentAmount, $request) {

            $resellerPayment->histories()->create([
                'amount' => $paymentAmount,
                'payment_date' => $request->input('payment_date'),
            ]);

            $resellerPayment->amount_paid += $paymentAmount;

            $resellerPayment->status = $resellerPayment->amount_paid >= $resellerPayment->amount_due
                ? 'paid'
                : 'pending';

            $resellerPayment->save();
        });

        return redirect()->route('reseller-payments.show', $resellerPayment->id)
            ->with('success', 'Pembayaran berhasil dicatat.');
    }

    public function destroy(ResellerPayment $resellerPayment)
    {
        $resellerPayment->delete();

        return redirect()->route('reseller-payments.index')
            ->with('success', 'Pembayaran dihapus.');
    }
}
