<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class withdrawalBackend extends Controller
{
    // Account ID: 231
    // Username:
    // eU5dlNkAxdYPt2vFXLUz
    // Password:
    // gIgJ9Z5gxMNPwrVUFuNegF4MZMIdHHnbavOqQkeE

    protected $apiUrl = 'https://backend.payhero.co.ke/api/v2/withdraw';
    protected $apiUsername = 'OCoSMTsLB9FA9kcBJeBv';
    protected $apiPassword = '7qvX6mlyB60hzdoOoFkPHW9x7ke23u6HR1vKlyaB';
    
    
    
    
    
    
    public function allCashouts()
    {
        return view('withdrawals.all');
    }
     public function pendingCashouts()
     {
       return view('withdrawals.pending');
     }

     public function approveCashouts(Request $request)
     {
        DB::table('cashouts')->where('id', $request->id)->update(['status' => 'approved']);
        return back()->with('success', 'Withdrawal Approved Successfully');
     }

     public function rejectCashouts(Request $request)
     {
        DB::table('cashouts')->where('id', $request->id)->update(['status' => 'rejected']);
        return back()->with('warning', 'Withdrawal Rejected Successfully');
     }

     public function approvedCashout()
     {
        return view('withdrawals.approved');
     }

     public function rejectedCashout()
     {
      return view('withdrawals.rejected');
     }
     
      // withdrawal implementation
      
      
    public function handleRequest($request, $amount)
    {
        // Get the IP address of the requester
        $ip = $request->ip();
    
        // Get the user ID (if authenticated)
        $userId = auth()->id();
    
        // Generate a unique token for the request
        $utoken =Str::random(10); // Adjust tunhe length of the token as needed 
    
    
        // Check for similar requests within the last 10 minutes
        $similarRequests = DB::table('request_logs')->where('ip', $ip)
            ->where('user_id', $userId)
            ->where('amount', $amount)
            ->where('token', $utoken)
            ->where('created_at', '>=', now()->subMinutes(10))
            ->exists();
    
        // If similar requests found, handle accordingly (e.g., update status, return error response)
        if ($similarRequests) {
            // Handle similar requests
            return false;
        } else {
            // Insert the request data into the database
            DB::table('request_logs')->insert([
                'ip' => $ip,
                'user_id' => $userId,
                'token' => $utoken,
                'amount' => $amount,
                'status' => 'received',
                'created_at' => now(),
                'status' => "ByAdmin"
            ]);
            
            // Process the request further
            return false;
        }
        return false;
    }


    public function payUser(Request $req)
    {
        $thisUserId = request()->query('user');
        $thisTrxId = request()->query('trx');
        $thisAmount = request()->query('amt');
        
        $isNotSafe = $this->handleRequest($req, $thisAmount);
        
        if($isNotSafe)
        {
            return back()->with('error', "Invalid request, Retry later!");
        }
        
       
        $amount = (float)$thisAmount;
        $userProfile = DB::table('users')->where('username', $thisUserId)->first();
        $userCashout = DB::table('cashouts')->where('id', $thisTrxId)->first();
        if($userCashout->status == 'approved'){
            return back()->with('error', "Invalid request, Already approved!");
        }
        
        $phone = $userProfile->phone; 
        $balance = $userProfile->balance;
        $name = $userProfile->username;
        $phoneNumber = $userCashout->phone;


        if ($userProfile) {
            if ($amount < 2000) 
            {
                // Call makePayment method with Basic Auth token
                $response = $this->makePayment($amount, $phoneNumber);
                //dd($response);
                // Check if the payment was successful
                if ($response['success']) {
                    // Payment was successful
                    $paymentData = $response['data'];
                    // Further processing or actions based on successful payment
                    $status = "approved";
                } else {
                    // Payment failed
                    $errorData = $response['data'];
                    // Further processing or actions based on failed payment
                    $status = 'pending';
                    //dd($errorData);
                    return back()->with('error', $errorData['error_message']);
                }
            } else 
            {
                $status = "pending";
                return back()->with('error', 'Error occured');
            }

            //cashout
            DB::table('cashouts')->where('id', $thisTrxId)->update([ 'status' => "$status"]);
        }


        //ennd of email
        return back()->with('success', "request successful");
    }

    protected function makePayment($amount, $receiverPhoneNumber)
    {
        // Generate Basic Auth token
        $basicAuthToken = $this->generateBasicAuthToken();

        $data = [
            "external_reference" => "mpesa101",
            "amount" => $amount,
            "phone_number" => $receiverPhoneNumber,
            "network_code" => "63902",
            "callback_url" => "https://trustline.co.ke/api/sasapay",
            "channel" => "mobile"
        ];

        $headers = [
            'Content-Type: application/json',
            'Authorization: ' . $basicAuthToken
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $this->apiUrl,
            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 => json_encode($data),
            CURLOPT_HTTPHEADER => $headers,
        ]);

        $response = curl_exec($curl);
        $error = curl_error($curl);

        curl_close($curl);

        if ($error) {
            return ['error' => $error];
        } else {
            $decodedResponse = json_decode($response, true);

            // Check for success or failure
            if (isset($decodedResponse['status']) && $decodedResponse['status'] == 'QUEUED' && isset($decodedResponse['response_code']) && $decodedResponse['response_code'] == '0') {
                // Payment successful
                return ['success' => true, 'data' => $decodedResponse];
            } else {
                // Payment failed
                return ['success' => false, 'data' => $decodedResponse];
            }
        }
    }

    protected function generateBasicAuthToken()
    {
        // Concatenate username and password with colon
        $credentials = $this->apiUsername . ':' . $this->apiPassword;
        // Base64 encode the credentials
        $encodedCredentials = base64_encode($credentials);
        // Creating the Basic Auth token
        return 'Basic ' . $encodedCredentials;
    }
       
       
       //end of the implementation

}
