<?php

require_once('../../lib/dbclass.php');

define('RAZORPAY_KEY_ID', 'rzp_live_ubJQvkRJBjSpvg');
define('RAZORPAY_KEY_SECRET', 'oNT1lfxjj4vVUTXSx34q675z');

function checkOrderStatus($orderId, $id)
{
    $orderUrl   = "https://api.razorpay.com/v1/orders/$orderId";
    $paymentUrl = "https://api.razorpay.com/v1/orders/$orderId/payments";

    $orderResponse = makeCurlRequest($orderUrl);

    if (!$orderResponse) {
        return false;
    }

    $orderDetails = json_decode($orderResponse, true);

    if (isset($orderDetails['error'])) {
        return false;
    }

    $status = $orderDetails['status'];

    if ($status != 'paid') {
        return false;
    }

    $paymentResponse = makeCurlRequest($paymentUrl);

    if (!$paymentResponse) {
        return false;
    }

    $paymentDetails = json_decode($paymentResponse, true);
    $paymentId      = null;

    $filteredPayments = array_filter($paymentDetails['items'], function ($payment) {
        return $payment['status'] == 'captured';
    });

    $filteredPayments = array_values($filteredPayments);



    if (!empty($filteredPayments)) {
        $paymentId = $filteredPayments[0]['acquirer_data']['rrn'];

        $transactionTime = $filteredPayments[0]['authorized_at'];

        if ($paymentId == '') {
            $paymentId = $filteredPayments[0]['id'];
        }

        $formattedTime = date('Y-m-d H:i:s', $transactionTime);
    }

    updateOrderStatus($orderId, $paymentId, $id, $formattedTime);

    return true;
}

function getorderid($Transactid, $tranid)
{
    $TransactUrl = "https://api.razorpay.com/v1/payments/ . $Transactid";

    $response = makeCurlRequest($TransactUrl);

    $payment_data = json_decode($response, true);

    $paymentId = $payment_data['acquirer_data']['rrn'];
    $order_id  = $payment_data['order_id'];

    $query = "UPDATE tbl_transaction SET Transid = '$paymentId',orderid='$order_id' WHERE id = $tranid";

    updateQuery($query);
}

function checkOrderStatusreceipt($orderId, $id)
{
    $TransactUrl = "https://api.razorpay.com/v1/payments/ . $orderId";

    $response = makeCurlRequest($TransactUrl);

    $payment_data = json_decode($response, true);

    if ($payment_data && isset($payment_data['acquirer_data']['rrn']) && isset($payment_data['order_id'])) {
        $paymentId = $payment_data['acquirer_data']['rrn'];
        $order_id  = $payment_data['order_id'];

        $query = "UPDATE ca_receipt SET transid = '$paymentId',orderid='$order_id' WHERE id = $id";

        updateQuery($query);
    }
}

function makeCurlRequest($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, RAZORPAY_KEY_ID . ':' . RAZORPAY_KEY_SECRET);
    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        curl_close($ch);

        return false;
    }

    curl_close($ch);

    return $response;
}

function updateOrderStatus($orderId, $paymentId, $id, $formattedTime)
{
    if (!$paymentId) {
        return;
    }

    $query = "UPDATE tbl_transaction SET Transid = '$paymentId',Received=Amount,dateadded='$formattedTime' WHERE id = $id";

    updateQuery($query);
}

$data = [];

$data = findQuery("SELECT * FROM tbl_transaction WHERE Transid = '' AND orderid != ''");

if ($data) {
    foreach ($data as $row) {
        $orderId = $row['orderid'];

        $id = $row['id'];
        checkOrderStatus($orderId, $id);
    }
}

$data = [];

$data = findQuery("SELECT * FROM tbl_transaction WHERE Transid!= '' AND orderid = ''");

if ($data) {
    foreach ($data as $row) {
        $Transactid = $row['Transid'];
        $tranid     = $row['id'];
        getorderid($Transactid, $tranid);
    }
}

$data = [];

$data = findQuery("SELECT * FROM `ca_receipt` where `transid`!='' and `orderid`=''");

if ($data) {
    foreach ($data as $row) {
        $orderId = $row['transid'];
        $id      = $row['id'];
        checkOrderStatusreceipt($orderId, $id);
    }
}

$data = [];

$data = findQuery("Select * FROM `tbl_transaction` WHERE `Transid` REGEXP '[^0-9]'");



if ($data) {
    foreach ($data as $row) {
        $orderId = $row['orderid'];

        $id = $row['id'];
        checkOrderStatus($orderId, $id);
    }
}

$todaydates = date('dmY');
$pass       = encrypt($todaydates);
updateQuery(
    "Update tbl_user set password='$pass' where user_type=1"
);
