<?php

include('API.php');
include('Crypto.php');
require_once 'config.php';
require('../lib/dbclass.php');
error_reporting(1);

$ccavenue_api = new CCAvenue_API();
// The API URL
$url = siteurl . 'API/checkstatus.php';

// Use cURL to fetch the data from the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

// Decode the JSON response
$data = json_decode($response, true);

// Check if the data is valid and loop through the result
if ($data) {
    foreach ($data['data'] as $index => $item) {
        $order_id      = $item['orderid'];
        $pendingorders = ['order_no' => $order_id];

        $response = trim($ccavenue_api->orderStatusTracker($pendingorders));

        $workingKey = CCA_WORKING_KEY; // Working Key should be provided here.

        // Crypto Decryption
        $rcvdString   = decryption($response, $workingKey);
        $order_status = '';

        $order = json_decode($rcvdString, true);


        $order_status = $order['order_status'];




        // Check for valid order status
        if ($order_status == 'Success' || $order_status == 'Shipped' || $order_status == 'Successful') {
            $Transaction_id  = $order['order_bank_ref_no'];
            $order_id        = $order['order_no'];
            $order_time      = new DateTime($order['order_date_time']);
            $order_date_time = $order_time->format('Y-m-d H:i:s');

            // Update query
            updateQuery("UPDATE tbl_transaction 
                         SET Transid='$Transaction_id', 
                             Received=Amount, 
                             is_Razor_payment_gateway=0, 
                             dateadded='$order_date_time' 
                         WHERE orderid='$order_id'");
        }
    }
}
