<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
require_once('../lib/dbclass.php');

extract($_POST);
$data = $_REQUEST;


$ReceivedAmount = trim($data['Amount']);
$volunteerid    = $data['userid'];


$datasave['userid'] = $volunteerid;

$id      = saveArray('ca_receipt', $datasave, 0);
$orderId = rand(10, 10000) . $id;

updateQuery("UPDATE ca_receipt 
                         SET 
                             amount=0,payable=$ReceivedAmount,orderid=$orderId
                              WHERE id=$id");



$datareceipt   = findQuery("SELECT * FROM tbl_user WHERE `id` =$volunteerid");
$volunteername = $datareceipt[0]['name'];


function containsNonEnglishCharacters($string)
{
    return preg_match('/[^\x20-\x7E]/', $string) ? 1 : 0;
}

function hashCalculate($salt, $input)
{
    $hash_columns = ['address_line_1', 'address_line_2', 'amount', 'api_key', 'city', 'country', 'currency', 'description', 'email', 'mode', 'name', 'order_id', 'phone', 'return_url', 'state', 'udf1', 'udf2', 'udf3', 'udf4', 'udf5', 'zip_code'];
    sort($hash_columns);
    $hash_data = $salt;

    foreach ($hash_columns as $column) {
        if (!empty($input[$column])) {
            $hash_data .= '|' . trim($input[$column]);
        }
    }

    return strtoupper(hash('sha512', $hash_data));
}



// Prepare hash
$name = containsNonEnglishCharacters($volunteername) ? 'name' : $volunteername;
$salt = SALT;


// Determine payment mode safely
$mode = (!empty($data['mode']) && intval($data['mode']) > 0) ? 'LIVE' : 'ios_sdk|LIVE';


$paymentFields = [
    'address_line_1' => 'ad1',
    'address_line_2' => 'ad2',
    'amount'         => $ReceivedAmount,
    'api_key'        => APIKEY,
    'city'           => CITY,
    'country'        => 'IND',
    'currency'       => 'INR',
    'description'    => DESCRIPTION,
    'email'          => EMAIL,
    'mode'           => $mode,
    'name'           => $name,
    'order_id'       => $orderId,
    'phone'          => PHONE,
    'return_url'     => 'http://localhost:8888/paymentresponse',
    'state'          => 'kerala',
    'zip_code'       => ZIPCODE,
    'udf1'           => $name,
    'udf2'           => $datareceipt[0]['mobile'],
    'udf3'           => $orderId,

];



$hash = hashCalculate($salt, $paymentFields);



// Final response
$status = ($id) ? 'True' : 'False';
echo json_encode([
    'Status'   => $status,
    'data'     => $id,
    'order_id' => $orderId,
    'hash'     => $hash,
    'name'     => $name,
    'mobile'   => $datareceipt[0]['mobile'],
]);


return;
?>	   


