<?php 
include('../../Connections/repnew.php'); 
include('../include/headscript.php');
include("../class/company.php");

$conn = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// two methods save and load data
if ($_POST['method'] == 'save') {
    $order = $_POST['order'];
    $user_id = $iduserlogin;
    // check if user already have order
    $order = implode(',', $order);
    $sql = "SELECT * FROM chart_order WHERE user_id = $user_id";
    $result = $conn->query($sql); 
    if ($result->num_rows > 0) {
        $sql = "UPDATE chart_order SET `order` = '$order' WHERE user_id = $user_id";
    } else {
        $sql = "INSERT INTO chart_order (`user_id`, `order`) VALUES ($user_id, '$order')";
    }  
    $conn->query($sql);
    echo 'Data saved';
    
} else if($_POST['method'] == 'load') {
    $sql = "SELECT `order` FROM chart_order WHERE user_id = $iduserlogin ORDER BY insert_date DESC LIMIT 1";
    $result = $conn->query($sql);
    if($result->num_rows == 0) {
        echo json_encode([]);
        return;
    }else{ 
        $row = $result->fetch_assoc(); 
        $order_list = explode(',', $row['order']);
        echo json_encode($order_list);
    }
}