<?php

session_start();
require '../lib/dbclass.php';



$datas = findQuery(
    'SELECT * FROM tbl_challenge WHERE status=0 AND CURDATE() between challenge_startdate and challenge_enddate'
);

if ($datas) {
    $clubid  = $_POST['clubid'] ? $_POST['clubid'] : 0;
    $Amount  = $_POST['Amount'];
    $orderid = $_POST['orderid'];

    unset($_POST['Amount']);
    unset($_POST['clubid']);
    unset($_POST['orderid']);

    if ($datas[0]['product_amount1'] > 0) {
        $price_per_item = $datas[0]['product_amount1'];

        $quantity = floor($Amount / $price_per_item);





        $custid = saveArray('tbl_customer', $_POST, 0); //customer save

        $_POST_HDR['clubid']                   = $clubid;
        $_POST_HDR['challengeid']              = $datas[0]['id'];
        $_POST_HDR['customerid']               = $custid;
        $_POST_HDR['orderid']                  = $orderid;
        $_POST_HDR['Amount']                   = $Amount;
        $_POST_HDR['Received']                 = 0;
        $_POST_HDR['uniquedid']                = '0ebdbfdcb3087511bef20bb0f8751f2808e27d12a7f595c3ae8b28b022203aca';
        $_POST_HDR['is_Razor_payment_gateway'] = 2;


        $hdrid = saveArray('tbl_transaction', $_POST_HDR, 0); //transaction save

        if ($quantity > 0) {
            $_POST_DTL['hdrid']  = $hdrid;
            $_POST_DTL['item']   = $datas[0]['id'];
            $_POST_DTL['qty']    = $quantity;
            $_POST_DTL['Totqty'] = $quantity;
            $_POST_DTL['rate']   = $price_per_item;
            $_POST_DTL['amount'] = $Amount;

            $hdrid = saveArray('tbl_transactiondetails', $_POST_DTL, 0); //transaction save
        }

        $message = 'Added successfully!';

        $encodedMessage = urlencode($message);

        $url = "challengereport.php?message={$encodedMessage}";

        // Redirect to the new URL
        echo "<script>window.location.href='{$url}';</script>";
    }
}
