<?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('sapdatafetch');
ini_set('memory_limit', '2048M');
ini_set('max_execution_time', '1000');
ini_set('max_input_time', '1000');
if (isset($_POST['fetch_data'])) {
    $curl = curl_init();
    
    // Updated API URL and parameters
    $todaysDate = date('Ymd');
    $fromDate = date('Ymd', strtotime('-45 days'));
    $api_url = "http://117.247.179.120:9049/vkc/po/sbu/pending-order?fromdate={$fromDate}&todate={$todaysDate}";
    
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => $api_url,
        CURLOPT_USERAGENT => 'Github API in CURL'
    ]);
    $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();
    }

    // Truncate the existing table before inserting new data
    $truncate_sql = "TRUNCATE TABLE podetails";
    if (!$db->query($truncate_sql)) {
        $session->msg("d", "Failed to truncate the table."); // Replace with your error message
    }

    foreach ($data['data'] as $item) {
        $sbu =  remove_junk($db->escape($item['SBU']));
        $sap_code =  remove_junk($db->escape($item['SAP_Code']));
        $description =  remove_junk($db->escape($item['Material_Description']));
        $uom =  remove_junk($db->escape($item['UOM']));
        $pending_qty =  remove_junk($db->escape($item['Pending_PO_Qty']));
        $from_date = $fromDate;
        $to_date = $todaysDate;

        // Insert data into the new table
        $sql = "INSERT INTO podetails (sbu, sap_code, description, uom, pending_qty, from_date, to_date)
                VALUES ('{$sbu}', '{$sap_code}', '{$description}', '{$uom}', '{$pending_qty}', '{$from_date}', '{$to_date}')";

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

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

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

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