<?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');

function get_challenge_product_details($productId)
{
    if ($productId > 0) {
        $product = findQuery('SELECT * FROM `tbl_product` WHERE id=' . intval($productId));

        if (!empty($product)) {
            return [
                'id'   => $product[0]['id'],
                'rate' => $product[0]['amount'],
            ];
        }
    }

    return ['id' => 0, 'rate' => 0];
}

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','zip_code', 'udf1', 'udf2', 'udf3', 'udf4', 'udf5'];
    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));
}

$data = $_POST;



// Get current date for challenge lookup
$today     = date('Y-m-d');
$challenge = findQuery("SELECT * FROM `tbl_challenge` WHERE '$today' BETWEEN `challenge_startdate` AND `challenge_enddate` AND status = 0");

$productData = [];
for ($i = 1; $i <= 5; $i++) {
    $productData[$i] = get_challenge_product_details($challenge[0]["sponsorproductid$i"] ?? 0);
}



// Determine Panchayat and Ward
if (!empty($data['volunteer']) && intval($data['volunteer']) > 0) {
    $volunteer = intval($data['volunteer']);

    $volunteerData = findQuery("SELECT * FROM tbl_user WHERE id = $volunteer");
    $wardId        = $volunteerData[0]['ward_id'];

    $wardData    = findQuery("SELECT * FROM tbl_ward WHERE status = 0 AND id = $wardId");
    $panchayatId = $wardData[0]['panchayat_id'];
} else {
    $wardId      = intval($data['Ward']);
    $panchayatId = intval($data['Panchayat']);
    $volunteer   = 0;
}

$assemblyId = 0;
$districtId = 0;


if ($panchayatId > 0) {
    $panchayat  = findQuery("SELECT * FROM tbl_panchayat WHERE status = 0 AND id = $panchayatId");
    $assemblyId = $panchayat[0]['assembly_id'];
    $assembly   = findQuery("SELECT * FROM tbl_assembly WHERE status = 0 AND id = $assemblyId");
    $districtId = $assembly[0]['district'];
}

// Prepare customer data
$data_customer = [
    'name'      => $data['name'],
    'Address'   => $data['Address'],
    'Mobile'    => $data['Mobile'],
    'Photo'     => '',
    'Panchayat' => $panchayatId,
    'Ward'      => $wardId,
    'Assembly'  => $assemblyId,
    'District'  => $districtId,
];

// Handle image upload
/*if (!empty($data['isphoto']) && $data['isphoto'] == 1 && isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
    $target_dir = "images/";
    $filename = sha1($_FILES['image']['name'] . rand(0,999999));
    $target_file_name = $target_dir . $filename;
    if (move_uploaded_file($_FILES['image']['tmp_name'], $target_file_name)) {
        $data_customer['Photo'] = $target_file_name;
    } else {
        echo json_encode(["Status" => "False", "data" => ["error" => "Error uploading photo"]]);
        return;
    }
}
*/


$id_customer = saveArray('tbl_customer', $data_customer, 0);

if ($volunteer > 0) {
    $orderId = '';
} else {
    $orderId = rand(10, 10000000) . $id_customer;
}


$data_header = [
    'clubid'                   => $data['clubid'],
    'donation'                 => $data['donation'],
    'sponsorship'              => $data['sponsorship'],
    'challengeid'              => $data['challengeid'],
    'hideidendity'             => $data['hideidendity'],
    'uniquedid'                => $data['uniquedid'],
    'orderforothers'           => $data['orderforothers'],
    'name'                     => $data['custname'],
    'address'                  => $data['custaddress'],
    'mobile'                   => $data['custmobile'],
    'Amount'                   => $data['Amount'],
    'Received'                 => $data['Received'],
    'volunteer'                => $data['volunteer'],
    'is_Razor_payment_gateway' => 2,
    'customerid'               => $id_customer,
    'orderid'                  => $orderId,
];

$id_header = saveArray('tbl_transaction', $data_header, 0);

// Save transaction details if sponsorship
if (intval($data['sponsorship'] == 1)) {
    for ($i = 1; $i <= 5; $i++) {
        $qtyKey = $i == 1 ? 'qty' : 'qty' . ($i - 1);
        $qty    = isset($data[$qtyKey]) ? intval($data[$qtyKey]) : 0;

        if ($qty > 0 && $productData[$i]['id'] > 0) {
            $data_detail = [
                'hdrid'  => $id_header,
                'item'   => $productData[$i]['id'],
                'qty'    => $qty,
                'Totqty' => $qty,
                'rate'   => $productData[$i]['rate'],
                'amount' => $qty * $productData[$i]['rate'],
            ];
            saveArray('tbl_transactiondetails', $data_detail, 0);
        }
    }
}

// Save transaction details if not a donation but challenge
if (intval($data['donation']) == 0 && intval($data['sponsorship']) == 0) {
    for ($i = 1; $i <= 3; $i++) {
        $qtyKey = $i == 1 ? 'qty' : 'qty' . ($i - 1);
        $qty    = isset($data[$qtyKey]) ? intval($data[$qtyKey]) : 0;

        $amountKey     = 'product_amount' . $i;
        $conversionKey = 'productconversion' . $i;

        $productAmount = isset($challenge[0][$amountKey]) ? floatval($challenge[0][$amountKey]) : 0;
        $conversion    = isset($challenge[0][$conversionKey]) ? floatval($challenge[0][$conversionKey]) : 1;

        if ($qty > 0 && $productAmount > 0 && isset($productData[$i]['id']) && $productData[$i]['id'] > 0) {
            $data_detail = [
                'hdrid'  => $id_header,
                'item'   => $i,
                'qty'    => $qty,
                'Totqty' => $qty * $conversion,
                'rate'   => $productAmount,
                'amount' => $qty * $productAmount,
            ];
            saveArray('tbl_transactiondetails', $data_detail, 0);
        }
    }
}




// Prepare hash
$name           = containsNonEnglishCharacters($data['name']) ? 'name' : $data['name'];
$salt           = SALT;
$ReceivedAmount = trim($data['Amount']);

// 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'           => $data['Mobile'],
    'udf3'           => $orderId,
    'udf4'           => '',
    'udf5'           => '',
];



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



// Final response
$status = ($id_customer && $id_header) ? 'True' : 'False';
echo json_encode([
    'Status'   => $status,
    'data'     => $id_customer,
    'order_id' => $orderId,
    'hash'     => $hash,
    'name'     => $name,
]);

return;
