<?php

namespace App\Http\Controllers;

use App\Models\ResellerPaymentHistory;
use Illuminate\Http\Request;

class ResellerPaymentHistoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(ResellerPaymentHistory $resellerPaymentHistory)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(ResellerPaymentHistory $resellerPaymentHistory)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, ResellerPaymentHistory $resellerPaymentHistory)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */

    public function destroy(ResellerPaymentHistory $history)
    {
        $payment = $history->resellerPayment;

        $payment->amount_paid -= $history->amount;

        if ($payment->amount_paid < 0) {
            $payment->amount_paid = 0;
        }

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

        $payment->save();

        $history->delete();

        return back()->with('success', 'History pembayaran berhasil dihapus.');
    }
}
