<?php

namespace App\Http\Controllers;

use App\Models\Balance;
use App\Models\Billpayment;
use App\Models\ReselleBalanceLogReport;
use App\Models\SubResellerBalanceLogReport;
use App\Models\UserAccounting;
use App\Models\Income;
use App\Models\CustomerAccount;
use App\Models\Client;
use App\Models\Clientsinfo;
use App\Models\BankTransfar;
use App\Services\ExpirationService;
use Illuminate\Http\Request;

class PaymentDeleteController extends Controller
{
    public static function deletePayment(Billpayment $payment, $amount, $paid_amount)
    {
        $note = 'Payment Deleted, Balanced adjusted. Payment reference: ' . $payment->id;

            if ($payment->reseller_balance_log_report) {

                $reseller_log = ReselleBalanceLogReport::with('reseller')->find($payment->reseller_balance_log_report);


                $reseller_balance = Balance::where('type', 'reseller')->where('type_id', $reseller_log->reseller->id)->first();

                if($reseller_balance){

                    $reseller_balance->increment('amount', $reseller_log->amount);
                    $reseller_log->amount = 0;
                    $reseller_log->action = $note;
                    $reseller_log->updated_at = now();
                    $reseller_log->save();
                }
            }

            if ($payment->sub_reseller_balance_log_report) {

                $sub_reseller_log = SubResellerBalanceLogReport::with('pop')->find($payment->sub_reseller_balance_log_report);

                $sub_reseller_balance = Balance::where('type', 'pop')->where('type_id', $sub_reseller_log->pop->id)->first();
                $sub_reseller_balance->increment('amount', $sub_reseller_log->amount);

                $sub_reseller_log->amount = 0;
                $sub_reseller_log->action = $note;
                $sub_reseller_log->updated_at = now();
                $sub_reseller_log->save();
            }

            if ($payment->user_accountings_id) {

                $UserAccounting = UserAccounting::find($payment->user_accountings_id);
                $UserAccounting->received_amount = 0;
                $UserAccounting->actions = $note;
                $UserAccounting->save();
            }

            if ($payment->income_id) {

                $income = Income::find($payment->income_id);
                $income->amount = 0;
                $income->description = $note;
                $income->save();

                // Delete associated bank deposit if exists
                // Find bank deposit by payment ID in description
                $bankDeposit = BankTransfar::where('description', 'like', '%Bill Payment [Payment ID:' . $payment->id . ']%')
                    ->whereNotNull('diposit_amount')
                    ->first();

                if ($bankDeposit) {
                    $bankDeposit->delete();
                }
            }

            $customerAccounts = CustomerAccount::where('client_id', $payment->client_id)->first();



            $customerAccounts->decrement('totalPaid', $payment->paid_amount);
            $customerAccounts->decrement('totalDiscount', $payment->discount_amount);
            $customerAccounts->increment('dueAmount', $amount);


            $user_email = "";
            if(auth()->user()->email == "limitedyetfix@gmail.com"){
                $user_email = "system";
            }else{
                $user_email = auth()->user()->email;
            }

            $payment->description = 'Wrong Transaction So Deleted. Payment Amount Was : ' . $payment->paid_amount . ' and Discount Amount was : ' . $payment->discount_amount
                                    . ' deleted by '. $user_email . ' at '. now();

            $payment->paid_amount = 0;
            $payment->reseller_balance_deduct = 0;
            $payment->pop_balance_deduct = 0;
            $payment->money_receipt_number = 'del_' . $payment->money_receipt_number;
            $payment->discount_amount = 0;
            $payment->sub_manager_commission = 0;
            $payment->manager_commission = 0;
            $payment->save();

            $client = Client::find($payment->client_id);
            if ($payment->expire_date_history) {
                $client->expire_date = $payment->expire_date_history;
                if ($payment->expire_date_history < today()->subDay()) {
                    $client->clients_status = 'expired';
                }
            }




            $client->save();

            if(globalPermission('RadiusExpiration')){

                (new ExpirationService())->syncExpiration($client->userid);
            }

            if(isset($payment->income)){
                if ($payment->income->incomeHead == 2) {
                    $clientinfo =  Clientsinfo::where('client_id', $client->id)->first();
                    $clientinfo->otc_due = $clientinfo->otc_due + $paid_amount;
                    $clientinfo->save();
                }
            }

            return $client->id;
    }
}
