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

$pdo = db_connect();

// GET 파라미터 받기 - JavaScript에서 보내는 파라미터 이름과 일치
$selectedItem = $_GET['selectedItem'] ?? '';
$selectedUA = $_GET['selectedUA'] ?? '';
$selectedBendingCategory = $_GET['selectedBendingCategory'] ?? '';
$selectedName = $_GET['selectedName'] ?? '';
$selectedMaterial = $_GET['selectedMaterial'] ?? '';
$search = $_GET['search'] ?? '';

// SQL 쿼리 구성
$sql = "SELECT * FROM {$DB}.bending WHERE is_deleted IS NULL";
$params = [];

// 필터 (item_sep)
if (!empty($selectedItem)) {
    $sql .= " AND item_sep = :selectedItem";
    $params[':selectedItem'] = $selectedItem;
}

// 인정/비인정 필터 (model_UA)
if (!empty($selectedUA)) {
    $sql .= " AND model_UA = :selectedUA";
    $params[':selectedUA'] = $selectedUA;
}

// 중분류 필터 (item_bending)
if (!empty($selectedBendingCategory)) {
    $sql .= " AND item_bending = :selectedBendingCategory";
    $params[':selectedBendingCategory'] = $selectedBendingCategory;
}

// 품명 필터 (itemName)
if (!empty($selectedName)) {
    $sql .= " AND itemName = :selectedName";
    $params[':selectedName'] = $selectedName;
}

// 재질 필터 (material)
if (!empty($selectedMaterial)) {
    $sql .= " AND material = :selectedMaterial";
    $params[':selectedMaterial'] = $selectedMaterial;
}

// 검색어 필터 (모든 텍스트 필드에서 검색)
if (!empty($search)) {
    $searchTerm = '%' . $search . '%';
    $sql .= " AND (itemName LIKE :search_name OR material LIKE :search_material OR item_sep LIKE :search_sep OR item_bending LIKE :search_bending OR model_UA LIKE :selectedUA)";
    $params[':search_name'] = $searchTerm;
    $params[':search_material'] = $searchTerm;
    $params[':search_sep'] = $searchTerm;
    $params[':search_bending'] = $searchTerm;
    $params[':selectedUA'] = $searchTerm;
}


$sql .= " ORDER BY num DESC";

// 디버깅용 로그
error_log("Search SQL: " . $sql);
error_log("Search Params: " . print_r($params, true));

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// shutterbox.json 읽기
$jsonFile = $_SERVER['DOCUMENT_ROOT'].'/shutterbox/shutterbox.json';
$shutterboxData = [];
if (file_exists($jsonFile)) {
    $jsonContent = file_get_contents($jsonFile);
    $shutterboxData = json_decode($jsonContent, true);
    if (!is_array($shutterboxData)) $shutterboxData = [];
}

// 결과 출력
if (empty($results)) {
    echo '<tr><td colspan="9" class="text-center">검색 결과가 없습니다.</td></tr>';
} else {
    foreach ($results as $row) {
        $num = $row['num'];
        $itemName = $row['itemName'] ?? '';
        $material = $row['material'] ?? '';
        $item_sep = $row['item_sep'] ?? '';
        $item_bending = $row['item_bending'] ?? '';
        $model_UA = $row['model_UA'] ?? '';
        $imgdata = $row['imgdata'] ?? '';
        $widthsum = $row['widthsum'] ?? '';
        $exit_direction = $row['exit_direction'] ?? '';
        $front_bottom_width = $row['front_bottom_width'] ?? '';
        $rail_width = $row['rail_width'] ?? '';
        $box_width = $row['box_width'] ?? '';
        $box_height = $row['box_height'] ?? '';
        $search_keyword = $row['search_keyword'] ?? '';
        // guiderail.json에서 상세 데이터 찾기 (모델명+형태+마감+대분류+UA)
        $summary = '';        
        // bending/write_form.php와 동일한 구조로 데이터 구성
        $inputList = $row['inputList'] ?? [];
        $bendingrateList = $row['bendingrateList'] ?? [];
        $sumList = $row['sumList'] ?? [];
        $colorList = $row['colorList'] ?? [];
        $AList = $row['AList'] ?? [];
        // 등록일 추가
        $registration_date = $row['registration_date'] ?? '';
        
        $summary = htmlspecialchars(json_encode([
            'inputList' => $inputList,
            'bendingrateList' => $bendingrateList,
            'calcAfterList' => $calcAfterList,
            'sumList' => $sumList,
            'colorList' => $colorList,
            'AList' => $AList
        ], JSON_UNESCAPED_UNICODE), ENT_QUOTES, 'UTF-8');

        $box_size = htmlspecialchars($box_width . 'x' . $box_height, ENT_QUOTES, 'UTF-8');
        
        echo '<tr data-num="' . $num . '" class="search-result-row">';
        echo '<td class="text-center">';
        echo '<input class="form-check-input bending-item-checkbox" type="checkbox" data-num="' . $num . '">';
        echo '</td>';
        echo '<td class="text-center order-number" style="width: 60px; font-weight: bold; color: #007bff;">-</td>';
        echo '<td class="text-center">' . htmlspecialchars($registration_date, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '<td class="text-center">' . htmlspecialchars($item_sep, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '<td class="text-center">' . htmlspecialchars($model_UA, ENT_QUOTES, 'UTF-8') . '</td>';        
        echo '<td class="text-center">' . htmlspecialchars($item_bending, ENT_QUOTES, 'UTF-8') . '</td>';        
        echo '<td class="text-center">' . htmlspecialchars($exit_direction, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '<td class="text-center">' . htmlspecialchars($box_size, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '<td class="text-center">' . htmlspecialchars($front_bottom_width, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '<td class="text-center">' . htmlspecialchars($rail_width, ENT_QUOTES, 'UTF-8') . '</td>';        
        echo '<td class="text-center">' . htmlspecialchars($itemName, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '<td class="text-center">' . htmlspecialchars($search_keyword, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '<td class="text-center">' . htmlspecialchars($material, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '<td class="text-center">';
        if ($imgdata) {
            echo '<img src="/bending/img/' . htmlspecialchars($imgdata, ENT_QUOTES, 'UTF-8') . '" 
                      class="search-zoomable-image" 
                      style="width: 40px; height: 24px; object-fit: cover; cursor: pointer;" 
                      data-src="/bending/img/' . htmlspecialchars($imgdata, ENT_QUOTES, 'UTF-8') . '">';
        }
        echo '</td>';
        // 합계 셀: data-summary 속성 추가        
        echo '<td class="text-center mini-summary-trigger" ' . ($summary ? 'data-summary=\'' . $summary . '\'' : '') . '>' . htmlspecialchars($widthsum, ENT_QUOTES, 'UTF-8') . '</td>';
        echo '</tr>';
    }
}
?> 