<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");

header("Content-Type: application/json");

$num = isset($_POST['num']) ? $_POST['num'] : '';
$slatlist = isset($_POST['slatlist']) ? $_POST['slatlist'] : '';
$response = ['success' => false];

if ($num && $slatlist) {
    try {
        $pdo = db_connect();

        // Fetch the existing slatlist from the database
        $sql = "SELECT slatlist FROM chandj.output WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();
        $existingslatlist = $stmh->fetch(PDO::FETCH_ASSOC)['slatlist'];
        $existingslatlist = json_decode($existingslatlist, true);

        $updatedslatlist = json_decode($slatlist, true);

        // Update the existing slatlist with new data
        foreach ($updatedslatlist as $index => $update) {
            if (isset($existingslatlist[$index])) {
                foreach ($update as $key => $value) {
                    // Update only the fields that are expected to change (e.g., checkboxes)
                    if (array_key_exists($key, $existingslatlist[$index]) && strpos($key, '_check') !== false) {
                        $existingslatlist[$index][$key] = $value;
                    }
                }
            }
        }

        // Convert the updated slatlist back to a JSON string and save it in the database
        $sql = "UPDATE chandj.output SET slatlist = ? WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, json_encode($existingslatlist), PDO::PARAM_STR);        
        $stmh->bindValue(2, $num, PDO::PARAM_INT);
        if ($stmh->execute()) {
            $response['success'] = true;
        } else {
            $response['message'] = "Failed to update the database.";
        }
    } catch (PDOException $e) {
        $response['message'] = "Error: " . $e->getMessage();
    }
}

echo json_encode($response);
?>
