<?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', '1000000');
ini_set('max_input_time', '100000');
if (isset($_POST['fetch_data'])) {
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => 'http://117.247.179.120:9049/external/api/allDbstock',
        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();
    }

    foreach ($data['data'] as $item) {
        $sap_code =  remove_junk($db->escape($item['SAP_CODE']));
        $main_category =  remove_junk($db->escape($item['MAIN_CATEGORY']));
        $sub_category =  remove_junk($db->escape($item['SUB_CATEGORY']));
        $description =  remove_junk($db->escape($item['MATERIAL_DESCRIPTION']));
        $closing_stock =  remove_junk($db->escape($item['CLOSING_STOCK']));
        $sbu =  remove_junk($db->escape($item['SBU']));

        // Replace with your database table name and column names
        $sql = "INSERT INTO sapdatafetch (sap_code, main_category, sub_category, description, closing_stock, sbu)
                VALUES ('{$sap_code}', '{$main_category}', '{$sub_category}', '{$description}', '{$closing_stock}', '{$sbu}')
                ON DUPLICATE KEY UPDATE main_category='{$main_category}', sub_category='{$sub_category}', description='{$description}', closing_stock='{$closing_stock}', sbu='{$sbu}'";

        if (!$db->query($sql)) {
            $session->msg("d", "Sorry 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'); ?>