<?php

namespace App\Http\Controllers\ResellerClient;

use App\Http\Controllers\Controller;
use App\Jobs\ResellerClientBillPaymentSyncJob;
use App\Models\ResellerBillGenerate;
use App\Models\ResellerClientBillPayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ResellerClientPaymentController extends Controller
{
    public function deletePayment($id)
    {
        try {
            DB::transaction(function () use ($id) {
                $payment = ResellerClientBillPayment::findOrFail($id);
                $client = $payment->client;

                // Delete the payment
                $payment->delete();

                // Dispatch job to recalculate balance
                ResellerClientBillPaymentSyncJob::dispatch($client->id);
            });

            return redirect()->back()->with('success', 'Payment deleted successfully');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to delete payment: ' . $e->getMessage());
        }
    }

    public function deleteBill($id)
    {
        try {
            DB::transaction(function () use ($id) {
                $bill = ResellerBillGenerate::findOrFail($id);
                $client = $bill->client;

                // Delete the bill
                $bill->delete();

                // Dispatch job to recalculate balance
                ResellerClientBillPaymentSyncJob::dispatch($client->id);
            });

            return redirect()->back()->with('success', 'Bill deleted successfully');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to delete bill: ' . $e->getMessage());
        }
    }
}
