<?php
$page_title = 'Fetch Data';
require_once('includes/load.php');
// Check what level user has permission to view this page
page_require_level(1);

$all_articles = find_all('sapfetcharticles');
ini_set('memory_limit', '2048M');
ini_set('max_execution_time', '1000');
ini_set('max_input_time', '1000');

$latestTimestamp = ""; // Variable to store the latest timestamp

if (isset($_POST['fetch_data'])) {
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://103.119.255.34:9098/external/api/whs',
        CURLOPT_USERAGENT => 'API Client'
    ]);
    $response = curl_exec($curl);
    curl_close($curl);

    $data = json_decode($response, true);
    if (!$data || !isset($data['data'])) {
        // Handle response error
        echo "Error: Invalid response from API endpoint";
        exit();
    }

    foreach ($data['data'] as $item) {
        $unitname = remove_junk($db->escape($item['UNITNAME']));
        $itemcode = remove_junk($db->escape($item['ITEMCODE']));
        $itemname = remove_junk($db->escape($item['ITEMNAME']));
        $quantity = remove_junk($db->escape($item['CBQTY']));

        // Replace with your database table name and column names
        $sql = "INSERT INTO sapfetcharticles (unitname, itemcode, itemname, quantity)
                VALUES ('{$unitname}', '{$itemcode}', '{$itemname}', '{$quantity}')";

        if (!$db->query($sql)) {
            $session->msg("d", "Sorry, failed to insert."); // Replace with your error message
        }
    }

    // Get the latest timestamp from the database
    $sql = "SELECT MAX(updated_at) AS last_updated FROM sapfetcharticles";
    $result = $db->query($sql);
    $row = $db->fetch_assoc($result);
    $latestTimestamp = $row['last_updated'];
}
?>

<?php include_once('layouts/header.php'); ?>

<form method="post">
    <button type="submit" name="fetch_data">Fetch Data</button>
</form>

<?php
if (!empty($latestTimestamp)) {
    echo "<p>Last Updated: $latestTimestamp</p>";
}
?>

<?php include_once('layouts/footer.php'); ?>
