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


ini_set('memory_limit', '-1');
ini_set('max_execution_time', '-1');
ini_set('max_input_time', '-1');
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/bom',
        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) {
        $sbu =  remove_junk($db->escape($item['SBU']));
        $father =  remove_junk($db->escape($item['Father']));
        $father_name =  remove_junk($db->escape($item['Father_Name']));
        $fathernoofpairs =  remove_junk($db->escape($item['fathernoofpairs']));
        $father_qty =  remove_junk($db->escape($item['Father_Qty']));
        $child =  remove_junk($db->escape($item['Child']));
        $child_name =  remove_junk($db->escape($item['Child_Name']));
        $child_qty =  remove_junk($db->escape($item['Child_Qty']));
        $process =  remove_junk($db->escape($item['Process']));
        $process_order =  remove_junk($db->escape($item['Process_Order']));
        // Replace with your database table name and column names
        $sql = "INSERT INTO sourcedatatable (`SBU`, `Father`, `Father Name`, `Father No of pairs`, `Father Qty`, `Child`, `Child Name`, `Child Qty`, `Process`, `Process Order`)
                VALUES ('{$sbu}', '{$father}', '{$father_name}', '{$fathernoofpairs}', '{$father_qty}', '{$child}', '{$child_name}','{$child_qty}','{$process}','{$process_order}')";

        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'); ?>