<?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'] : '';
$screenlist = isset($_POST['screenlist']) ? $_POST['screenlist'] : '';

$response = ['success' => false];

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

        // 기존의 screenlist를 가져와서 업데이트
        $sql = "SELECT screenlist FROM chandj.output WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();
        $existingScreenlist = $stmh->fetch(PDO::FETCH_ASSOC)['screenlist'];
        $existingScreenlist = json_decode($existingScreenlist, true);

        $updatedScreenlist = json_decode($screenlist, true);

        // 배열의 순서대로 업데이트
        foreach ($updatedScreenlist as $index => $update) {
            if (isset($existingScreenlist[$index])) {
                $existingScreenlist[$index] = array_merge($existingScreenlist[$index], $update);
            }
        }

        // 업데이트된 screenlist를 다시 JSON 문자열로 변환하여 저장
        $sql = "UPDATE chandj.output SET screenlist = ? WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, json_encode($existingScreenlist), PDO::PARAM_STR);
        $stmh->bindValue(2, $num, PDO::PARAM_INT);
        $stmh->execute();

        $response['success'] = true;
    } catch (PDOException $e) {
        $response['message'] = "Error: " . $e->getMessage();
    }
}

echo json_encode($response);
?>
