<?php
// put_guiderail_image.php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    sleep(1);
    header("HTTP/1.1 403 Forbidden");
    exit;
}

$jsonFile = $_SERVER['DOCUMENT_ROOT'] . '/guiderail/guiderail.json';

// POST 필드
$firstitem      = trim($_POST['firstitem']      ?? '');
$UA              = trim($_POST['UA']            ?? '');
$model_name     = trim($_POST['model_name']     ?? '');
$check_type     = trim($_POST['check_type']     ?? '');
$finishing_type = trim($_POST['finishing_type'] ?? '');
$search_keyword = trim($_POST['search_keyword'] ?? '');
// overwrite 용 index
$index          = isset($_POST['index']) ? intval($_POST['index']) : null;

// JSON 읽기
$guiderailData = [];
if (file_exists($jsonFile)) {
    $json = file_get_contents($jsonFile);
    $guiderailData = json_decode($json, true) ?: [];
}

// 이미지 업로드
$imagePath = '';
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/guiderail/images/';
if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);

if (isset($_FILES['upfile']) && $_FILES['upfile']['error'] === UPLOAD_ERR_OK) {
    $orig = $_FILES['upfile']['name'];
    $tmp  = $_FILES['upfile']['tmp_name'];
    $info = pathinfo($orig);
    $name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $info['filename']);
    $new  = date("Y_m_d_H_i_s") . "_{$name}" . (!empty($info['extension']) ? ".{$info['extension']}" : '');
    $dest = $uploadDir . $new;
    if (!move_uploaded_file($tmp, $dest)) {
        echo json_encode(['error' => '파일 업로드 실패']);
        exit;
    }
    $imagePath = '/guiderail/images/' . $new;
} else {
    echo json_encode(['error' => '업로드된 이미지가 없습니다']);
    exit;
}

// 새 항목 배열
$newItem = [
    'firstitem'      => $firstitem,
    'UA'             => $UA,
    'model_name'     => $model_name,
    'check_type'     => $check_type,
    'finishing_type' => $finishing_type,
    'search_keyword' => $search_keyword,
    'image'          => $imagePath
];

// 덮어쓰기 or 신규 추가
if ($index !== null && isset($guiderailData[$index])) {
    $guiderailData[$index] = $newItem;
} else {
    $guiderailData[] = $newItem;
}

// JSON 저장
if (false === file_put_contents(
    $jsonFile,
    json_encode($guiderailData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
)) {
    echo json_encode(['error' => 'JSON 저장 실패']);
    exit;
}

// 성공 응답
echo json_encode([
    'success'   => true,
    'imagePath' => $imagePath
]);
