middleware('client'); } public function index($requestUniqueId = null) { $user_id = auth()->guard('client')->user()->id; $get_card_lists = Card::where('user_id', $user_id)->where('browser_type', 2)->orderBy('id', 'DESC')->get(); $query = CreditCardBillRequest::where('retailer_id', $user_id) ->where('credit_card_bill_requests.request_card_unique_id', $requestUniqueId) ->whereNotNull('credit_card_bill_requests.card_id') // Ensure card_id is not NULL ->join('cards', 'cards.id', '=', 'credit_card_bill_requests.card_id') // Ensure related Card exists ->join('customers', 'customers.id', '=', 'credit_card_bill_requests.customer_id') ->selectRaw('credit_card_bill_requests.request_card_unique_id, MAX(credit_card_bill_requests.id) as id,MAX(credit_card_bill_requests.created_at) as created_at,MAX(credit_card_bill_requests.status) as status,SUM(credit_card_bill_requests.due_amount) as total_due_amount,COUNT(*) as total_records,customers.customer_name as customer_name') ->groupBy( 'credit_card_bill_requests.request_card_unique_id', 'customers.customer_name', ) ->orderByDesc('created_at'); $CreditCardBillRequest = $query->get(); Session::put('header_title', "Customer Pay Request Details"); return view('retailer.payRequest.index', compact('get_card_lists', 'CreditCardBillRequest', 'requestUniqueId')); } // New method for grouped customer pay request list public function customerPayRequestList() { Session::put('header_title', "Customer Pay Request List"); $user_id = auth()->guard('client')->user()->id; $staffs = Staff::where('retailer_id', $user_id)->get(); return view('retailer.payRequest.list', compact('staffs')); } public function customerPayRequestListAjax(Request $request) { $draw = $request->get('draw'); $start = $request->get("start"); $limit = $request->get("length"); $columnIndex_arr = $request->get('order'); $columnName_arr = $request->get('columns'); $order_arr = $request->get('order'); $search = $request->get('search') ?? $request->get('search.value'); $columnIndex = $columnIndex_arr[0]['column']; $order = $columnName_arr[$columnIndex]['data']; $dir = $order_arr[0]['dir']; if ($order == "action") { $order = 'created_at'; } $user_id = auth()->guard('client')->user()->id; $filter_from = $request->input('filter_from'); $filter_to = $request->input('filter_to'); // Query grouped by request_card_unique_id $query = CreditCardBillRequest::where('retailer_id', $user_id) ->whereNotNull('credit_card_bill_requests.request_card_unique_id') ->whereNotNull('credit_card_bill_requests.card_id') ->join('customers', 'customers.id', '=', 'credit_card_bill_requests.customer_id') ->selectRaw(' credit_card_bill_requests.request_card_unique_id, MAX(credit_card_bill_requests.id) as id, MAX(credit_card_bill_requests.created_at) as created_at, MAX(credit_card_bill_requests.status) as status, SUM(credit_card_bill_requests.due_amount) as total_due_amount, SUM(credit_card_bill_requests.calculated_amount_card_charge) as total_card_charges, SUM(credit_card_bill_requests.status) as total_status, COUNT(*) as total_records, customers.customer_name as customer_name, customers.customer_last_name as customer_last_name, customers.customer_mobile_number as customer_mobile_number, MAX(credit_card_bill_requests.staff_id) as staff_id ') ->groupBy( 'credit_card_bill_requests.request_card_unique_id', 'customers.customer_name', 'customers.customer_last_name', 'customers.customer_mobile_number' ); if (!empty($filter_from) && !empty($filter_to)) { $query->whereBetween(DB::raw('DATE(credit_card_bill_requests.created_at)'), [$filter_from, $filter_to]); } if (!empty($search)) { $query->where(function ($query) use ($search) { $query->where('customers.customer_name', 'LIKE', "%{$search}%") ->orWhere('customers.customer_last_name', 'LIKE', "%{$search}%") ->orWhere('customers.customer_mobile_number', 'LIKE', "%{$search}%") ->orWhere('credit_card_bill_requests.request_card_unique_id', 'LIKE', "%{$search}%") ->orWhereRaw("CONCAT(customers.customer_name, ' ', COALESCE(customers.customer_last_name, '')) LIKE ?", ["%{$search}%"]); }); } $totalData = CreditCardBillRequest::where('retailer_id', $user_id) ->whereNotNull('request_card_unique_id') ->distinct('request_card_unique_id') ->count('request_card_unique_id'); $totalFiltered = $query->get()->count(); // Fetch all filtered records (without pagination) to calculate pending amounts $allValues = $query->orderBy('created_at', 'desc')->get(); // Calculate pending amount for each record $processedData = []; foreach ($allValues as $value) { // Get all bill requests for this card $cardBillRequests = CreditCardBillRequest::where('request_card_unique_id', $value->request_card_unique_id) ->orderByDesc('id') ->get(['id', 'due_amount', 'calculated_amount_card_charge']); $billIds = $cardBillRequests->pluck('id'); // Get debit totals per bill $debitTotals = CreditCardPayout::whereIn('credit_card_bill_request_id', $billIds) ->where('transaction_type', 'Debit') ->where('retailer_id', $user_id) ->where('status', 1) ->selectRaw('credit_card_bill_request_id, SUM(pay_amount) as total') ->groupBy('credit_card_bill_request_id') ->pluck('total', 'credit_card_bill_request_id'); // Get credit totals per bill $creditTotals = CreditCardPayout::whereIn('credit_card_bill_request_id', $billIds) ->where('transaction_type', 'Credit') ->where('retailer_id', $user_id) ->where('status', 1) ->selectRaw('credit_card_bill_request_id, SUM(pay_amount) as total') ->groupBy('credit_card_bill_request_id') ->pluck('total', 'credit_card_bill_request_id'); // Get card charge payments per bill $chargeTotals = CardChargePay::whereIn('credit_card_bill_requests_id', $billIds) ->where('status', 1) ->selectRaw('credit_card_bill_requests_id, SUM(card_charge_pay_amount) as total') ->groupBy('credit_card_bill_requests_id') ->pluck('total', 'credit_card_bill_requests_id'); // Calculate totals for this card $total_amount = 0; $total_pay_amount_with_charge = 0; $pending_amount = 0; foreach ($cardBillRequests as $bill) { $dueAmount = $bill->due_amount; $chargeAmount = $bill->calculated_amount_card_charge; $totalCcBillCharge = $dueAmount + $chargeAmount; $total_amount += $totalCcBillCharge; $debitPaid = $debitTotals[$bill->id] ?? 0; $creditPaid = $creditTotals[$bill->id] ?? 0; $chargePaid = $chargeTotals[$bill->id] ?? 0; // Same logic as getAmountData $paid = $debitPaid - $creditPaid; if ($paid <= 0) { $totalPaid = abs($debitPaid + $chargePaid); } else { $totalPaid = $chargePaid; } $billPending = $totalCcBillCharge - $totalPaid; $total_pay_amount_with_charge += $totalPaid; $pending_amount += $billPending; } // Auto-update status: If pending is 0, mark all card entries as PAID (status = 1) if ($pending_amount <= 0 && $total_amount > 0 && $value->status == 0) { CreditCardBillRequest::where('request_card_unique_id', $value->request_card_unique_id) ->where('retailer_id', $user_id) ->update(['status' => 1]); } // Store the record with calculated pending amount $processedData[] = [ 'value' => $value, 'pending_amount' => $pending_amount, 'total_pay_amount_with_charge' => $total_pay_amount_with_charge, 'total_amount' => $total_amount ]; } // Sort by pending_amount descending usort($processedData, function ($a, $b) { return $b['pending_amount'] <=> $a['pending_amount']; }); // Apply pagination $paginatedData = array_slice($processedData, $start, $limit); $data = array(); if (!empty($paginatedData)) { $staffs = Staff::where('retailer_id', $user_id)->get(); $i = $start + 1; foreach ($paginatedData as $item) { $value = $item['value']; $pending_amount = $item['pending_amount']; // Status determination if ($value->total_records == $value->total_status) { $statusLabel = "Paid"; $statusColor = 'text-success'; } else { $statusLabel = "Unpaid"; $statusColor = 'text-danger'; } $mainData['id'] = $i; $mainData['customer_name'] = $value->customer_name . ' ' . ($value->customer_last_name ? $value->customer_last_name : ''); $mainData['customer_mobile'] = $value->customer_mobile_number; $mainData['request_card_unique_id'] = $value->request_card_unique_id; $mainData['total_records'] = $value->total_records; $mainData['total_due_amount'] = number_format($value->total_due_amount, 2); $mainData['total_card_charges'] = number_format($value->total_card_charges, 2); $mainData['pending_amount'] = '' . number_format($pending_amount, 2) . ''; $mainData['amount_to_be_collected_status'] = '' . $statusLabel . ''; $mainData['created_at'] = Carbon::parse($value->created_at)->format('d-m-Y'); $mainData['created_at'] = Carbon::parse($value->created_at)->format('d-m-Y'); $staffDropdown = ''; $mainData['staff_assign'] = $staffDropdown; $mainData['action'] = ''; $mainData['action'] .= 'View Details  '; $mainData['action'] .= 'Download Invoice'; $data[] = $mainData; $i++; } } $json_data = array( "draw" => intval($request->input('draw')), "recordsTotal" => intval($totalData), "recordsFiltered" => intval($totalFiltered), "data" => $data ); echo json_encode($json_data); } public function customerPayRequest(Request $request) { $userId = auth()->guard('client')->user()->id; $draw = (int) $request->input('draw'); $start = (int) $request->input('start', 0); $limit = (int) $request->input('length', 25); $search = $request->input('search.value') ?? $request->input('search'); $filterFrom = $request->input('filter_from'); $filterTo = $request->input('filter_to'); $query = CreditCardBillRequest::with(['customer', 'card']) ->where('retailer_id', $userId); if ($filterFrom && $filterTo) { $query->whereBetween(DB::raw('DATE(created_at)'), [$filterFrom, $filterTo]); } if (!empty($search)) { $query->where(function ($q) use ($search) { $q->where('created_at', 'like', "%{$search}%") ->orWhere('due_amount', 'like', "%{$search}%") ->orWhereHas('customer', function ($q) use ($search) { $q->where('customer_name', 'like', "%{$search}%"); }) ->orWhereHas('card', function ($q) use ($search) { $q->where('card_number', 'like', "%{$search}%") ->orWhere('name_on_card', 'like', "%{$search}%") ->orWhere('network_type', 'like', "%{$search}%") ->orWhere('bank_name', 'like', "%{$search}%"); }); }); } if ($request->filled('customer_id')) { $query->where('request_card_unique_id', $request->customer_id); } $totalData = (clone $query)->count(); $totalFiltered = $totalData; $records = $query ->orderBy('id', 'DESC') ->offset($start) ->limit($limit) ->get(); $billIds = $records->pluck('id'); $paidChargeAmounts = CardChargePay::whereIn('credit_card_bill_requests_id', $billIds) ->where('status', '!=', 2) ->selectRaw('credit_card_bill_requests_id, SUM(card_charge_pay_amount) as total_paid') ->groupBy('credit_card_bill_requests_id') ->pluck('total_paid', 'credit_card_bill_requests_id'); $creditPayoutAmounts = CreditCardPayout::whereIn('credit_card_bill_request_id', $billIds) ->where('status', 1) ->where('transaction_type', 'Credit') ->selectRaw('credit_card_bill_request_id, SUM(pay_amount) as total_paid') ->groupBy('credit_card_bill_request_id') ->pluck('total_paid', 'credit_card_bill_request_id'); $debitPayoutAmounts = CreditCardPayout::whereIn('credit_card_bill_request_id', $billIds) ->where('status', 1) ->where('transaction_type', 'Debit') ->selectRaw('credit_card_bill_request_id, SUM(pay_amount) as total_paid') ->groupBy('credit_card_bill_request_id') ->pluck('total_paid', 'credit_card_bill_request_id'); $data = []; $i = $start + 1; foreach ($records as $row) { $totalPaidAmount = ($debitPayoutAmounts[$row->id] ?? 0) - ($creditPayoutAmounts[$row->id] ?? 0); $totalCardChargeAmount = $row->calculated_amount_card_charge; $dueAmount = $row->totalCardChargeAmount; $paidAmount = $paidChargeAmounts[$row->id] ?? 0; $remainingAmount = $totalCardChargeAmount - $paidAmount; // Calculate total card charge payments for this bill $totalChargePaid = CardChargePay::where('request_card_unique_id', $row->request_card_unique_id) ->where('status', 1) // Only count paid charges ->where(function ($query) use ($row) { $query->whereRaw('FIND_IN_SET(?, credit_card_bill_requests_id)', [$row->id]); }) ->sum('card_charge_pay_amount'); // Determine charge status based on payment vs required amount if (isset($creditPayoutAmounts[$row->id]) && isset($debitPayoutAmounts[$row->id]) && $totalPaidAmount <= 0) { $dueStatus = 'Paid'; } elseif (isset($creditPayoutAmounts[$row->id]) && isset($debitPayoutAmounts[$row->id]) && $totalPaidAmount > 0) { $dueStatus = 'Partial'; } else { $dueStatus = 'Unpaid'; } // Determine charge status based on payment vs required amount if ($totalChargePaid >= $row->calculated_amount_card_charge) { $chargeStatus = 'Paid'; } elseif ($totalChargePaid > 0) { $chargeStatus = 'Partial'; } else { $chargeStatus = 'Unpaid'; } $card = $row->card; $action = ' Pay Bill Charge History '; if ($remainingAmount > 0) { $action .= ' Pay Card Charge '; } $data[] = [ 'id' => $i++, 'card_type' => $card?->network_type ?? '', 'card_name' => $card?->name_on_card ?? '', 'card_number' => $card ? 'xxxx-xxxx-xxxx-' . substr($card->card_number, -4) : '', 'bank_name' => $card?->bank_name ?? '', 'due_amount' => $row->due_amount, 'deposite_amount' => $debitPayoutAmounts[$row->id] ?? "-", 'withdraw_amount' => $creditPayoutAmounts[$row->id] ?? "-", 'due_amount_status' => $dueStatus, 'card_charge_amount' => $row->calculated_amount_card_charge, 'card_charge_status' => $chargeStatus, 'created_at' => Carbon::parse($row->created_at)->format('d-m-Y'), 'action' => $action ]; } return response()->json([ 'draw' => $draw, 'recordsTotal' => $totalData, 'recordsFiltered' => $totalFiltered, 'data' => $data ]); } public function creditCardCharge() { Session::put('header_title', "Credit Card Charge List"); $user_id = auth()->guard('client')->user()->id; $Customer = Customer::where('status', 1)->whereNull('member_parent_id')->where('user_id', $user_id)->orderBy('id', 'DESC')->get(); return view('retailer.credit_card_charge.index', compact('Customer')); } public function creditCardChargeAjax(Request $request) { $draw = $request->get('draw'); $start = $request->get("start"); $limit = $request->get("length"); $columnIndex_arr = $request->get('order'); $columnName_arr = $request->get('columns'); $order_arr = $request->get('order'); $search_arr = $request->get('search'); $columnIndex = $columnIndex_arr[0]['column']; $order = $columnName_arr[$columnIndex]['data']; $dir = $order_arr[0]['dir']; if ($order == "action") { $order = 'credit_card_bill_requests.id'; } $id = auth()->guard('client')->user()->id; // $id = auth()->user()->user_id; $filter_name = $request->input('filter_name'); $filter_card_number = $request->input('filter_card_number'); $filter_status = $request->input('filter_status'); $filter_from = $request->input('filter_from'); $filter_to = $request->input('filter_to'); $customer_id = $request->input('customer_id'); $query = CreditCardBillRequest::where('retailer_id', $id); if (!empty($search_arr['value'])) { $search = $search_arr['value']; $query->where(function ($query) use ($search) { $query->where('due_amount', 'LIKE', "%{$search}%") ->orWhere('due_amount', 'LIKE', "%{$search}%") ->orWhere('created_at', 'LIKE', "%{$search}%"); }); } if ($customer_id) { $query->where('customer_id', $customer_id); } $totalData = $query->count(); $totalFiltered = $totalData; $query->selectRaw('request_card_unique_id, MAX(id) as id, MAX(created_at) as created_at,MAX(status) as status, SUM(due_amount) as total_due_amount, COUNT(*) as total_records') ->groupBy('request_card_unique_id'); $query->offset($start)->limit($limit)->orderBy($order, $dir); $values = $query->get(); $data = array(); if (!empty($values)) { $i = $start + 1; foreach ($values as $value) { $user_id = auth()->guard('client')->user(); $requestData = CreditCardBillRequest::where('request_card_unique_id', $value->request_card_unique_id)->where('retailer_id', $user_id->id)->with('card')->get(); $totalCharges = $requestData->sum('calculated_amount_card_charge'); $card_charge_pay = CardChargePay::where('request_card_unique_id', $value->request_card_unique_id)->get(); $card_charge_pay_amount = $card_charge_pay->sum('card_charge_pay_amount') ?? 0; // dump($totalCharges, $card_charge_pay_amount); $currentStatus = $value->status; $encryptedValueId = encrypt($value->request_card_unique_id); $dropdown = ''; $statusLabel = \App\Enums\CardChargePayStatus::label($value->status); $statusColor = ''; switch ($value->status) { case \App\Enums\CardChargePayStatus::PROCESSING: $statusColor = 'text-primary'; // Blue break; case \App\Enums\CardChargePayStatus::PAID: $statusColor = 'text-success'; // Green break; case \App\Enums\CardChargePayStatus::UNPAID: $statusColor = 'text-danger'; // Red break; case \App\Enums\CardChargePayStatus::PARTIAL_PAID: $statusColor = 'text-warning'; // Yellow break; default: $statusColor = 'text-secondary'; // Gray (default) break; } $walletData['id'] = $i; $walletData['request_card_unique_id'] = $value->request_card_unique_id; $walletData['total_records'] = $value->total_records; $walletData['status'] = '' . $statusLabel . ''; $walletData['status_change'] = $dropdown; $walletData['created_at'] = $value->created_at->format('d-m-y'); $walletData['action'] = ''; $walletData['action'] .= 'View Request  '; $walletData['action'] .= 'Download Invoice  '; if ($totalCharges !== $card_charge_pay_amount) { $walletData['action'] .= 'Pay Card Charge  '; } $data[] = $walletData; $i++; } } $json_data = array( "draw" => intval($request->input('draw')), "recordsTotal" => intval($totalData), "recordsFiltered" => intval($totalFiltered), "data" => $data ); echo json_encode($json_data); } public function creditCardChangeStatus(Request $request) { $validated = $request->validate([ 'credit_card_request' => 'required|integer|exists:credit_card_bill_requests,request_card_unique_id', 'status' => 'required|in:' . implode(',', [ CardChargePayStatus::UNPAID, CardChargePayStatus::PROCESSING, CardChargePayStatus::PAID, CardChargePayStatus::PARTIAL_PAID ]) ]); $CreditCardBillRequests = CreditCardBillRequest::where('request_card_unique_id', $validated['credit_card_request'])->get(); $CardChargePays = CardChargePay::where('request_card_unique_id', $validated['credit_card_request'])->get(); // Update status for CreditCardBillRequest foreach ($CreditCardBillRequests as $CreditCardBillRequest) { $CreditCardBillRequest->status = $validated['status']; $CreditCardBillRequest->save(); } // Update status for CardChargePay foreach ($CardChargePays as $CardChargePay) { $CardChargePay->status = $validated['status']; $CardChargePay->save(); } return response()->json([ 'message' => 'Status updated successfully!' ]); } public function requestDetails(Request $request) { $decryptedId = decrypt($request->decrypt_id); $retailer = auth()->guard('client')->user(); $cardBillRequest = CreditCardBillRequest::where('id', $decryptedId) ->where('retailer_id', $retailer->id) ->with('card', 'customer') ->first(); $debitAmount = CreditCardPayout::where('credit_card_bill_request_id', $decryptedId) ->where('transaction_type', 'Debit') ->where('retailer_id', auth()->guard('client')->user()->id) ->where('status', 1) ->sum('pay_amount'); $creditAmount = CreditCardPayout::where('credit_card_bill_request_id', $decryptedId) ->where('transaction_type', 'Credit') ->where('retailer_id', auth()->guard('client')->user()->id) //->where('status', 1) ->sum('pay_amount'); $paidChargeAmount = CardChargePay::where('credit_card_bill_requests_id', $decryptedId) ->where('status', '!=', 2) ->sum('card_charge_pay_amount'); // Get payment methods for online withdraw $pgservicetypes = PgServicesType::where('status', 1)->whereHas('paymentGateway', function ($query) { $query->where('payment_type', 'online'); })->get(); // Get payment modes for offline transactions $paymentModes = CustomerPaymentMode::where('user_id', $retailer->id) ->where('status', 1) ->get(); $view = view('retailer.payRequest.credit_card_pay_bill', compact('cardBillRequest', 'debitAmount', 'creditAmount', 'paidChargeAmount', 'pgservicetypes', 'paymentModes'))->render(); return response()->json([ 'view' => $view ]); } public function generateCreditCardBillPayment(Request $request) { $validator = Validator::make($request->all(), [ 'card_id' => 'required|integer|exists:cards,id', 'mobile' => 'required|digits:10', 'card_number' => 'required|digits_between:3,19', 'amount' => 'required|numeric|min:0', 'web_bill_payment_charges' => 'required|numeric|min:0', 'credit_card_bill_request_id' => 'required|integer|exists:credit_card_bill_requests,id', 'payout_provider' => 'required', 'remarks' => 'nullable|string|max:500', ]); if ($validator->fails()) { return response()->json([ 'response_code' => 0, 'message' => 'Validation error', 'errors' => $validator->errors(), ]); } $wallet_balance = auth()->guard('client')->user()->wallet_balance; $id = auth()->guard('client')->user()->id; $mobile_number = auth()->guard('client')->user()->mobile_number; $card_id = $request->card_id; $get_cards = Card::where('id', $card_id)->first(); $name = $get_cards->name_on_card; $card_number = $get_cards->card_number; $network = $get_cards->network; $mobile = $request->mobile; $amount = $request->amount; $ifsc_code = $request->ifsc_code; $pay_amount = $request->pay_amount; $transaction_mode = $request->transaction_mode; $payout_provider = $request->input('payout_provider'); $web_bill_payment_charges = $request->web_bill_payment_charges; $card_percentage_charges = $request->card_percentage_charges; $remarks = $request->remarks; $credit_card_bill_request_id = $request->credit_card_bill_request_id; if ($pay_amount >= $wallet_balance) { echo json_encode(['response_code' => 0, 'message' => 'Your wallet balance is not greater than bill amount.']); die; } $ref_id = 'C-' . $id . '-' . date("Ymdhis") . time(); $transaction_id = sha1(md5(time())); $is_rental_payout_service = config('setting.is_rental_payout_service'); $credit_card_bill_service = config('setting.credit_card_bill_service'); $is_credit_card_bill_service = config('setting.is_credit_card_bill_service'); $formatted_date = Carbon::now()->subMinutes(5)->format('Y-m-d H:i:s'); if ($credit_card_bill_service == "Instantpay" && $is_credit_card_bill_service == 1 && $payout_provider == "credit_card") { $get_bill_paymnet_duplicate_check = CreditCardPayout::where('retailer_id', $id)->where('amount', $amount)->where('card_number', $card_number)->where('created_at', '>=', $formatted_date)->first(); if ($get_bill_paymnet_duplicate_check) { echo json_encode(['response_code' => 0, 'message' => 'This amount and account number have already been paid out. Please wait for 5 minutes before attempting another transfer with the same account and amount.']); die; } $retailer_transuction_id = CreditCardPayout::insertGetId(['retailer_id' => $id, 'card_id' => $card_id, 'credit_card_bill_request_id' => $credit_card_bill_request_id, 'type' => $payout_provider, 'refid' => $ref_id, 'name' => $name, 'mobile' => $mobile, 'card_number' => $card_number, 'amount' => $pay_amount, 'pay_amount' => $amount, 'service_charges' => $web_bill_payment_charges, 'card_charges' => $card_percentage_charges, 'remarks' => $remarks, 'network' => $network, 'transaction_mode' => $transaction_mode, 'network' => $network, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), 'status' => 0, 'browser_type' => 2, 'payout_api' => $credit_card_bill_service]); $client = Client::whereId($id)->first(); $wallet_amount = $client->wallet_balance - $amount; Client::whereId($id)->update(['wallet_balance' => $wallet_amount]); $last_retailer_wallet_id = RetailerWallet::insertGetId(['retailer_id' => $id, 'mihpayid' => $ref_id, 'topay_transuction_id' => $transaction_id, 'amount' => $amount, 'received_amount' => $amount, 'mode' => 'Debit', 'payment_mode' => 'Online', 'is_status' => 1, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), 'remarks' => 'Credit card bill payment', 'payment_api' => $credit_card_bill_service, 'retailer_transuction_id' => $retailer_transuction_id, 'transuction_type' => "Credit Card Bill Payment"]); $get_insatnt_pay_account = InsatntPayAccount::where('status', 1)->first(); if ($get_insatnt_pay_account) { $pay_profile_id = $get_insatnt_pay_account->profile_id; $pay_account_num = $get_insatnt_pay_account->account_number; } else { $pay_profile_id = 25266529310; $pay_account_num = "084163400004448"; } $encryptionKey = '3077725f6fdf7be73077725f6fdf7be7'; $ivlen = openssl_cipher_iv_length('aes-256-cbc'); $iv = openssl_random_pseudo_bytes($ivlen); $ciphertext = openssl_encrypt($card_number, 'aes-256-cbc', $encryptionKey, OPENSSL_RAW_DATA, $iv); $encryptedNumber = base64_encode($iv . $ciphertext); $instantpay_client_id = config('setting.instantpay_client_id'); $instantpay_client_secret = config('setting.instantpay_client_secret'); $server_ip_address = config('setting.server_ip_address'); $curl = curl_init(); $url = config('setting.instantpay_url') . "/payments/payout"; curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => '{ "payer" : { "bankProfileId" : "0", "bankIfsc" : "9327282729" }, "payee" : { "name" : "' . $name . '", "accountNumber" : "' . $encryptedNumber . '" }, "transferMode" : "CREDITCARD", "transferAmount" : "' . $amount . '", "externalRef" : "' . $ref_id . '", "latitude" : "20.3636", "longitude" : "78.6528", "remarks" : "Credit Card BILL", "alertEmail" : "" }', CURLOPT_HTTPHEADER => array( 'X-Ipay-Auth-Code: 1', 'X-Ipay-Client-Id: ' . $instantpay_client_id . '', 'X-Ipay-Client-Secret: ' . $instantpay_client_secret . '', 'X-Ipay-Endpoint-Ip: ' . $server_ip_address . '', 'Content-Type: application/json' ), )); $response = curl_exec($curl); curl_close($curl); $res = json_decode($response); if ($res->statuscode == 'TXN') { CreditCardPayout::where('id', $retailer_transuction_id)->update([ 'status' => 1, 'response' => trim($response), 'updated_at' => date('Y-m-d h:i:s'), ]); RetailerWallet::where('id', $last_retailer_wallet_id)->update([ 'is_pay' => 1, 'updated_at' => date('Y-m-d h:i:s'), ]); $sms_text = "Topay Your transaction " . $amount . " is successful. For details or assistance, contact support. Thank you for using our services!"; Helper::sendSmsMessages($sms_text, $mobile_number); // Manage payment status $CreditCardPayout = CreditCardPayout::where('status', 1)->where('card_id', $card_id)->where('credit_card_bill_request_id', $credit_card_bill_request_id)->sum('pay_amount'); $originalBill = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->value('due_amount'); if ($CreditCardPayout > 0 && $CreditCardPayout < $originalBill) { // Partial payment made, set status to PARTIAL_PAID $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PARTIAL_PAID]); } elseif ($CreditCardPayout == $originalBill) { // Full payment made, set status to PAID $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PAID]); } else { // Processing payment, e.g., amount being verified $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PROCESSING]); } echo json_encode(['response_code' => 1, 'message' => $res->status, 'payment_api' => $credit_card_bill_service, 'ref_id' => $ref_id]); die; } else if ($res->statuscode == 'TUP') { CreditCardPayout::where('id', $retailer_transuction_id)->update([ 'status' => 1, 'response' => trim($response), 'updated_at' => date('Y-m-d h:i:s'), ]); echo json_encode(['response_code' => 0, 'payment_api' => $credit_card_bill_service, 'message' => $res->status]); die; } else { CreditCardPayout::where('id', $retailer_transuction_id)->update([ 'status' => 1, 'response' => trim($response), 'updated_at' => date('Y-m-d h:i:s'), ]); echo json_encode(['response_code' => 0, 'payment_api' => $credit_card_bill_service, 'message' => $res->status]); die; } echo json_encode(['response_code' => 0, 'payment_api' => $credit_card_bill_service, 'message' => $res->status]); die; } if ($payout_provider == "rental" && $is_rental_payout_service == 1) { $get_rental_payout_duplicate_check = CreditCardPayout::where('retailer_id', $id)->where('amount', $amount)->where('card_number', $card_number)->where('created_at', '>=', $formatted_date)->first(); if ($get_rental_payout_duplicate_check) { return response()->json(['status' => 'error', 'msg' => 'This amount and bank account have already been paid out. Please wait for 5 minutes before attempting another transfer with the same account and amount.']); } $retailer_transuction_id = CreditCardPayout::insertGetId(['retailer_id' => $id, 'card_id' => $card_id, 'credit_card_bill_request_id' => $credit_card_bill_request_id, 'refid' => $ref_id, 'name' => $name, 'mobile' => $mobile, 'card_number' => $card_number, 'amount' => $pay_amount, 'pay_amount' => $amount, 'service_charges' => $web_bill_payment_charges, 'card_charges' => $card_percentage_charges, 'remarks' => $remarks, 'network' => $network, 'type' => $payout_provider, 'transaction_mode' => $transaction_mode, 'network' => $network, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), 'status' => 0, 'browser_type' => 2, 'payout_api' => $credit_card_bill_service]); $client = Client::whereId($id)->first(); $wallet_amount = $client->wallet_balance - $amount; Client::whereId($id)->update(['wallet_balance' => $wallet_amount]); $last_retailer_wallet_id = RetailerWallet::insertGetId(['retailer_id' => $id, 'mihpayid' => $ref_id, 'topay_transuction_id' => $transaction_id, 'amount' => $amount, 'received_amount' => $amount, 'mode' => 'Debit', 'payment_mode' => 'Online', 'is_status' => 1, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), 'remarks' => 'Credit card bill payment', 'payment_api' => $credit_card_bill_service, 'retailer_transuction_id' => $retailer_transuction_id, 'transuction_type' => "Credit Card Bill Payment"]); $instantpay_client_id = config('setting.instantpay_client_id'); $instantpay_client_secret = config('setting.instantpay_client_secret'); $server_ip_address = config('setting.server_ip_address'); $get_insatnt_pay_account = InsatntPayAccount::where('status', 0)->first(); if ($get_insatnt_pay_account) { $pay_profile_id = $get_insatnt_pay_account->profile_id; $pay_account_num = $get_insatnt_pay_account->account_number; } else { $pay_profile_id = 25266529310; $pay_account_num = "084163400004448"; } $curl = curl_init(); $url = config('setting.instantpay_url') . "/payments/payout"; curl_setopt_array($curl, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => '', CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 0, CURLOPT_FOLLOWLOCATION => true, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => '{ "payer" : { "bankProfileId" : "' . $pay_profile_id . '", "accountNumber" : "' . $pay_account_num . '" }, "payee" : { "name" : "' . $name . '", "accountNumber" : "' . $card_number . '", "bankIfsc" : "' . $ifsc_code . '" }, "transferMode" : "' . $transaction_mode . '", "transferAmount" : "' . $amount . '", "externalRef" : "' . $ref_id . '", "latitude" : "20.5936", "longitude" : "78.9628", "remarks" : "KAV PAYMENT SERVICE PRIVATE LIMITED", "alertEmail" : "admin@gmail.com", "purpose": "REIMBURSEMENT", "otp" : "", "otpReference" : "" }', CURLOPT_HTTPHEADER => array( 'X-Ipay-Auth-Code: 1', 'X-Ipay-Client-Id: ' . $instantpay_client_id . '', 'X-Ipay-Client-Secret: ' . $instantpay_client_secret . '', 'X-Ipay-Endpoint-Ip: ' . $server_ip_address . '', 'Content-Type: application/json' ), )); $response = curl_exec($curl); $payu_response = $response; curl_close($curl); $res = json_decode($response); if ($res->statuscode == "TXN") { $response_status = 1; $response_messages = $res->status; $response_code = $res->statuscode; } else { $response_status = 0; $response_messages = $res->status; $response_code = $res->statuscode; } if ($response_status == 1) { CreditCardPayout::where('id', $retailer_transuction_id)->update([ 'status' => $response_status, 'response' => trim($response), 'updated_at' => date('Y-m-d h:i:s'), ]); RetailerWallet::where('id', $last_retailer_wallet_id)->update([ 'is_pay' => 1, 'updated_at' => date('Y-m-d h:i:s'), ]); $sms_text = "Topay Your transaction " . $amount . " is successful. For details or assistance, contact support. Thank you for using our services!"; Helper::sendSmsMessages($sms_text, $mobile_number); // Manage payment status $CreditCardPayout = CreditCardPayout::where('status', 1)->where('card_id', $card_id)->where('credit_card_bill_request_id', $credit_card_bill_request_id)->sum('pay_amount'); $originalBill = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->value('due_amount'); if ($CreditCardPayout > 0 && $CreditCardPayout < $originalBill) { // Partial payment made, set status to PARTIAL_PAID $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PARTIAL_PAID]); } elseif ($CreditCardPayout == $originalBill) { // Full payment made, set status to PAID $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PAID]); } else { // Processing payment, e.g., amount being verified $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PROCESSING]); } return response()->json(['response_code' => '1', 'payment_api' => 'Instantpay', 'message' => 'Payment Send Successfully.!']); } else if ($response_status == 0) { CreditCardPayout::where('id', $retailer_transuction_id)->update([ 'status' => $response_status, 'response' => trim($response), 'updated_at' => date('Y-m-d h:i:s'), ]); return response()->json(['response_code' => 0, 'payment_api' => 'Instantpay', 'message' => $response_messages]); } else { return response()->json(['response_code' => 0, 'payment_api' => 'Instantpay', 'message' => $response_messages]); } } if ($payout_provider == "Credit Card") { // dd($request->all()); DB::beginTransaction(); try { $utility_services = config('setting.utility_services'); $is_utility_services = config('setting.is_utility_services'); if ($utility_services == "NSDL" && $is_utility_services != 1) { return response()->json([ 'response_code' => 0, 'message' => 'The NSDL service is currently inactive. Please contact the administrator.' ]); } $operator_id = $request->operator_id; $operator = $request->operator; $clientUserId = auth()->guard('client')->user()->id; $agentId = auth()->guard('client')->user()->agent_id; $category = $request->category; $txnamount = $request->txn_amount; $pay_amount = $request->pay_amount; $amount = $request->amount_main; $name = $request->name; $bill_fetch = $request->bill_fetch; $referenceid = date("Ymdhis") . time(); //$mobileno = "8401276950"; $mobileno = auth()->guard('client')->user()->mobile_number; $emailid = auth()->guard('client')->user()->email; $client_name = auth()->guard('client')->user()->name; $wallet_balance = auth()->guard('client')->user()->wallet_balance; if ($txnamount >= $wallet_balance) { return response()->json([ 'response_code' => 0, 'message' => 'Insufficient wallet balance. Please ensure your balance exceeds the bill amount.' ]); } $check_service = UtilityServices::where('name', $category)->first(); $check_service_provider = ApiModule::where('name', $utility_services)->first(); $check_service_provider_key = BbpsApiWithServices::where('utility_service_id', $check_service->id)->where('api_module_id', $check_service_provider->id)->first(); $billereffctvto = $request->billereffctvto; $billermode = $request->billermode; $parentbiller = $request->parentbiller; $billereffctvfrom = $request->billereffctvfrom; $fetchrequirement = $request->fetchrequirement; $paymentamtexactness = $request->paymentamtexactness ?? ''; $billercoverage = $request->billercoverage; $supportbillvalid = $request->supportbillvalid; $billeracceptsadhoc = $request->billeracceptsadhoc; $billerownershp = $request->billerownershp; // Bill Ftech Details $decodedJson = html_entity_decode($bill_fetch); $billfetch = json_decode($decodedJson); $customerName = $billfetch->fetchresponse->billerResponse->customerName ?? $client_name; $txnrefid = $billfetch->refid ?? ''; $dueDate = $billfetch->fetchresponse->billerResponse->dueDate ?? ''; $custConvFee = $billfetch->fetchresponse->billerResponse->custConvFee ?? ''; $custConvDesc = $billfetch->fetchresponse->billerResponse->custConvDesc ?? ''; $billDate = $billfetch->fetchresponse->billerResponse->billDate ?? ''; $billNumber = $billfetch->fetchresponse->billerResponse->billNumber ?? ''; $billPeriod = $billfetch->fetchresponse->billerResponse->billPeriod ?? ''; $billtags = $billfetch->fetchresponse->additionalInfo->tag ?? []; $canumber = $request->ad1_value; $post_custom_fields = ['ad1_name', 'ad1_value', 'ad2_name', 'ad2_value', 'ad3_name', 'ad3_value', 'ad4_name', 'ad4_value', 'ad5_name', 'ad5_value', 'ad6_name', 'ad6_value', 'ad7_name', 'ad7_value', 'ad8_name', 'ad8_value', 'ad9_name', 'ad9_value']; $billercustomerparamsArr = []; $custome_string = []; $billercustomerparams = ''; foreach ($request->only($post_custom_fields) as $key => $value) { if (!empty($value)) { $billercustomerparams .= $value; $fieldType = explode('_', $key)[1] ?? null; if ($fieldType) { $custome_string[$fieldType] = $value; if (isset($custome_string['name']) && isset($custome_string['value'])) { $billercustomerparamsArr[] = $custome_string; $custome_string = []; } } } } //Bill Tags $billeradditionalinfo = ''; $billeradditionalinfotag = []; foreach ($billtags as $tag) { $billeradditionalinfo .= $tag->name . $tag->value; $billeradditionalinfotag[] = ['name' => $tag->name, 'value' => $tag->value]; } // Get values from configuration $nsdlChannelId = config('setting.nsdl_channel_id'); $nsdlPartnerId = config('setting.nsdl_partner_id'); $token = "NA"; $appId = "com.kavpay.nsdl"; $txncurrency = "INR"; $userloggedinflag = "Y"; $custauthverflg = "Y"; $chantxnrefno = $referenceid; $usrtxnrefno = $referenceid; // Step 1: Payment Details $paymentdtls = $chantxnrefno . $usrtxnrefno . $txnamount . $txncurrency . $userloggedinflag . $custauthverflg; // Step 2: BillPay Details $billeraliasname = $operator; $billerid = $operator_id; $paymentmode = 'Cash'; $billercategoryname = $check_service_provider_key->api_service_name;; $billername = $operator; $billerresponseparams = $customerName . $amount . $dueDate . $custConvFee . $custConvDesc . $billDate . $billNumber . $billPeriod . ''; $paymentchannel = "AGT"; $billamttype = "NA"; $billnumber = $billNumber; $custconvfee = '0.0'; $billpaydtls = $billeraliasname . $billereffctvto . $billeradditionalinfo . $billerid . $paymentmode . $parentbiller . $billereffctvfrom . $fetchrequirement . $paymentamtexactness . $billercategoryname . $billercoverage . $supportbillvalid . $billermode . $billeracceptsadhoc . $billerownershp . $billername . $billercustomerparams . $billerresponseparams . $paymentchannel . $billamttype . $billnumber . $txnrefid . $mobileno . $custconvfee; // Step 3: Channel Device Details $ipaddress = "124.170.23.24"; $imei = "448674528976410"; $os = "Android"; $appname = $agentId; // "appname" => "NS01NS02BNK510230768" $channeldevdtls = $ipaddress . $imei . $os . $appname; // Step 4: Build Full Checksum String $checksum = $nsdlChannelId . $nsdlPartnerId . $appId . $paymentdtls . $billpaydtls . $channeldevdtls . $token; $url = config('setting.nsdl_url') . "/partner/billpaytxn"; $secretKey = config('setting.nsdl_secret_key'); $signcs = Helper::signatureChecksum($secretKey, $checksum); $postdata = array( "channelid" => $nsdlChannelId, "partnerid" => $nsdlPartnerId, "appid" => $appId, "paymentdtls" => array( "chantxnrefno" => $chantxnrefno, "usrtxnrefno" => $usrtxnrefno, "txnamount" => $txnamount, "txncurrency" => $txncurrency, "userloggedinflag" => $userloggedinflag, "custauthverflg" => $custauthverflg ), "billpaydtls" => array( "billeraliasname" => $operator, "billereffctvto" => $billereffctvto, "billerid" => $operator_id, "paymentmode" => $paymentmode, "parentbiller" => $parentbiller, "billereffctvfrom" => $billereffctvfrom, "fetchrequirement" => $fetchrequirement, "paymentamtexactness" => $paymentamtexactness, "billercategoryname" => $billercategoryname, "billercoverage" => $billercoverage, "supportbillvalid" => $supportbillvalid, "billermode" => $billermode, "billeracceptsadhoc" => $billeracceptsadhoc, "billerownershp" => $billerownershp, "billername" => $operator, "billercustomerparams" => $billercustomerparamsArr, "billerresponseparams" => array( "customerName" => $customerName, "amount" => $amount, "dueDate" => $dueDate, "custConvFee" => $custConvFee, "custConvDesc" => $custConvDesc, "billDate" => $billDate, "billNumber" => $billNumber, "billPeriod" => $billPeriod, "tag" => array() ), "billeradditionalinfo" => array( "tag" => $billeradditionalinfotag ), "paymentchannel" => $paymentchannel, "billamttype" => $billamttype, "billnumber" => $billNumber, "txnrefid" => $txnrefid, "mobileno" => $mobileno, "custconvfee" => $custconvfee ), "channeldevdtls" => array( "ipaddress" => $ipaddress, "imei" => $imei, "os" => $os, "appname" => $appname ), "token" => $token, "signcs" => $signcs ); $result = Helper::nsdlCurlPost($url, $postdata); $res = json_decode($result); // dd($res); $respcode = $res->respcode == '00' ? 1 : 0; $response_messages = $res->response; // Create a new utility payment record $last_payment_id = CreditCardPayout::create([ 'retailer_id' => $clientUserId, 'category' => $category, 'operator_id' => $operator_id, 'credit_card_bill_request_id' => $credit_card_bill_request_id, 'operator' => $operator, 'card_id' => $card_id, 'refid' => $referenceid, 'name' => $name, 'mobile' => $mobile, 'card_number' => $card_number, 'type' => $payout_provider, 'amount' => $pay_amount, 'pay_amount' => $txnamount, 'service_charges' => $web_bill_payment_charges, 'card_charges' => $card_percentage_charges, 'remarks' => $remarks, 'transaction_mode' => $transaction_mode, 'network' => $network, 'browser_type' => 2, 'status' => 0, 'payout_api' => $utility_services, 'created_at' => now(), 'updated_at' => now() ])->id; if ($respcode == 1) { // Generate filename for the invoice // Deduct the amount from the client's wallet Client::whereId($clientUserId)->decrement('wallet_balance', $txnamount); // Record the debit transaction in RetailerWallet RetailerWallet::create([ 'topay_transuction_id' => sha1(md5(time())), 'retailer_id' => $clientUserId, 'amount' => $txnamount, 'received_amount' => $txnamount, 'mode' => 'Debit', 'payment_mode' => 'Online', 'is_status' => 1, 'payment_api' => $utility_services, 'remarks' => "{$category} Bill payment for {$operator} Rs. {$txnamount} only", 'retailer_transuction_id' => $last_payment_id, 'transuction_type' => "Utility Payment", 'created_at' => now(), 'updated_at' => now() ]); CreditCardPayout::whereId($last_payment_id)->update([ 'response' => trim($result), 'status' => 1, 'updated_at' => now() ]); // Manage payment status $CreditCardPayout = CreditCardPayout::where('status', 1)->where('card_id', $card_id)->where('credit_card_bill_request_id', $credit_card_bill_request_id)->sum('pay_amount'); $originalBill = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->value('due_amount'); if ($CreditCardPayout > 0 && $CreditCardPayout < $originalBill) { // Partial payment made, set status to PARTIAL_PAID $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PARTIAL_PAID]); } elseif ($CreditCardPayout == $originalBill) { // Full payment made, set status to PAID $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PAID]); } else { // Processing payment, e.g., amount being verified $updated = CreditCardBillRequest::where('id', $credit_card_bill_request_id) ->update(['status' => CardChargePayStatus::PROCESSING]); } $get_retailer_commission = RetailerCommission::where('retailer_id', $clientUserId)->where('utility_service_id', $check_service->id)->first(); // Fetch retailer commission $commission = RetailerCommission::where('retailer_id', $clientUserId) ->where('utility_service_id', $check_service->id) ->first(); if ($commission) { // Update payment with commission details UtilityPayment::whereId($last_payment_id)->update([ 'retailer_commission' => $commission->commission, 'distributor_commission' => $commission->distributor_commission, 'updated_at' => now() ]); // Process retailer commission if ($commission->commission > 0) { $retailer_commission_value = ($txnamount * $commission->commission) / 100; Client::whereId($clientUserId)->increment('wallet_balance', $retailer_commission_value); RetailerWallet::create([ 'topay_transuction_id' => sha1(md5(time())), 'retailer_id' => $clientUserId, 'amount' => $retailer_commission_value, 'mode' => 'Credit', 'payment_mode' => 'Commission', 'is_status' => 1, 'payment_api' => $utility_services, 'remarks' => "{$category} Bill Cash Back for Rs. {$retailer_commission_value} only", 'retailer_transuction_id' => $last_payment_id, 'transuction_type' => "Utility Payment Commission", 'created_at' => now(), 'updated_at' => now() ]); } // Process distributor commission if ($commission->distributor_commission > 0) { $distributor_commission_value = ($txnamount * $commission->distributor_commission) / 100; Client::whereId($commission->distributor_id)->increment('wallet_balance', $distributor_commission_value); Wallet::create([ 'topay_transuction_id' => sha1(md5(time())), 'distributor_id' => $commission->distributor_id, 'amount' => $distributor_commission_value, 'mode' => 'Credit', 'payment_mode' => 'Commission', 'is_status' => 1, 'payment_api' => $utility_services, 'payout_transuction_id' => $last_payment_id, 'transuction_type' => "Utility Payment Commission", 'created_at' => now(), 'updated_at' => now() ]); } } // Send SMS notification $sms_text = "Thank you for the bill payment of Rs. {$txnamount} against {$operator} Consumer No. {$canumber}. Transaction Ref. ID {$referenceid} received on " . now() . ". Payment channel Wallet. Thank you for choosing Topay."; Helper::sendSmsMessages($sms_text, $mobileno); DB::commit(); // Return a success response return response()->json(['response_code' => $respcode, 'payment_api' => 'NSDL', 'message' => $response_messages]); } // Return a failed response return response()->json(['response_code' => $respcode, 'payment_api' => 'NSDL', 'message' => $response_messages]); } catch (\Throwable $e) { DB::rollBack(); return response()->json(['response_code' => 0, 'message' => 'API error : ' . $e->getMessage()]); } } } public function viewRequestDetails(Request $request) { if ($request->decrypt_request_card_unique_id) { $decryptedId = $request->decrypt_request_card_unique_id; } else { $decryptedId = decrypt($request->request_card_unique_id); } $user_id = auth()->guard('client')->user(); $requestData = CreditCardBillRequest::where('request_card_unique_id', $decryptedId)->where('retailer_id', $user_id->id)->with('card')->get(); $card_charge_pay = CardChargePay::where('request_card_unique_id', $decryptedId)->get(); // requestModel balde file same use in customer and retailer $view = view('customer.payRequest.requestModel', compact('requestData', 'card_charge_pay'))->render(); return response()->json([ 'view' => $view ]); } public function downloadPdf($encryptedId) { if (strlen($encryptedId) < 32) { $requestCardUniqueId = $encryptedId; } else { $requestCardUniqueId = decrypt($encryptedId); } $user = auth()->guard('client')->user(); $requestData = CreditCardBillRequest::where('request_card_unique_id', $requestCardUniqueId)->where('retailer_id', $user->id)->with('card')->get(); if (!$requestData) { abort(404, 'Request data not found'); } $customer = Customer::where('id', $requestData[0]->customer_id)->first(); $pdf = app(PDF::class); // credit_card_bill_pdf balde file same use in customer and retailer $pdf = $pdf->loadView('customer.payRequest.credit_card_bill_pdf', ['requestData' => $requestData, 'user' => $user, 'customer' => $customer]); return $pdf->download('credit_card_bill_' . 'pdf' . '.pdf'); } public function requestCardCharge(Request $request) { if ($request->decrypt_request_card_unique_id) { $requestUniqueId = $request->decrypt_request_card_unique_id; } else { $requestUniqueId = decrypt($request->request_card_unique_id); } $user_id = auth()->guard('client')->user()->id; if ($request->filled('table_id')) { $billRequestId = $request->table_id; } else { // Fallback to first pending if not specified (for top button) $firstBill = CreditCardBillRequest::where('request_card_unique_id', $requestUniqueId) ->where('retailer_id', $user_id) ->first(); $billRequestId = $firstBill ? $firstBill->id : null; } if (!$billRequestId) { return response()->json(['error' => 'No bill request found'], 404); } $billRequest = CreditCardBillRequest::with('card')->findOrFail($billRequestId); $totalCalculatedCharge = $billRequest->calculated_amount_card_charge; $paidChargeAmount = CardChargePay::where('credit_card_bill_requests_id', $billRequestId) ->where('status', '!=', 2) ->sum('card_charge_pay_amount'); $remainingCharge = max($totalCalculatedCharge - $paidChargeAmount, 0); // requestCardChargeModel blade file same use in customer and retailer $view = view('customer.payRequest.requestCardChargeModel', [ 'requestData' => $billRequest, 'requestUniqueId' => $requestUniqueId, 'remainingCharge' => $remainingCharge, 'billRequestId' => $billRequestId, ])->render(); return response()->json([ 'view' => $view ]); } public function storePayCardCharge(Request $request) { $request->validate([ 'request_card_unique_id' => 'required|string', 'credit_card_bill_requests_id' => 'required|integer', 'transaction_id' => 'required|string|unique:card_charge_pay,transaction_id', 'card_charge_calculated_amount' => 'required|numeric', 'card_charge_pay_amount' => 'required|numeric|min:0.01|lte:card_charge_calculated_amount', 'payment_method' => 'required|string', 'card_charge_image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', ], [ 'transaction_id.unique' => 'This transaction ID has already been used. Please enter a unique transaction ID.', 'card_charge_pay_amount.lte' => 'Pay amount cannot be greater than the calculated card charge amount.', ]); DB::beginTransaction(); try { $imagePath = null; if ($request->hasFile('card_charge_image')) { $imagePath = $request->file('card_charge_image') ->store('public/credit_card_charge'); } CardChargePay::create([ 'request_card_unique_id' => $request->request_card_unique_id, 'transaction_id' => $request->transaction_id, 'credit_card_bill_requests_id' => $request->credit_card_bill_requests_id, 'card_charge_calculated_amount' => $request->card_charge_calculated_amount, 'card_charge_pay_amount' => $request->card_charge_pay_amount, 'payment_method' => $request->payment_method, 'image' => $imagePath, 'status' => 1, ]); DB::commit(); return response()->json([ 'success' => true, 'message' => 'Card Charge Added Successfully!', ]); } catch (\Throwable $e) { DB::rollBack(); return response()->json([ 'success' => false, 'message' => 'Failed to process card charge payment.', ], 500); } } public function getCreditCardOperatorList(Request $request) { $category = $request->category; $operators = []; // dd($request->all(),$category); $utility_services = config('setting.utility_services'); $is_utility_services = config('setting.is_utility_services'); if ($utility_services == "Paysprint" && $is_utility_services == 1) { $check_service = UtilityServices::where('name', $category)->first(); $check_service_provider = ApiModule::where('name', $utility_services)->first(); $check_service_provider_key = BbpsApiWithServices::where('utility_service_id', $check_service->id)->where('api_module_id', $check_service_provider->id)->first(); $url = config('setting.paysprint_url') . "/api/v1/service/bill-payment/bill/getoperator"; $postdata = ['mode' => 'online']; $result = Helper::curlPost($url, $postdata); $res = json_decode($result); $operators = $res->data; $output = ""; if ($check_service_provider_key) { foreach ($operators as $operator) { if (trim($operator->category) == $check_service_provider_key->api_service_name) { $output .= ''; } } } } if ($utility_services == "NSDL" && $is_utility_services != 1) { return response()->json([ 'response_code' => 0, 'message' => 'The NSDL service is currently inactive. Please contact the administrator.' ]); } $check_service = UtilityServices::where('name', $category)->first(); $check_service_provider = ApiModule::where('name', $utility_services)->first(); $check_service_provider_key = BbpsApiWithServices::where('utility_service_id', $check_service->id) ->where('api_module_id', $check_service_provider->id) ->first(); $url = config('setting.nsdl_url') . "/partner/fetchbillerlist"; $secretKey = config('setting.nsdl_secret_key'); $output = ""; $billercustomerparams = []; if ($check_service_provider_key) { $channelId = config('setting.nsdl_channel_id'); $partnerId = config('setting.nsdl_partner_id'); $searchType = "BILLERTYPE"; $searchStr = $check_service_provider_key->api_service_name; $token = "NA"; // Generate checksum $checksum = "{$channelId}{$partnerId}{$searchType}{$searchStr}{$token}"; $signcs = Helper::signatureChecksum($secretKey, $checksum); // Prepare post data $postData = [ "channelid" => $channelId, "partnerid" => $partnerId, "searchtype" => $searchType, "searchstr" => $searchStr, "token" => $token, "signcs" => $signcs, ]; // Execute the cURL request and decode the result $response = Helper::nsdlCurlPost($url, $postData); $res = json_decode($response); if ($res->respcode == 00) { $aggregatorlists = $res->billerslist[0]->aggregatorlist ?? []; foreach ($aggregatorlists as $key => $operator) { // Determine viewbill value $viewbill = (!empty($operator->fetchrequirement) && $operator->fetchrequirement !== "NOT_SUPPORTED") ? 1 : 0; $customFieldText = ''; if (!empty($operator->billercustomerparams)) { foreach ($operator->billercustomerparams as $key => $customField) { $fieldKey = $key + 1; // Use ternary operator to assign values to variables with default if empty $regex = !empty($customField->regex) ? $customField->regex : ''; $values = !empty($customField->values) ? $customField->values : ''; // Build the array for data attributes $customFieldArrays = [ 'data-ad' . $fieldKey . '_d_name' => $customField->paramName, 'data-ad' . $fieldKey . '_name' => $customField->paramName, 'data-ad' . $fieldKey . '_regex' => $regex, 'data-ad' . $fieldKey . '_values' => $values ]; // Concatenate the text string with the attribute values foreach ($customFieldArrays as $key => $value) { $customFieldText .= $key . '="' . $value . '" '; } } } $billereffctvto = $operator->billereffctvto ?? ''; $billermode = $operator->billermode ?? ''; $parentbiller = $operator->parentbiller ?? ''; $billereffctvfrom = $operator->billereffctvfrom ?? ''; $fetchrequirement = $operator->fetchrequirement ?? ''; $paymentamtexactness = $operator->paymentamtexactness ?? ''; $billercoverage = $operator->billercoverage ?? ''; $supportbillvalid = $operator->supportbillvalid ?? ''; $billeracceptsadhoc = $operator->billeracceptsadhoc ?? ''; $billerownershp = $operator->billerownershp ?? ''; $billercustomerparams[$operator->operator_code][] = $operator->billercustomerparams ? $operator->billercustomerparams : []; // Use array_filter to find the object where paymentChannel is 'AGT' $billerresponseparams = array_filter($operator->billerresponseparams, function ($param) { return isset($param->paymentChannel) && $param->paymentChannel === "AGT"; }); $billerresponseparams = array_values($billerresponseparams); $amountMinLimit = $billerresponseparams[0]->minLimit ?? 100; $amountMaxLimit = $billerresponseparams[0]->maxLimit ?? 1000000; $output .= ''; } } } // dd($output,$billercustomerparams); return response()->json([ 'response_code' => 1, 'message' => 'success.', 'output' => $output, 'billercustomerparams' => $billercustomerparams ]); } public function fetchCreditCardBillRecharge(Request $request) { $operator_id = $request->operator_id; $canumber = $request->canumber; $amount = $request->amount; $wallet_balance = auth()->guard('client')->user()->wallet_balance; $agentId = auth()->guard('client')->user()->agent_id; $category = $request->category; $ad1_name = $request->ad1_name; $ad1_value = $request->ad1_value; $ad2_name = $request->ad2_name; $ad2_value = $request->ad2_value; $ad3_name = $request->ad3_name; $ad3_value = $request->ad3_value; if ($amount >= $wallet_balance) { return response()->json(['response_code' => 0, 'message' => 'Your wallet balance is not greater than bill amount.']); } $utility_services = config('setting.utility_services'); $is_utility_services = config('setting.is_utility_services'); $mobileno = auth()->guard('client')->user()->mobile_number; $emailid = auth()->guard('client')->user()->email; if ($utility_services == "NSDL" && $is_utility_services == 1) { $url = config('setting.nsdl_url') . "/partner/fetchbill"; $secretKey = config('setting.nsdl_secret_key'); $post_text_string = ''; $post_text_string_array = array(); foreach ($_POST as $key => $custom_val) { // Check if the key starts with 'ad' and contains '_name' or '_value' if (strpos($key, 'ad') === 0 && (strpos($key, '_name') !== false || strpos($key, '_value') !== false)) { if (!empty($custom_val)) { $post_text_string .= $custom_val; // Split the key to determine its type (e.g., ad1_name or ad1_value) $val_check = explode("_", $key); $custome_string[$val_check[1]] = $custom_val; // Check if both "name" and "value" are set before adding to the array if (isset($custome_string['name']) && isset($custome_string['value'])) { $post_text_string_array[] = $custome_string; // Reset the array for the next iteration $custome_string = array(); } } } } // dd(config('setting.nsdl_channel_id'),config('setting.nsdl_partner_id'),$mobileno , $emailid , $operator_id,$agentId,$post_text_string); $checksum = config('setting.nsdl_channel_id') . config('setting.nsdl_partner_id') . $mobileno . $emailid . $operator_id . "124.170.23.24" . "448674528976410" . "Android" . $agentId . $post_text_string . "NA"; $signcs = Helper::signatureChecksum($secretKey, $checksum); $postdata = array( "channelid" => config('setting.nsdl_channel_id'), "partnerid" => config('setting.nsdl_partner_id'), "billdtls" => array( "mobileno" => $mobileno, "emailid" => $emailid, "billerid" => $operator_id, "channeldevdtls" => array( "ipaddress" => "124.170.23.24", "imei" => "448674528976410", "os" => "Android", "appname" => $agentId ), "customerparams" => $post_text_string_array ), "token" => "NA", "signcs" => $signcs ); $result = Helper::nsdlCurlPost($url, $postdata); $res = json_decode($result); if ($res->respcode == 00) { $customerName = $res->fetchresponse->billerResponse->customerName; $amount = $res->fetchresponse->billerResponse->amount; $dueDate = $res->fetchresponse->billerResponse->dueDate; return response()->json(['response_code' => 1, 'biller_name' => $customerName, 'biller_amount' => $amount, 'biller_duedate' => $dueDate, 'message' => $res->response, 'nsdl_refid' => $res->refid, 'bill_fetch_request' => json_encode($postdata), 'bill_fetch' => json_encode($res)]); } return response()->json(['response_code' => $res->respcode, 'bill_fetch_request' => json_encode($postdata), 'bill_fetch' => json_encode($res), 'message' => $res->response]); } if ($utility_services == "Paysprint" && $is_utility_services == 1) { $url = config('setting.paysprint_url') . "/api/v1/service/bill-payment/bill/fetchbill"; $postdata = ['operator' => $operator_id, 'canumber' => $canumber, 'mode' => 'online']; if ($request->ad1_value) { $postdata[$request->ad1_name] = $request->ad1_value; } if ($request->ad2_value) { $postdata[$request->ad2_name] = $request->ad2_value; } if ($request->ad3_value) { $postdata[$request->ad3_name] = $request->ad3_value; } $result = Helper::curlPost($url, $postdata); $res = json_decode($result); if ($res->response_code == 1) { return response()->json(['response_code' => $res->response_code, 'biller_name' => $res->name, 'biller_amount' => $res->amount, 'biller_duedate' => $res->duedate, 'message' => $res->message, 'bill_fetch' => json_encode($res->bill_fetch)]); } return response()->json(['response_code' => $res->response_code, 'message' => $res->message]); } } public function customerAllTransaction(Request $request) { $draw = $request->get('draw'); $start = $request->get("start"); $limit = $request->get("length"); $columnIndex_arr = $request->get('order'); $columnName_arr = $request->get('columns'); $order_arr = $request->get('order'); $search_arr = $request->get('search'); $columnIndex = $columnIndex_arr[0]['column']; $order = $columnName_arr[$columnIndex]['data']; $dir = $order_arr[0]['dir']; if ($order == "action") { $order = 'id'; } $id = auth()->guard('client')->user()->id; $filter_from = $request->input('filter_from'); $filter_to = $request->input('filter_to'); $query = CreditCardPayout::where('retailer_id', $id)->with('card'); if (!empty($filter_from) && !empty($filter_to)) { $query->whereBetween(DB::raw('DATE(created_at)'), [$filter_from, $filter_to]); } if (!empty($request->card_id) && !empty($request->card_id)) { $query->where('card_id', $request->card_id); } if (!empty($request->credit_card_bill_request_id) && !empty($request->credit_card_bill_request_id)) { $query->where('credit_card_bill_request_id', $request->credit_card_bill_request_id); } if (!empty($request->input('search'))) { $search = $request->input('search'); $query->where(function ($query) use ($search) { $query->where('created_at', 'LIKE', "%{$search}%") ->orWhere('pay_amount', 'LIKE', "%{$search}%") ->orWhere('debit_amount', 'LIKE', "%{$search}%") ->orWhere('status', 'LIKE', "%{$search}%") ->orWhere('remarks', 'LIKE', "%{$search}%") ->orWhereHas('card', function ($query) use ($search) { $query->where('card_number', 'LIKE', "%{$search}%") ->orWhere('name_on_card', 'LIKE', "%{$search}%") ->orWhere('network_type', 'LIKE', "%{$search}%") ->orWhere('bank_name', 'LIKE', "%{$search}%"); }); }); } if (!empty($request->customer_id)) { $query->where('request_card_unique_id', $request->customer_id); } $totalFiltered = $query->count(); $totalData = $query->count(); $values = $query->orderBy('id', 'DESC')->offset($start)->limit($limit)->get(); $data = array(); if (!empty($values)) { $i = $start + 1; foreach ($values as $value) { // $customer = Customer::where('id', $value->customer_id)->first(); // $card = Card::where('id', $value->card_id)->where('customer_id', $value->customer_id)->first(); $mainData['id'] = $i; $mainData['card_type'] = $value->card->network_type; // $mainData['customer_name'] = $customer->customer_name; $mainData['card_name'] = $value->card->name_on_card; $mainData['card_number'] = 'xxxx-xxxx-xxxx-' . substr($value->card->card_number, -4); $mainData['bank_name'] = $value->card->bank_name; $mainData['pay_amount'] = $value->pay_amount ? '' . htmlspecialchars($value->pay_amount, ENT_QUOTES, 'UTF-8') . '' : '00'; $mainData['debit_amount'] = $value->debit_amount ? '' . htmlspecialchars($value->debit_amount, ENT_QUOTES, 'UTF-8') . '' : '00'; $mainData['status'] = $value->status == 1 ? 'paid' : ($value->status == 0 ? 'unpaid' : ''); $mainData['remarks'] = $value->remarks; $mainData['payout_provider'] = str_replace('_', ' ', $value->type); $mainData['created_at'] = \Carbon\Carbon::parse($value->created_at)->format('d-m-y'); $data[] = $mainData; $i++; } } $json_data = array( "draw" => intval($request->input('draw')), "recordsTotal" => intval($totalData), "recordsFiltered" => intval($totalFiltered), "data" => $data ); echo json_encode($json_data); } public function creditCardBillView(Request $request, $id) { $decryptedId = decrypt($id); $user_id = auth()->guard('client')->user(); $requestData = CreditCardBillRequest::where('id', $decryptedId)->where('retailer_id', $user_id->id)->with('card', 'customer')->first(); $card_id = $requestData->card_id; $credit_card_bill_request_id = $requestData->id; $CreditCardBillRequest_id = CreditCardBillRequest::where('id', $decryptedId)->where('retailer_id', $user_id->id)->with('card', 'customer')->pluck('id'); $get_pay_amount = CreditCardPayout::where('credit_card_bill_request_id', $requestData->id)->get(); $card_charge_pay = CardChargePay::where('request_card_unique_id', $requestData->request_card_unique_id) ->where(function ($query) use ($CreditCardBillRequest_id) { foreach ($CreditCardBillRequest_id as $id) { $query->orWhereRaw('FIND_IN_SET(?, credit_card_bill_requests_id)', [$id]); } }) ->get(); $total_credit_card_bill = $requestData->due_amount; $total_charge = $requestData->calculated_amount_card_charge; $pay_charge = $card_charge_pay->sum('card_charge_pay_amount'); $total_paid = $get_pay_amount->sum('pay_amount') + $pay_charge; $total_cc_bill_charge = $total_credit_card_bill + $total_charge; $total_pending = $total_cc_bill_charge - $total_paid; Session::put('header_title', "All Customer Pay List"); return view('retailer.payRequest.view', compact('card_id', 'requestData', 'credit_card_bill_request_id', 'total_credit_card_bill', 'total_charge', 'total_paid', 'total_cc_bill_charge', 'total_pending')); } public function withdrawGetModel(Request $request) { $card_id = $request->card_id; $credit_card_bill_request_id = $request->credit_card_bill_request_id; $action = $request->action; $user_id = auth()->guard('client')->user(); $requestData = CreditCardBillRequest::where('id', $credit_card_bill_request_id)->where('retailer_id', $user_id->id)->with('card', 'customer')->first(); $card = Card::find($card_id); $view = view('retailer.payRequest.withdeawModel', compact('card', 'action', 'requestData'))->render(); return response()->json([ 'view' => $view ]); } public function depositeStore(Request $request) { try { // Comprehensive validation $validated = $request->validate([ 'card_id' => 'required|exists:cards,id', 'credit_card_bill_request_id' => 'required|exists:credit_card_bill_requests,id', 'amount' => 'required|numeric|min:0.01', 'pay_amount' => 'required|numeric|min:0.01', 'transaction_mode' => 'required|in:Online,Offline', 'payment_method' => 'required_if:transaction_mode,Online|nullable|string|in:InstantPay', 'payment_mode_id' => 'required_if:transaction_mode,Offline|nullable', 'payout_charge' => 'required_if:transaction_mode,Online|nullable|numeric|min:0|max:100', 'total_amount' => 'required_if:transaction_mode,Online|nullable|numeric|min:0', 'transaction_id' => 'nullable|string|max:255', 'remarks' => 'nullable|string|max:1000', ], [ 'card_id.required' => 'Card ID is required', 'card_id.exists' => 'Invalid card selected', 'credit_card_bill_request_id.required' => 'Bill request ID is required', 'credit_card_bill_request_id.exists' => 'Invalid bill request', 'amount.required' => 'Due amount is required', 'amount.min' => 'Due amount must be greater than 0', 'pay_amount.required' => 'Pay amount is required', 'pay_amount.min' => 'Pay amount must be greater than 0', 'transaction_mode.required' => 'Transaction mode is required', 'transaction_mode.in' => 'Invalid transaction mode selected', 'payment_method.required_if' => 'Payment method is required for online transactions', 'payment_method.in' => 'Invalid payment method selected', 'payout_charge.required_if' => 'Payout charge is required for online transactions', 'total_amount.required_if' => 'Total amount is required for online transactions', ]); // Additional business logic validation if ($validated['pay_amount'] > $validated['amount']) { return response()->json([ 'success' => false, 'message' => 'Pay amount (₹' . number_format($validated['pay_amount'], 2) . ') cannot be greater than due amount (₹' . number_format($validated['amount'], 2) . ')' ], 422); } $retailer_id = auth()->guard('client')->user()->id; // Verify ownership and authorization $billRequest = CreditCardBillRequest::where('id', $validated['credit_card_bill_request_id']) ->where('retailer_id', $retailer_id) ->first(); if (!$billRequest) { return response()->json([ 'success' => false, 'message' => 'Unauthorized: This bill request does not belong to you' ], 403); } // Verify card ownership $card = Card::where('id', $validated['card_id']) ->where('user_id', $retailer_id) ->first(); if (!$card) { return response()->json([ 'success' => false, 'message' => 'Unauthorized: This card does not belong to you' ], 403); } // Start database transaction DB::beginTransaction(); if ($validated['transaction_mode'] === 'Offline') { return $this->depositeOffline($request->all(), $retailer_id, $card); } else { return $this->depositeOnline($request->all(), $retailer_id, $card); } } catch (\Illuminate\Validation\ValidationException $e) { // Validation errors return response()->json([ 'success' => false, 'message' => 'Validation failed. Please check your input.', 'errors' => $e->errors() ], 422); } catch (\Exception $e) { // Rollback transaction on any error DB::rollBack(); // Return user-friendly error message return response()->json([ 'success' => false, 'message' => 'Failed to record deposit. Please try again or contact support.', 'error' => config('app.debug') ? $e->getMessage() : 'An unexpected error occurred' ], 500); } } public function withdrawStore(Request $request) { try { // Comprehensive validation $validated = $request->validate([ 'card_id' => 'required|exists:cards,id', 'credit_card_bill_request_id' => 'required|exists:credit_card_bill_requests,id', 'amount' => 'required|numeric|min:0.01', 'pay_amount' => 'required|numeric|min:0.01', 'include_card_charges' => 'nullable|numeric', 'transaction_mode' => 'required|in:Online,Offline', 'payment_method' => 'required_if:transaction_mode,Online|nullable', 'payment_mode_id' => 'required_if:transaction_mode,Offline|nullable', 'transaction_id' => 'nullable|string|max:255', 'remarks' => 'nullable|string|max:1000', ], [ 'card_id.required' => 'Card ID is required', 'card_id.exists' => 'Invalid card selected', 'credit_card_bill_request_id.required' => 'Bill request ID is required', 'credit_card_bill_request_id.exists' => 'Invalid bill request', 'amount.required' => 'Withdraw amount is required', 'amount.min' => 'Withdraw amount must be greater than 0', 'pay_amount.required' => 'Pay amount is required', 'pay_amount.min' => 'Pay amount must be greater than 0', 'include_card_charges.numeric' => 'Include card charges must be a number', 'transaction_mode.required' => 'Transaction mode is required', 'transaction_mode.in' => 'Invalid transaction mode selected', 'payment_method.required_if' => 'Payment method is required for online transactions', 'payment_method.exists' => 'Invalid payment method selected', ]); // Additional business logic validation if ($validated['pay_amount'] > $validated['amount']) { return response()->json([ 'success' => false, 'message' => 'Pay amount (₹' . number_format($validated['pay_amount'], 2) . ') cannot be greater than withdraw amount (₹' . number_format($validated['amount'], 2) . ')' ], 422); } $retailer_id = auth()->guard('client')->user()->id; // Verify ownership and authorization $billRequest = CreditCardBillRequest::where('id', $validated['credit_card_bill_request_id']) ->where('retailer_id', $retailer_id) ->first(); if (!$billRequest) { return response()->json([ 'success' => false, 'message' => 'Unauthorized: This bill request does not belong to you' ], 403); } // Verify card ownership $card = Card::where('id', $validated['card_id']) ->where('user_id', $retailer_id) ->first(); if (!$card) { return response()->json([ 'success' => false, 'message' => 'Unauthorized: This card does not belong to you' ], 403); } // Start database transaction DB::beginTransaction(); // Route to appropriate method based on transaction mode if ($validated['transaction_mode'] === 'Offline') { // Offline: Record as Credit, DON'T update wallet $result = $this->withdrawOffline($request->all(), $retailer_id, $card); } else { // Online: Record as Credit, DEDUCT from wallet $result = $this->withdrawOnline($request->all(), $retailer_id, $card); } // Commit all database changes DB::commit(); return response()->json($result, 200); } catch (\Illuminate\Validation\ValidationException $e) { // Validation errors return response()->json([ 'success' => false, 'message' => 'Validation failed. Please check your input.', 'errors' => $e->errors() ], 422); } catch (\Exception $e) { // Rollback transaction on any error DB::rollBack(); // Return user-friendly error message return response()->json([ 'success' => false, 'message' => 'Failed to record withdraw. Please try again or contact support.', 'error' => config('app.debug') ? $e->getMessage() : 'An unexpected error occurred' ], 500); } } /** * Handle offline deposit - Record transaction but DON'T update wallet * Offline means retailer received cash/offline payment from customer */ private function depositeOffline($validated, $retailer_id, $card) { // Generate unique reference ID $ref_id = 'CCPD-OFF-' . $retailer_id . '-' . date("YmdHis") . '-' . rand(1000, 9999); // Create credit card payout record (Debit entry for offline payment) $payout = CreditCardPayout::create([ 'retailer_id' => $retailer_id, 'card_id' => $validated['card_id'], 'credit_card_bill_request_id' => $validated['credit_card_bill_request_id'], 'refid' => $ref_id, 'amount' => $validated['amount'], 'pay_amount' => $validated['pay_amount'], 'card_charges' => 0, 'transaction_type' => 'Debit', // Debit for offline 'transaction_mode' => 'Offline', 'transaction_id' => $validated['transaction_id'] ?? null, 'remarks' => $validated['remarks'] ?? 'Offline credit card bill deposit', 'status' => 1, 'browser_type' => 2, 'payment_mode_id' => $validated['payment_mode_id'] ?? null, ]); // Check and update bill request status if pending is now 0 $this->updateBillRequestStatusIfPaid($validated['credit_card_bill_request_id'], $retailer_id); DB::commit(); return [ 'success' => true, 'message' => 'Offline deposit recorded successfully! ₹' . number_format($validated['pay_amount'], 2) . ' received (wallet not updated for offline payment).', 'data' => [ 'payout_id' => $payout->id, 'ref_id' => $ref_id, 'transaction_id' => $validated['transaction_id'] ?? 'N/A', 'amount_deposited' => '₹' . number_format($validated['pay_amount'], 2), 'transaction_mode' => 'Offline', 'note' => 'Offline payment - Wallet balance unchanged' ] ]; } private function depositeOnline($validated, $retailer_id, $card) { // Generate unique reference ID $ref_id = 'CCPD-ONL-' . $retailer_id . '-' . date("YmdHis") . '-' . rand(1000, 9999); // Check if InstantPay payment method is selected if (isset($validated['payment_method']) && $validated['payment_method'] === 'InstantPay') { return $this->processInstantPayDeposit($validated, $retailer_id, $card, $ref_id); } } private function processInstantPayDeposit($validated, $retailer_id, $card, $ref_id) { $payoutCharge = $validated['payout_charge'] ?? 0; $payAmount = $validated['pay_amount']; $chargeAmount = ($payAmount * $payoutCharge) / 100; $totalAmount = $payAmount + $chargeAmount; // Deduct total amount (including charges) from wallet $retailer = Client::lockForUpdate()->find($retailer_id); if (!$retailer) { return [ 'success' => false, 'message' => 'Retailer account not found', ]; } if ($retailer->wallet_balance < $totalAmount) { return [ 'success' => false, 'message' => 'Insufficient wallet balance. Required: ₹' . number_format($totalAmount, 2) . ', Available: ₹' . number_format($retailer->wallet_balance, 2), ]; } // Call InstantPay API via Service try { $instantPayService = new \App\Services\InstantPay(); $cardDetails = [ 'card_number' => $card->card_number, 'name_on_card' => $card->name_on_card, ]; $apiResponse = $instantPayService->processCreditCardPayout($cardDetails, $payAmount, $ref_id); if ($apiResponse['success']) { // Create pending payout record $payout = CreditCardPayout::create([ 'retailer_id' => $retailer_id, 'card_id' => $validated['card_id'], 'credit_card_bill_request_id' => $validated['credit_card_bill_request_id'], 'refid' => $ref_id, 'amount' => $validated['amount'], 'pay_amount' => $payAmount, 'card_charges' => 0, 'transaction_type' => 'Debit', 'transaction_mode' => 'Online', 'payment_method' => 'InstantPay', 'remarks' => $validated['remarks'] ?? 'InstantPay credit card bill payout', 'browser_type' => 2, 'payout_api' => 'InstantPay', 'payout_charges' => $payoutCharge, 'payout_charge_amount' => $chargeAmount, 'status' => 1, 'transaction_id' => $apiResponse['transaction_id'] ?? null, 'order_id' => $apiResponse['order_id'] ?? null, 'response' => $apiResponse, ]); $previousBalance = $retailer->wallet_balance; $retailer->wallet_balance -= $totalAmount; $retailer->save(); // Create wallet debit record RetailerWallet::create([ 'retailer_id' => $retailer_id, 'mihpayid' => $ref_id, 'topay_transuction_id' => $payout->id, 'amount' => $totalAmount, 'received_amount' => $totalAmount, 'mode' => 'Debit', 'payment_mode' => 'online', 'is_status' => 1, 'remarks' => 'InstantPay deposit - ' . $card->bank_name . ' (Amount: ₹' . $payAmount . ' + Charge: ₹' . number_format($chargeAmount, 2) . ')', 'payment_api' => 'InstantPay', 'retailer_transuction_id' => $payout->id, 'transuction_type' => 'Credit Card Bill Deposit - InstantPay', ]); // Check and update bill request status if pending is now 0 $this->updateBillRequestStatusIfPaid($validated['credit_card_bill_request_id'], $retailer_id); DB::commit(); return [ 'success' => true, 'message' => 'InstantPay deposit successful! ₹' . number_format($payAmount, 2) . ' transferred to card.', 'data' => [ 'payout_id' => $payout->id, 'ref_id' => $ref_id, 'transaction_id' => $apiResponse['transaction_id'] ?? $ref_id, 'amount_deposited' => '₹' . number_format($payAmount, 2), 'payout_charge' => '₹' . number_format($chargeAmount, 2), 'total_deducted' => '₹' . number_format($totalAmount, 2), 'previous_balance' => '₹' . number_format($previousBalance, 2), 'new_wallet_balance' => '₹' . number_format($retailer->wallet_balance, 2), 'transaction_mode' => 'Online - InstantPay', ] ]; } else { return [ 'success' => false, 'message' => $apiResponse['message'] ?? 'InstantPay API failed', ]; } } catch (\Exception $e) { throw $e; } } /** * Handle offline withdraw - Record Credit entry, DON'T update wallet * Offline means retailer pays cash to customer */ private function withdrawOffline($validated, $retailer_id, $card) { // Generate unique reference ID $ref_id = 'CCPW-OFF-' . $retailer_id . '-' . date("YmdHis") . '-' . rand(1000, 9999); // Create credit card payout record (Credit entry for offline withdraw) $payout = CreditCardPayout::create([ 'retailer_id' => $retailer_id, 'card_id' => $validated['card_id'], 'credit_card_bill_request_id' => $validated['credit_card_bill_request_id'], 'refid' => $ref_id, 'amount' => $validated['amount'], 'pay_amount' => ($validated['pay_amount'] - $validated['include_card_charges']), 'card_charges' => $validated['include_card_charges'] ?? 0, 'transaction_type' => 'Credit', // Credit for withdraw 'transaction_mode' => 'Offline', 'transaction_id' => $validated['transaction_id'] ?? null, 'remarks' => $validated['remarks'] ?? 'Offline credit card bill withdraw', 'status' => 1, 'browser_type' => 2, 'payment_mode_id' => $validated['payment_mode_id'] ?? null, ]); if ($validated['include_card_charges'] > 0) { CardChargePay::create([ 'request_card_unique_id' => $validated['request_card_unique_id'], 'credit_card_bill_requests_id' => $validated['credit_card_bill_request_id'], 'card_charge_calculated_amount' => $validated['include_card_charges'], 'card_charge_pay_amount' => $validated['include_card_charges'], 'status' => 1, 'payment_method' => "Credit Card", ]); } // Check and update bill request status if pending is now 0 $this->updateBillRequestStatusIfPaid($validated['credit_card_bill_request_id'], $retailer_id); // Get current wallet balance (NO CHANGE to wallet for offline) $retailer = Client::find($retailer_id); $currentBalance = $retailer->wallet_balance; DB::commit(); return [ 'success' => true, 'message' => 'Offline withdraw recorded successfully! ₹' . number_format($validated['pay_amount'], 2) . ' paid (wallet not updated for offline payment).', 'data' => [ 'payout_id' => $payout->id, 'ref_id' => $ref_id, 'transaction_id' => $validated['transaction_id'] ?? 'N/A', 'amount_withdrawn' => '₹' . number_format($validated['pay_amount'], 2), 'wallet_balance' => '₹' . number_format($currentBalance, 2), 'transaction_mode' => 'Offline', 'note' => 'Offline payment - Wallet balance unchanged' ] ]; } /** * Handle online withdraw - Record Credit entry AND deduct from wallet * Online means payment goes through digital wallet */ private function withdrawOnline($validated, $retailer_id, $card) { $pay_amount = $validated['pay_amount']; // Generate unique reference ID $ref_id = 'CCPW-ONL-' . $retailer_id . '-' . date("YmdHis") . '-' . rand(1000, 9999); $get_pg_services_types = PgServicesType::select( "pg_services_types.id", "pg_services_types.name", "pg_services_types.payment_gateway_id", "pg_services_types.charges", "payment_gateway_services.name as payment_gateway_name" ) ->join("payment_gateway_services", "pg_services_types.payment_gateway_id", '=', "payment_gateway_services.id") ->where('pg_services_types.id', $validated['payment_method']) ->first(); if (!$get_pg_services_types) { return [ 'success' => false, 'message' => 'Something Wrong. Please Contact to admin!', ]; } $transacation_service = $get_pg_services_types->payment_gateway_name ?? null; if (!$transacation_service) { return [ 'success' => false, 'message' => 'Something Wrong. Please Contact to admin!', ]; } do { $partnerOrderId = sha1(md5(uniqid(mt_rand(), true))); } while (Wallet::where('topay_transuction_id', $partnerOrderId)->exists()); if ($transacation_service == "VegaahPay" && config('setting.vegaah_status_id') == 1) { $merchantUrl = config('setting.vegaah_url'); // vendorkey $merchantTerminalId = config('setting.vegaah_terminalId'); // vendorkey $merchantPassword = config('setting.vegaah_password'); $merchantKey = config('setting.vegaah_merchantkey'); $user = auth()->guard('client')->user(); $userId = $user->id ?? null; $name = $user->name ?? 'Customer'; $email = $user->email ?? 'demo@gmail.com'; $payout_charge_amount = $validated['pay_amount'] * ($validated['payout_charge'] / 100); $payout = CreditCardPayout::create([ 'retailer_id' => $retailer_id, 'card_id' => $validated['card_id'], 'credit_card_bill_request_id' => $validated['credit_card_bill_request_id'], 'refid' => $ref_id, 'amount' => $validated['amount'] - $validated['include_card_charges'], 'pay_amount' => ($validated['pay_amount'] - $validated['include_card_charges']), 'card_charges' => $validated['include_card_charges'] ?? 0, 'transaction_type' => 'Credit', // Credit for withdraw 'transaction_mode' => 'Online', 'payout_charges' => $validated['payout_charge'] ?? 0, 'payout_charge_amount' => $payout_charge_amount, 'transaction_id' => $validated['transaction_id'] ?? null, 'remarks' => $validated['remarks'] ?? 'Online credit card bill withdraw', 'status' => 0, 'browser_type' => 2, 'payout_api' => $transacation_service, 'response' => null, ]); $data_insert = [ 'topay_transuction_id' => $partnerOrderId, 'retailer_id' => $retailer_id, 'credit_card_payout_id' => $payout->id, 'amount' => $validated['pay_amount'], 'received_amount' => $validated['total_amount'], 'mode' => 'Credit', 'payment_mode' => 'Online', 'is_status' => 0, 'is_pay' => 0, 'transuction_type' => "Credit Card Withdraw", 'pg_services_id' => $validated['payment_method'], 'pg_servic_charges' => $validated['payout_charge'] ?? 0, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; RetailerWallet::insertGetId($data_insert); // amount MUST be string with 2 decimals $pay_amount = number_format((float) $pay_amount, 2, '.', ''); // generate signature $signature = $this->generateVegaahSignature( $partnerOrderId, $merchantTerminalId, $merchantPassword, $merchantKey, $pay_amount, "INR" ); $payload = [ "terminalId" => $merchantTerminalId, "password" => $merchantPassword, "paymentType" => "1", "amount" => $pay_amount, "currency" => "INR", "order" => [ "orderId" => $partnerOrderId, "description" => "Wallet Recharge for distributor: " . $name ], "customer" => [ "customerEmail" => $email, "billingAddressStreet" => "", "billingAddressCity" => "", "billingAddressState" => "", "billingAddressPostalCode" => "", "billingAddressCountry" => "IN" ], "additionalDetails" => [ "userData" => json_encode([ "entryone" => $userId, "entrytwo" => "retailer_withdraw", "entrythree" => $payout->id, "receiptUrl" => url('retailer-vegaah-pay/withdraw-return-url') ]) ], "signature" => $signature ]; $paymentResponse = Http::withHeaders([ 'Content-Type' => 'application/json', ]) ->post($merchantUrl, $payload); if (!$paymentResponse->ok()) { return [ 'success' => false, 'message' => 'Payment link failed', ]; } $paymentData = $paymentResponse->json(); if (isset($paymentData['result']) && $paymentData['result'] === "FAILURE") { return [ 'success' => false, 'message' => $paymentData['responseDescription'] ?? 'No payment link found!', ]; } $paymentLink = $paymentData['paymentLink']['linkUrl'] ?? null; $transactionId = $paymentData['transactionId'] ?? null; $mainPaymentLink = $paymentLink . $transactionId; if (!$mainPaymentLink) { return [ 'success' => false, 'message' => 'No payment link found!', ]; } // 3️⃣ Step 3: Redirect User return [ 'success' => true, 'message' => 'Payment link generated successfully', 'type' => 'pg', 'payment_link' => $mainPaymentLink, ]; } elseif ($transacation_service == "POS") { $payout_charge_amount = $validated['pay_amount'] * ($validated['payout_charge'] / 100); $payout = CreditCardPayout::create([ 'retailer_id' => $retailer_id, 'card_id' => $validated['card_id'], 'credit_card_bill_request_id' => $validated['credit_card_bill_request_id'], 'refid' => $ref_id, 'amount' => $validated['amount'] - $validated['include_card_charges'], 'pay_amount' => ($validated['pay_amount'] - $validated['include_card_charges']), 'card_charges' => $validated['include_card_charges'] ?? 0, 'transaction_type' => 'Credit', // Credit for withdraw 'transaction_mode' => 'Online', 'payout_charges' => $validated['payout_charge'] ?? 0, 'payout_charge_amount' => $payout_charge_amount, 'transaction_id' => $validated['transaction_id'] ?? null, 'remarks' => $validated['remarks'] ?? 'Online credit card bill withdraw', 'status' => 0, 'browser_type' => 2, 'payout_api' => null, ]); $data_insert = [ 'topay_transuction_id' => $partnerOrderId, 'retailer_id' => $retailer_id, 'credit_card_payout_id' => $payout->id, 'amount' => $validated['pay_amount'], 'received_amount' => $validated['total_amount'], 'mode' => 'Credit', 'payment_mode' => 'Online', 'is_status' => 0, 'is_pay' => 0, 'transuction_type' => "Credit Card Without payment gateway POS From Withdraw", 'pg_services_id' => $validated['payment_method'], 'pg_servic_charges' => $validated['payout_charge'] ?? 0, 'payment_api' => 'POS', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), ]; RetailerWallet::insertGetId($data_insert); return [ 'success' => true, 'message' => 'payment done successfully.', ]; } } protected function generateVegaahSignature($trackId, $terminalId, $password, $merchantKey, $amount, $currency) { // Ensure amount has exactly 2 decimals and currency uppercase $amount = number_format((float)$amount, 2, '.', ''); $currency = strtoupper(trim($currency)); $parts = [ trim((string)$trackId), trim((string)$terminalId), trim((string)$password), trim((string)$merchantKey), $amount, $currency ]; $raw = implode('|', $parts); // Vegaah expects SHA256 hex (lowercase) return hash('sha256', $raw); } /** * Check and update bill request status if pending amount is 0 * This is called after deposit/withdraw transactions */ private function updateBillRequestStatusIfPaid($billRequestId, $retailerId) { try { // Get the bill request $billRequest = CreditCardBillRequest::where('id', $billRequestId) ->where('retailer_id', $retailerId) ->first(); if (!$billRequest) { return; } $requestCardId = $billRequest->request_card_unique_id; // Get all bill requests for this card $cardBillRequests = CreditCardBillRequest::where('request_card_unique_id', $requestCardId) ->orderByDesc('id') ->get(['id', 'due_amount', 'calculated_amount_card_charge']); $billIds = $cardBillRequests->pluck('id'); // Get debit totals per bill $debitTotals = CreditCardPayout::whereIn('credit_card_bill_request_id', $billIds) ->where('transaction_type', 'Debit') ->where('retailer_id', $retailerId) ->where('status', 1) ->selectRaw('credit_card_bill_request_id, SUM(pay_amount) as total') ->groupBy('credit_card_bill_request_id') ->pluck('total', 'credit_card_bill_request_id'); // Get credit totals per bill $creditTotals = CreditCardPayout::whereIn('credit_card_bill_request_id', $billIds) ->where('transaction_type', 'Credit') ->where('retailer_id', $retailerId) ->where('status', 1) ->selectRaw('credit_card_bill_request_id, SUM(pay_amount) as total') ->groupBy('credit_card_bill_request_id') ->pluck('total', 'credit_card_bill_request_id'); // Get card charge payments per bill $chargeTotals = CardChargePay::whereIn('credit_card_bill_requests_id', $billIds) ->where('status', 1) ->selectRaw('credit_card_bill_requests_id, SUM(card_charge_pay_amount) as total') ->groupBy('credit_card_bill_requests_id') ->pluck('total', 'credit_card_bill_requests_id'); // Calculate totals for this card $totalAmount = 0; $pending = 0; foreach ($cardBillRequests as $bill) { $dueAmount = $bill->due_amount; $chargeAmount = $bill->calculated_amount_card_charge; $totalCcBillCharge = $dueAmount + $chargeAmount; $totalAmount += $totalCcBillCharge; $debitPaid = $debitTotals[$bill->id] ?? 0; $creditPaid = $creditTotals[$bill->id] ?? 0; $chargePaid = $chargeTotals[$bill->id] ?? 0; // Same logic as getAmountData $paid = $debitPaid - $creditPaid; if ($paid <= 0) { $totalPaid = abs($debitPaid + $chargePaid); } else { $totalPaid = $chargePaid; } $billPending = $totalCcBillCharge - $totalPaid; $pending += $billPending; } // If pending is 0 and there's an actual amount, mark all as PAID if ($pending <= 0 && $totalAmount > 0) { CreditCardBillRequest::where('request_card_unique_id', $requestCardId) ->where('retailer_id', $retailerId) ->update(['status' => 1]); } } catch (\Exception $e) { // Log error but don't fail the transaction \Illuminate\Support\Facades\Log::error('Error updating bill request status: ' . $e->getMessage()); } } public function payoutHistory(Request $request) { $billRequestId = $request->bill_request_id; $retailer_id = auth()->guard('client')->user()->id; // Verify ownership $billRequest = CreditCardBillRequest::where('id', $billRequestId) ->where('retailer_id', $retailer_id) ->first(); if (!$billRequest) { return response()->json([ 'data' => [], 'recordsTotal' => 0, 'recordsFiltered' => 0 ]); } // Fetch payout history with payment mode relationship $payouts = CreditCardPayout::where('credit_card_bill_request_id', $billRequestId) ->where('retailer_id', $retailer_id) ->with(['paymentMode', 'staff', 'retailer']) ->orderBy('created_at', 'desc') ->get(); $data = []; $i = 1; foreach ($payouts as $payout) { // Format transaction type with badge $typeBadge = $payout->transaction_type === 'Debit' ? 'Debit' : 'Credit'; // Format transaction mode $modeBadge = $payout->transaction_mode === 'Online' ? 'Online' : 'Offline'; // Format payment mode (only for offline transactions) $paymentMode = '-'; if ($payout->transaction_mode === 'Offline' && $payout->paymentMode) { $paymentMode = $payout->paymentMode->payment_mode; } // Format status $statusBadge = match ($payout->status) { 1 => 'Success', 2 => 'Failed', default => 'Pending', }; $data[] = [ 'DT_RowIndex' => $i++, 'created_at' => date('d M Y, h:i A', strtotime($payout->created_at)), 'refid' => $payout->refid ?? 'N/A', 'transaction_type' => $typeBadge, 'transaction_mode' => $modeBadge, 'payment_mode' => $paymentMode, 'pay_amount' => '₹' . number_format($payout->pay_amount, 2), 'card_charges' => $payout->card_charges > 0 ? '₹' . number_format($payout->card_charges, 2) : '-', 'transaction_id' => !empty($payout->transaction_id) ? $payout->transaction_id : '-', 'order_id' => !empty($payout->order_id) ? $payout->order_id : '-', 'remarks' => $payout->remarks ?? '-', 'status' => $statusBadge, 'transaction_by' => $payout->staff_id ? (($payout->staff->name ?? '-') . ' (Staff)') : (($payout->retailer->name ?? '-') . ' (Retailer)') ]; } return response()->json([ 'data' => $data, 'recordsTotal' => count($data), 'recordsFiltered' => count($data) ]); } public function creditCardReports() { $user_id = auth()->guard('client')->user()->id; $get_card_lists = Card::where('user_id', $user_id)->where('browser_type', 2)->orderBy('id', 'DESC')->get(); $query = CreditCardBillRequest::where('retailer_id', $user_id) ->whereNotNull('credit_card_bill_requests.request_card_unique_id') ->join('customers', 'customers.id', '=', 'credit_card_bill_requests.customer_id')->selectRaw('credit_card_bill_requests.request_card_unique_id, MAX(credit_card_bill_requests.id) as id, MAX(credit_card_bill_requests.created_at) as created_at, MAX(credit_card_bill_requests.status) as status, SUM(credit_card_bill_requests.due_amount) as total_due_amount, COUNT(*) as total_records, customers.customer_name as customer_name ') ->groupBy('credit_card_bill_requests.request_card_unique_id', 'customers.customer_name'); $query->orderByDesc('created_at'); $CreditCardBillRequest = $query->get(); $get_customers = Customer::where('user_id', $user_id)->where('status', 1)->get(); Session::put('header_title', "Credit Card Reports"); return view('retailer.payRequest.report', compact('get_card_lists', 'CreditCardBillRequest', 'get_customers')); } public function creditCardChargeList(Request $request) { $draw = $request->get('draw'); $start = $request->get("start"); $limit = $request->get("length"); $columnIndex_arr = $request->get('order'); $columnName_arr = $request->get('columns'); $order_arr = $request->get('order'); $search_arr = $request->get('search'); $columnIndex = $columnIndex_arr[0]['column']; $order = $columnName_arr[$columnIndex]['data']; $dir = $order_arr[0]['dir']; if ($order == "action") { $order = 'id'; } $id = auth()->guard('client')->user()->id; $filter_from = $request->input('filter_from'); $filter_to = $request->input('filter_to'); $query = CreditCardBillRequest::where('retailer_id', $id)->whereHas('card')->with('card'); if (!empty($filter_from) && !empty($filter_to)) { $query->whereBetween(DB::raw('DATE(created_at)'), [$filter_from, $filter_to]); } if (!empty($request->input('search'))) { $search = $request->input('search'); $query->whereHas('card', function ($query) use ($search) { $query->where('network_type', 'LIKE', "%{$search}%") ->orWhere('name_on_card', 'LIKE', "%{$search}%") ->orWhere('card_number', 'LIKE', "%{$search}%") ->orWhere('bank_name', 'LIKE', "%{$search}%"); })->orWhere(function ($query) use ($search) { $query->where('calculated_amount_card_charge', 'LIKE', "%{$search}%") ->orWhere('status', 'LIKE', "%{$search}%") ->orWhere('remarks', 'LIKE', "%{$search}%") ->orWhere('created_at', 'LIKE', "%{$search}%") ->orWhere('request_card_unique_id', 'LIKE', "%{$search}%"); }); } if (!empty($request->input('filter_customer_id'))) { $customerId = $request->input('filter_customer_id'); $query->where('customer_id', $customerId); } if (!empty($request->input('request_card_unique_id'))) { $request_card_unique_id = $request->input('request_card_unique_id'); $query->where('request_card_unique_id', $request_card_unique_id); } $totalFiltered = $query->count(); $totalData = $query->count(); $values = $query->orderBy('id', 'DESC')->offset($start)->limit($limit)->get(); $data = array(); if (!empty($values)) { $i = $start + 1; foreach ($values as $value) { // Get Debit transactions (approved only) $debitPaid = CreditCardPayout::where('retailer_id', $id) ->where('credit_card_bill_request_id', $value->id) ->where('transaction_type', 'Debit') ->where('status', 1) ->sum('pay_amount'); // Get Credit transactions (approved only) $creditPaid = CreditCardPayout::where('retailer_id', $id) ->where('credit_card_bill_request_id', $value->id) ->where('transaction_type', 'Credit') ->where('status', 1) ->sum('pay_amount'); // Get card charge payments (approved only) $card_charge_pay = CardChargePay::where('request_card_unique_id', $value->request_card_unique_id) ->where(function ($query) use ($value) { $query->whereRaw('FIND_IN_SET(?, credit_card_bill_requests_id)', [$value->id]); }) ->where('status', 1) ->sum('card_charge_pay_amount'); // Calculate total amount (due + card charge) $total_amount = $value->due_amount + $value->calculated_amount_card_charge; // Calculate net payment (same logic as getAmountData) $paid = $debitPaid - $creditPaid; if ($paid <= 0) { $totalPaid = abs($debitPaid + $card_charge_pay); } else { $totalPaid = $card_charge_pay; } // Determine payment status if ($totalPaid >= $total_amount) { $card_charge_status = \App\Enums\CardChargePayStatus::label(2); // Paid $statusColors = 'text-success'; } else { $card_charge_status = \App\Enums\CardChargePayStatus::label(0); // Unpaid $statusColors = 'text-danger'; } $statusLabel = \App\Enums\CardChargePayStatus::label($value->status); $statusColor = ''; switch ($value->status) { case \App\Enums\CardChargePayStatus::PROCESSING: $statusColor = 'text-primary'; // Blue break; case \App\Enums\CardChargePayStatus::PAID: $statusColor = 'text-success'; // Green break; case \App\Enums\CardChargePayStatus::UNPAID: $statusColor = 'text-danger'; // Red break; case \App\Enums\CardChargePayStatus::PARTIAL_PAID: $statusColor = 'text-warning'; // Yellow break; default: $statusColor = 'text-secondary'; // Gray (default) break; } $mainData['id'] = $i; $mainData['request_card_unique_id'] = isset($value->request_card_unique_id) ? $value->request_card_unique_id : null; $mainData['card_type'] = $value->card->network_type; $mainData['card_name'] = $value->card->name_on_card; $mainData['card_number'] = 'xxxx-xxxx-xxxx-' . substr($value->card->card_number, -4);; $mainData['bank_name'] = $value->card->bank_name; $mainData['pay_amount'] = !empty($debitPaid) ? '' . number_format($debitPaid, 2) . '' : '-'; $mainData['debit_amount'] = !empty($creditPaid) ? '' . number_format($creditPaid, 2) . '' : '-'; $mainData['calculated_amount_card_charge'] = $value->calculated_amount_card_charge; $mainData['amount_to_be_collected_status'] = '' . $statusLabel . ''; $mainData['card_charge_status'] = '' . $card_charge_status . ''; $mainData['remarks'] = $value->remarks; $mainData['created_at'] = \Carbon\Carbon::parse($value->created_at)->format('d-m-y'); //$mainData['action'] = ' View  '; $mainData['action'] = ''; $data[] = $mainData; $i++; } } $json_data = array( "draw" => intval($request->input('draw')), "recordsTotal" => intval($totalData), "recordsFiltered" => intval($totalFiltered), "data" => $data ); echo json_encode($json_data); } public function getAmountData(Request $request) { $requestCardId = $request->request_card_unique_id; $retailerId = auth()->guard('client')->user()->id; // 🔹 Get all related bill requests $cardBillRequests = CreditCardBillRequest::where('request_card_unique_id', $requestCardId) ->orderByDesc('id') ->get(['id', 'due_amount', 'calculated_amount_card_charge']); if ($cardBillRequests->isEmpty()) { return response()->json([ 'total_credit_card_bill' => 0, 'total_charge' => 0, 'total_cc_bill_charge' => 0, 'total_paid' => 0, 'total_pending' => 0, ]); } $billIds = $cardBillRequests->pluck('id'); // 🔹 Debit totals $debitTotals = CreditCardPayout::whereIn('credit_card_bill_request_id', $billIds) ->where('transaction_type', 'Debit') ->where('retailer_id', $retailerId) ->where('status', 1) ->selectRaw('credit_card_bill_request_id, SUM(pay_amount) as total') ->groupBy('credit_card_bill_request_id') ->pluck('total', 'credit_card_bill_request_id'); // 🔹 Credit totals $creditTotals = CreditCardPayout::whereIn('credit_card_bill_request_id', $billIds) ->where('transaction_type', 'Credit') ->where('retailer_id', $retailerId) ->where('status', 1) ->selectRaw('credit_card_bill_request_id, SUM(pay_amount) as total') ->groupBy('credit_card_bill_request_id') ->pluck('total', 'credit_card_bill_request_id'); // 🔹 Card charge payments $chargeTotals = CardChargePay::whereIn('credit_card_bill_requests_id', $billIds) ->where('status', 1) ->selectRaw('credit_card_bill_requests_id, SUM(card_charge_pay_amount) as total') ->groupBy('credit_card_bill_requests_id') ->pluck('total', 'credit_card_bill_requests_id'); // 🔹 Final aggregation $data = [ 'total_credit_card_bill' => 0, 'total_charge' => 0, 'total_cc_bill_charge' => 0, 'total_paid' => 0, 'total_pending' => 0, ]; foreach ($cardBillRequests as $bill) { $dueAmount = $bill->due_amount; $chargeAmount = $bill->calculated_amount_card_charge; $data['total_credit_card_bill'] += $dueAmount; $data['total_charge'] += $chargeAmount; $totalCcBillCharge = $dueAmount + $chargeAmount; $data['total_cc_bill_charge'] += $totalCcBillCharge; $debitPaid = $debitTotals[$bill->id] ?? 0; $creditPaid = $creditTotals[$bill->id] ?? 0; $chargePaid = $chargeTotals[$bill->id] ?? 0; // 🔹 SAME LOGIC AS YOUR CODE $paid = $debitPaid - $creditPaid; if ($paid <= 0) { $totalPaid = abs($debitPaid + $chargePaid); } else { $totalPaid = $chargePaid; } $pending = $totalCcBillCharge - $totalPaid; $data['total_paid'] += $totalPaid; $data['total_pending'] += $pending; } return response()->json($data); } // Get Card Charge Payment History public function getCardChargeHistory(Request $request) { $billId = $request->bill_id; $requestUniqueId = $request->request_card_unique_id; $chargePayments = CardChargePay::with('card') ->where('request_card_unique_id', $requestUniqueId) ->where(function ($query) use ($billId) { $query->whereRaw('FIND_IN_SET(?, credit_card_bill_requests_id)', [$billId]); }) ->orderBy('created_at', 'DESC') ->get(); $data = $chargePayments->map(function ($payment) { // Get card details if payment was made using a card $cardDetails = null; if ($payment->card_request_id && $payment->card) { $cardDetails = $payment->card->bank_name . ' - **** ' . substr($payment->card->card_number, -4); } return [ 'id' => $payment->id, 'payment_method' => $payment->payment_method ?? null, 'transaction_id' => $payment->transaction_id ?? null, 'card_charge_pay_amount' => $payment->card_charge_pay_amount, 'image' => $payment->image ? asset('storage/' . str_replace('public/', '', $payment->image)) : null, 'status' => $payment->status, 'reject_reason' => $payment->reject_reason ?? null, 'created_at' => Carbon::parse($payment->created_at)->format('d-m-Y H:i'), 'card_details' => $cardDetails, ]; }); return response()->json([ 'success' => true, 'data' => $data ]); } // Update Card Charge Payment Status public function updateCardChargeStatus(Request $request) { $chargeId = $request->charge_id; $status = $request->status; $chargePayment = CardChargePay::find($chargeId); if (!$chargePayment) { return response()->json([ 'success' => false, 'message' => 'Payment record not found' ]); } // Prevent changing status if it's already paid or rejected if ($chargePayment->status == 1 || $chargePayment->status == 2) { return response()->json([ 'success' => false, 'message' => 'Cannot change status of a ' . ($chargePayment->status == 1 ? 'paid' : 'rejected') . ' payment' ]); } $chargePayment->status = $status; // If status is being set to Rejected (2), save the reject reason if ($status == 2) { $rejectReason = $request->reject_reason; if (!$rejectReason) { return response()->json([ 'success' => false, 'message' => 'Reject reason is required' ]); } $chargePayment->reject_reason = $rejectReason; } $chargePayment->save(); return response()->json([ 'success' => true, 'message' => 'Status updated successfully' ]); } // Delete Card Charge Payment public function deleteCardChargePayment(Request $request) { $chargeId = $request->charge_id; $chargePayment = CardChargePay::find($chargeId); if (!$chargePayment) { return response()->json([ 'success' => false, 'message' => 'Payment record not found' ]); } // Prevent deletion of paid payments if ($chargePayment->status == 1) { return response()->json([ 'success' => false, 'message' => 'Cannot delete a paid payment record' ]); } $chargePayment->delete(); return response()->json([ 'success' => true, 'message' => 'Payment deleted successfully' ]); } public function getCombinedCardChargeHistory(Request $request) { $requestUniqueId = $request->request_unique_id; $chargePayments = CardChargePay::where('request_card_unique_id', $requestUniqueId) ->with(['billRequest.card']) ->orderBy('created_at', 'DESC') ->get(); $data = $chargePayments->map(function ($payment) { $card = $payment->billRequest->card ?? null; return [ 'id' => $payment->id, 'card_name' => $card ? ($card->name_on_card . ' (' . substr($card->card_number, -4) . ')') : 'N/A', 'payment_method' => $payment->payment_method ?? null, 'transaction_id' => $payment->transaction_id ?? null, 'card_charge_pay_amount' => $payment->card_charge_pay_amount, 'image' => $payment->image ? asset('storage/' . str_replace('public/', '', $payment->image)) : null, 'status' => $payment->status, 'reject_reason' => $payment->reject_reason ?? null, 'created_at' => Carbon::parse($payment->created_at)->format('d-m-Y H:i'), ]; }); return response()->json([ 'success' => true, 'data' => $data ]); } public function combineRequestCardCharge(Request $request) { $uniqueId = $request->request_card_unique_id; $billRequests = CreditCardBillRequest::where('request_card_unique_id', $uniqueId) ->with('card') ->get(); $billRequestIds = $billRequests->pluck('id'); $paidChargeAmounts = CardChargePay::whereIn('credit_card_bill_requests_id', $billRequestIds) ->where('status', '!=', 2) ->selectRaw('credit_card_bill_requests_id, SUM(card_charge_pay_amount) as total_paid') ->groupBy('credit_card_bill_requests_id') ->pluck('total_paid', 'credit_card_bill_requests_id'); $cardCharges = $billRequests->map(function ($billRequest) use ($paidChargeAmounts) { $paidAmount = $paidChargeAmounts[$billRequest->id] ?? 0; $remainingAmount = max($billRequest->calculated_amount_card_charge - $paidAmount, 0); $billRequest->remaining_amount = $remainingAmount; return $billRequest; })->filter(function ($billRequest) { return $billRequest->remaining_amount > 0; }); $totalRemainingCharge = $cardCharges->sum('remaining_amount'); $requestUniqueId = $uniqueId; $hasCards = $cardCharges->count() > 0; if (!$hasCards) { return response()->json([ 'hasCards' => false, 'message' => 'No cards with remaining charges found.' ]); } $view = view('retailer.payRequest.combineCardChargeModal', compact( 'cardCharges', 'totalRemainingCharge', 'requestUniqueId' ))->render(); return response()->json([ 'hasCards' => true, 'view' => $view ]); } public function storeCombinePayCardCharge(Request $request) { $request->validate([ 'request_card_unique_id' => 'required|string', 'bill_request_ids' => 'required|array', 'bill_request_ids.*' => 'required|integer', 'card_charge_amounts' => 'required|array', 'card_charge_amounts.*' => 'required|numeric|min:0.01', 'transaction_id' => 'required|string|unique:card_charge_pay,transaction_id', 'payment_method' => 'required|string', 'card_charge_image' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', ], [ 'transaction_id.unique' => 'This transaction ID has already been used. Please enter a unique transaction ID.', 'bill_request_ids.required' => 'No cards selected for payment.', 'card_charge_image.required' => 'Payment proof image is required.', ]); DB::beginTransaction(); try { $imagePath = null; if ($request->hasFile('card_charge_image')) { $imagePath = $request->file('card_charge_image') ->store('public/credit_card_charge'); } $createdCount = 0; foreach ($request->bill_request_ids as $index => $billRequestId) { $chargeAmount = $request->card_charge_amounts[$index]; if ($chargeAmount > 0) { CardChargePay::create([ 'request_card_unique_id' => $request->request_card_unique_id, 'transaction_id' => $request->transaction_id, 'credit_card_bill_requests_id' => $billRequestId, 'card_charge_calculated_amount' => $chargeAmount, 'card_charge_pay_amount' => $chargeAmount, 'payment_method' => $request->payment_method, 'image' => $imagePath, 'status' => 1, // Paid for Retailer ]); $createdCount++; } } DB::commit(); return response()->json([ 'success' => true, 'message' => "Successfully created {$createdCount} card charge payment(s) marked as Paid!", ]); } catch (\Throwable $e) { DB::rollBack(); return response()->json([ 'success' => false, 'message' => 'Failed to process combined card charge payment.', 'error' => $e->getMessage(), ], 500); } } public function updateStaff(Request $request) { $validator = Validator::make($request->all(), [ 'request_ids' => 'required|array', 'staff_id' => 'required' ]); if ($validator->fails()) { return response()->json(['success' => false, 'message' => $validator->errors()->first()]); } try { $retailerId = auth()->guard('client')->id(); \Log::info('Bulk Assign Staff Request', [ 'retailer_id' => $retailerId, 'request_ids' => $request->request_ids, 'staff_id' => $request->staff_id ]); $updated = CreditCardBillRequest::where('retailer_id', $retailerId) ->whereIn('request_card_unique_id', $request->request_ids) ->update(['staff_id' => $request->staff_id]); \Log::info('Rows updated: ' . $updated); if ($updated > 0) { return response()->json(['success' => true, 'message' => 'Staff assigned successfully']); } else { return response()->json(['success' => false, 'message' => 'No records updated. Please check selection.']); } } catch (\Exception $e) { \Log::error('Update Staff Error: ' . $e->getMessage()); return response()->json(['success' => false, 'message' => 'Failed to assign staff']); } } }