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

$num = $_POST['num'] ?? '';
$mode = $_POST['mode'] ?? '';
$tablename = 'KDunitprice';

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

$row = [
    "prodcode" => "",
    "item_name" => "",
    "item_div" => "",
    "spec" => "",
    "unit" => "",
    "unitprice" => "",
    "searchtag" => "",
    "update_log" => ""
];

if ($mode === 'update' && $num !== '') {
    try {
        $sql = "SELECT * FROM {$DB}.{$tablename} WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);
        if (is_numeric($row['unitprice'])) {
            $row['unitprice'] = number_format($row['unitprice']);
        }
    } catch (PDOException $e) {
        echo "DB 오류: " . $e->getMessage();
        exit;
    }
} else if ($mode === 'copy' && $num !== '') {
    try {
        $sql = "SELECT * FROM {$DB}.{$tablename} WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);
        if (is_numeric($row['unitprice'])) {
            $row['unitprice'] = number_format($row['unitprice']);
        }
        $num = '';
        $row['update_log'] = '';
    } catch (PDOException $e) {
        echo "DB 오류: " . $e->getMessage();
        exit;
    }
}

// item_div 목록 로딩
$itemDivList = [];
$unitList = [];
try {
    $sql = "SELECT DISTINCT item_div FROM {$DB}.{$tablename} WHERE item_div IS NOT NULL AND item_div != ''";
    $stmt = $pdo->query($sql);
    $itemDivList = $stmt->fetchAll(PDO::FETCH_COLUMN);

    $sql2 = "SELECT DISTINCT unit FROM {$DB}.{$tablename} WHERE unit IS NOT NULL AND unit != ''";
    $stmt2 = $pdo->query($sql2);
    $unitList = $stmt2->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    echo "오류: " . $e->getMessage();
}

$title = '단가 신규 등록';
if ($mode === 'update') {
    $title = '단가 수정';
} else if ($mode === 'copy') {
    $title = '단가 복사';
}
?>

<div class="container-fluid">
    <div class="d-flex align-items-center justify-content-center">
        <div class="card">
            <div class="card-header text-center">
                <span class="fs-5 fw-bold"><?=$title?></span>
            </div>
            <div class="card-body">
                <input type="hidden" id="mode" name="mode" value="<?=$mode?>">
                <input type="hidden" id="num" name="num" value="<?=$num?>">
                <input type="hidden" class="form-control" name="searchtag" id="searchtag" value="<?=htmlspecialchars($row['searchtag'])?>">
                <input type="hidden" class="form-control" name="update_log" id="update_log" value="<?=htmlspecialchars($row['update_log'])?>">
                <table class="table table-bordered">
                    <tbody>
                        <tr>
                            <td class="text-center fw-bold">품목코드</td>
                            <td colspan="3">
                                <input type="text" class="form-control" name="prodcode" id="prodcode" value="<?=htmlspecialchars($row['prodcode'])?>" autocomplete="off">
                            </td>
                        </tr>
                        <tr>
                            <td class="text-center fw-bold">품목명</td>
                            <td>
                                <input type="text" class="form-control" name="item_name" id="item_name" value="<?=htmlspecialchars($row['item_name'])?>" autocomplete="off">
                            </td>
                            <td class="text-center fw-bold">품목구분</td>
                            <td>
                                <select class="form-select" name="item_div" id="item_div">
                                    <option value="">선택</option>
                                    <?php foreach ($itemDivList as $div): ?>
                                        <option value="<?=$div?>" <?=($row['item_div'] == $div) ? 'selected' : ''?>><?=$div?></option>
                                    <?php endforeach; ?>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td class="text-center fw-bold">규격</td>
                            <td>
                                <input type="text" class="form-control" name="spec" id="spec" value="<?=htmlspecialchars($row['spec'])?>" autocomplete="off">
                            </td>
                            <td class="text-center fw-bold">단위</td>
                            <td>
                                <select class="form-select" name="unit" id="unit">
                                    <option value="">선택</option>
                                    <?php foreach ($unitList as $unit): ?>
                                        <option 
                                            value="<?= htmlspecialchars($unit) ?>" 
                                            <?= (strcasecmp($row['unit'], $unit) === 0) ? 'selected' : '' ?>
                                        >
                                            <?= htmlspecialchars($unit) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </td>

                        </tr>
                        <tr>
                            <td class="text-center fw-bold">단가</td>
                            <td>
                                <input type="text" class="form-control text-end" name="unitprice" id="unitprice" value="<?=htmlspecialchars($row['unitprice'])?>" onkeyup="inputNumberFormat(this)" autocomplete="off">
                            </td>
                            <td class="text-center fw-bold">검색태그</td>
                            <td>
                                <span class="text-muted">자동 생성됩니다</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
