<?php
use GuzzleHttp\Client;

function easebuzzInitiatePayment($studentData, $pg_setup, $amount, $api_url, $userid, $paymentGatewayCredentialKey, $conn_rjllearning)
{
    global $conn_rjllearning_specific, $workspace_id;

    $pg_credentials = json_decode(aes128Decrypt($pg_setup['credentials'], $paymentGatewayCredentialKey), true);

    if (empty($pg_credentials['key']) || empty($pg_credentials['salt'])) {
        errorreturn("Incomplete Easebuzz credentials.");
    }
    
    $txnid = $workspace_id . '_' . $studentData['institution_id'] . '_' . $studentData['branch_id'] . '_' . $studentData['admission_number'] . '_' . time();
    $amount = number_format((float)$amount, 2, '.', '');
    $productinfo = $studentData['productinfo'] ?? 'Tuition Fee';
    $firstname = $studentData['firstname'] ?? $studentData['name'] ?? 'Student';
    $email = $studentData['email'] ?? 'email@example.com';
    $phone = $studentData['mobile'] ?? '9999999999';
    $surl = $pg_setup['return_url'];
    $furl = $pg_setup['return_url'];
    
    $section_name=getSection($conn_rjllearning_specific, $studentData['institution_id'], $studentData['section_id']);
    $class_info=getClass($conn_rjllearning_specific, $studentData['institution_id'], $studentData['class_id']);
    $branch_name=getBranchInfo($conn_rjllearning_specific, $studentData['institution_id'], $studentData['branch_id'], $additional_data =  null);

    // // UDF fields
    
    // Map existing fields into udf keys
        $studentData['udf1'] = $phone ?? '';
        $studentData['udf2'] = $branch_name['name'] ?? '';
        $studentData['udf3'] = $class_info['class_name'] ?? '';
        $studentData['udf4'] = $section_name['section_name'] ?? '';
        // fill more udf if needed or leave blank
        $studentData['udf5'] = $studentData['admission_number'] ?? '';
        $studentData['udf6'] = $studentData['fathername'] ?? '';
        $studentData['udf7'] = '';
        $studentData['udf8'] = '';
        $studentData['udf9'] = '';
        $studentData['udf10'] = '';
        
        // Now run your original loop
        $udf = [];
        for ($i = 1; $i <= 10; $i++) {
            $udf["udf$i"] = $studentData["udf$i"] ?? '';
        }
        
        // Then build your hash
        $hashSequence = implode('|', [
            $pg_credentials['key'], $txnid, $amount, $productinfo, $firstname, $email,
            $udf['udf1'], $udf['udf2'], $udf['udf3'], $udf['udf4'], $udf['udf5'],
            $udf['udf6'], $udf['udf7'], $udf['udf8'], $udf['udf9'], $udf['udf10'],
            $pg_credentials['salt']
        ]);

    $hash = strtolower(hash('sha512', $hashSequence));

    // Prepare post data
    $postData = [
        'key' => $pg_credentials['key'],
        'txnid' => $txnid,
        'amount' => $amount,
        'productinfo' => $productinfo,
        'firstname' => $firstname,
        'email' => $email,
        'phone' => $phone,
        'surl' => $surl,
        'furl' => $furl,
        'hash' => $hash,
        'unique_id' => $txnid
    ] + $udf;

    $optionalFields = ['address1', 'address2', 'city', 'state', 'country', 'zipcode', 'show_payment_mode', 'split_payments', 'request_flow', 'sub_merchant_id', 'payment_category', 'account_no', 'ifsc'];
    foreach ($optionalFields as $field) {
        if (!empty($studentData[$field])) {
            $postData[$field] = $studentData[$field];
        }
    }

    try {
        $client = new Client();
        $response = $client->request('POST', 'https://pay.easebuzz.in/payment/initiateLink', [
            'form_params' => $postData,
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/x-www-form-urlencoded',
            ]
        ]);

        $responseBody = json_decode($response->getBody(), true);
    
        if (!isset($responseBody['status']) || $responseBody['status'] != 1) {
            errorreturn("Easebuzz Error: " . ($responseBody['data'] ?? 'Unknown error'));
        }
        
        $payment_data = [
        "hash" => $responseBody['data'],
        "pg_url" => "https://pay.easebuzz.in/v2/pay"
    ];

    insertInitiatedTransaction($conn_rjllearning, $workspace_id, $studentData['institution_id'], $studentData['branch_id'], $pg_setup['id'], $txnid, $amount);

        // Match CCAvenue-style return structure
        successreturn([
            'order_id' => $txnid,
            'white_label_url' => $api_url,
            'json_encoded_data' => $payment_data,
            'gateway' => 'easebuzz'
        ]);
    } catch (Exception $e) {
        errorreturn("Exception: " . $e->getMessage());
    }
}


function handleEasebuzzResponse($data, $pg_vendor, $workspace_id, $institution_id, $branch_id, $conn_rjllearning) {
    global $paymentGatewayCredentialKey;

    try {
        // Decode and validate Easebuzz credentials (if needed)
        $pg_credentials = json_decode(aes128Decrypt($pg_vendor['credentials'], $paymentGatewayCredentialKey), true);

        if (empty($pg_credentials['key']) || empty($pg_credentials['salt'])) {
            return errorreturn("Incomplete Easebuzz credentials.");
        }

        // Check if txnid and status exist
        if (!isset($data['txnid'], $data['status'])) {
            return errorreturn("Invalid Easebuzz response.");
        }

        $order_id = $data['txnid'];
        $status_string = $data['status'];
        $easepayid = $data['easepayid'] ?? 'NA';
        $failure_msg = $data['error_Message'] ?? 'No error message';
        $amount = $data['amount'] ?? 0;

        $remarks = "Easebuzz response for order_id: $order_id. Status: $status_string. Failure: $failure_msg";
        $status = ($status_string === 'success') ? 1 : (($status_string === 'userCancelled' || $status_string === 'failure') ? -1 : 0);

        if($status == 1) {
            $transaction_data = [
                'order_id' => $order_id,
                'amount' => $amount,
                'payment_gateway' => "easebuzz",
            ];
            
            $parts = explode('_', $order_id);
            $student_id = $parts[3];
    
            $create_finware_transaction_response = createPaymentGatewayTransactionFinware($conn_rjllearning,$workspace_id, $institution_id, $student_id, $transaction_data, $branch_id, 'common_response.php'); // admission number is sent in student id her

        } else {
            $sql = "UPDATE initiated_transactions set finware_verification = ? where workspace_id = ? and institution_id = ? and order_id = ?";
            $update = $conn_rjllearning->prepare($sql);
            // update initiated_transactions with negative response
            $update->execute(array(-1, $workspace_id, $institution_id, $order_id));
        }


        // Insert into transactions
        $insert = $conn_rjllearning->prepare("INSERT INTO transactions 
            (workspace_id, institution_id, branch_id,amount, gateway_id, reference_no, remarks, status, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, ?,?, NOW(), NOW())");

        $insert->execute([
            $workspace_id,
            $institution_id,
            $branch_id,
            $amount,
            $pg_vendor['id'],
            $order_id,
            $remarks,
            $status
        ]);

        if ($insert->rowCount() === 0) {
            return errorreturn("Failed to insert transaction for order_id: $order_id");
        }
        $sql = "UPDATE initiated_transactions set status = ? where workspace_id = ? and institution_id = ? and order_id = ?";
        $update = $conn_rjllearning->prepare($sql);
        // update initiated_transactions with positive response
        $update->execute(array(1, $workspace_id, $institution_id, $order_id));

        return [
            'status' => 1,
            'message' => 'Easebuzz transaction processed successfully',
            'order_id' => $order_id,
            'remarks' => $remarks,
            'gateway_status' => $status
        ];

    } catch (Exception $e) {
        return errorreturn("Exception during processing Easebuzz response: " . $e->getMessage());
    }
}


function checkEasebuzzStatus($order_id) {
    global $conn_rjllearning;
    global $paymentGatewayCredentialKey;

    $parts = explode('_', $order_id);
    if (count($parts) < 5) {
        errorreturn("Invalid order_id format");
    }

    list($workspace_id, $institution_id, $branch_id, $student_id, $unique_id) = $parts;

    // Step 1: Fetch PG vendor
    $stmt = $conn_rjllearning->prepare("SELECT id, pg_vendor, credentials 
                                        FROM payment_gateway_setup 
                                        WHERE workspace_id = ? AND institution_id = ? AND branch_id = ? and status = 1 
                                        LIMIT 1");
    $stmt->execute([$workspace_id, $institution_id, $branch_id]);
    $pg_vendor = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$pg_vendor) {
        errorreturn("PG Vendor not found for this branch");
    }

    // Step 2: Decrypt Easebuzz credentials
    $pg_credentials = json_decode(aes128Decrypt($pg_vendor['credentials'], $paymentGatewayCredentialKey), true);
    if (empty($pg_credentials['key']) || empty($pg_credentials['salt'])) {
        errorreturn("Incomplete Easebuzz credentials.");
    }

    $key = $pg_credentials['key'];
    $salt = $pg_credentials['salt'];
    $txnid = $order_id;

    // Step 3: Generate hash
    $hash_input = $key . '|' . $txnid . '|' . $salt;
    $hash = hash('sha512', $hash_input);

    try {
        $client = new \GuzzleHttp\Client();

        $response = $client->request('POST', 'https://dashboard.easebuzz.in/transaction/v2.1/retrieve', [
            'form_params' => [
                'txnid' => $txnid,
                'key'   => $key,
                'hash'  => $hash
            ],
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
        ]);

        $body = $response->getBody()->getContents();
        $result = json_decode($body, true);

        if (!isset($result['status']) || !isset($result['msg'][0])) {
            errorreturn("Invalid or empty response from Easebuzz");
        }

        $txn_data = $result['msg'][0];
        
        
        

        $gateway_status = $txn_data['status'] ?? '';
        $status = ($gateway_status === 'success') ? 1 : -1;
        $order_status = ($gateway_status === 'success') ? 'Successful' : 'Notsuccessful';
        $amount = $txn_data['amount'];
        
        
        // verify if it is already verified in initiated transaction
        if(!checkFinwareStatusInitiatedTransaction($conn_rjllearning, $workspace_id, $institution_id, $order_id)) {
            if($status == 1) {
                $transaction_data = [
                    'order_id' => $order_id,
                    'amount' => $txn_data['amount'],
                    'payment_gateway' => "easebuzz",
                ];
        
                $create_finware_transaction_response = createPaymentGatewayTransactionFinware($conn_rjllearning,$workspace_id, $institution_id, $student_id, $transaction_data, $branch_id, 'status_check_api'); // admission number is sent in student id her
            } else {
                $sql = "UPDATE initiated_transactions set finware_verification = ? where workspace_id = ? and institution_id = ? and order_id = ?";
                $update = $conn_rjllearning->prepare($sql);
                // update initiated_transactions with negative response
                $update->execute(array(-1, $workspace_id, $institution_id, $order_id));
            }
        }
        
        // verify if it is already verified in initiated transaction
        if(!checkTransactionStatusLearningTable($conn_rjllearning, $workspace_id, $institution_id, $order_id)) {
            // Insert into transactions
            $insert = $conn_rjllearning->prepare("INSERT INTO transactions 
                (workspace_id, institution_id, branch_id,amount, gateway_id, reference_no, remarks, status, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, ?, ?,?, NOW(), NOW())");
    
            $insert->execute([
                $workspace_id,
                $institution_id,
                $branch_id,
                $amount,
                $pg_vendor['id'],
                $order_id,
                'Order Id : ' . $order_id,
                $status
            ]);
    
            if ($insert->rowCount() === 0) {
                return errorreturn("Failed to insert transaction for order_id: $order_id");
            }
            $sql = "UPDATE initiated_transactions set status = ? where workspace_id = ? and institution_id = ? and order_id = ?";
            $update = $conn_rjllearning->prepare($sql);
            // update initiated_transactions with positive response
            $update->execute(array(1, $workspace_id, $institution_id, $order_id));
        }
        
        

        
        
        return [
            'name' => $txn_data['firstname'] ?? '',
            'email' => $txn_data['email'] ?? '',
            'country' => $txn_data['m_country'] ?? '',
            'phone' => $txn_data['phone'] ?? '',
            'branch' => $txn_data['udf2'] ?? '',
            'class' => $txn_data['udf3'] ?? '',
            'section' => $txn_data['udf4'] ?? '',
            'admission_number' => $student_id,
            'status' => $status,
            'txn_id' => $txn_data['easepayid'] ?? '',
            'order_status' => $order_status,
            'amount' => $txn_data['amount'] ?? '',
            'payment_date' => $txn_data['addedon'] ?? date('Y-m-d H:i:s'),
            'vendor_ref' => $txn_data['bank_ref_num'] ?? '',
            'order_no' => $txnid,
            'order_bank_response' => $txn_data['status'] ?? '',
        ];

    } catch (\GuzzleHttp\Exception\RequestException $e) {
        errorreturn("Easebuzz API request failed: " . $e->getMessage());
    }
}
