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

// Get search parameters from list.php style
$selectedName = $_REQUEST['selectedName'] ?? '';
$selectedItem = $_REQUEST['selectedItem'] ?? '';
$selectedUA = $_REQUEST['selectedUA'] ?? '';
$selectedBendingCategory = $_REQUEST['selectedBendingCategory'] ?? '';
$selectedMaterial = $_REQUEST['selectedMaterial'] ?? '';
$search = $_REQUEST['search'] ?? '';

// Build query conditions
$conditions = ["is_deleted IS NULL"];
$bindParams = [];

// Add selectedItem condition (대분류)
if (!empty($selectedItem)) {
    $conditions[] = "item_sep = :selectedItem";
    $bindParams[":selectedItem"] = $selectedItem;
}

// Add selectedUA condition (인정/비인정)
if (!empty($selectedUA)) {
    $conditions[] = "model_UA = :selectedUA";
    $bindParams[":selectedUA"] = $selectedUA;
}

// Add selectedBendingCategory condition (절곡물 분류)
if (!empty($selectedBendingCategory)) {
    $conditions[] = "item_bending = :selectedBendingCategory";
    $bindParams[":selectedBendingCategory"] = $selectedBendingCategory;
}

// Add selectedName condition (품명)
if (!empty($selectedName)) {
    $conditions[] = "itemName = :selectedName";
    $bindParams[":selectedName"] = $selectedName;
}

// Add selectedMaterial condition (재질)
if (!empty($selectedMaterial)) {
    $conditions[] = "material = :selectedMaterial";
    $bindParams[":selectedMaterial"] = $selectedMaterial;
}

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

// Add search condition if provided (전체 컬럼 검색)
if (!empty($search)) {
    $columns = [];
    $stmt = $pdo->query("SHOW COLUMNS FROM {$DB}.{$tablename}");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $columns[] = $row['Field'];
    }

    // 각 컬럼에 대해 LIKE 검색 조건 추가
    $searchConditions = [];
    foreach ($columns as $index => $col) {
        $paramName = ":search{$index}";
        $searchConditions[] = "$col LIKE $paramName";
        $bindParams[$paramName] = "%{$search}%";
    }
    
    if (!empty($searchConditions)) {
        $conditions[] = "(" . implode(" OR ", $searchConditions) . ")";
    }
}

// Build final SQL query
$sqlWhere = implode(" AND ", $conditions);
$sqlOrder = "ORDER BY num DESC";
$sql = "SELECT * FROM {$DB}.{$tablename} WHERE {$sqlWhere} {$sqlOrder}";

// Execute query
$stmh = $pdo->prepare($sql);

// Bind all parameters using bindValue
foreach ($bindParams as $key => $value) {
    $stmh->bindValue($key, $value, PDO::PARAM_STR);
}

$stmh->execute();

// print($sql);

// Output results as HTML table rows
while ($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
    $num = $row['num'];
    $item_sep = $row['item_sep']; // 대분류
    $model_UA = $row['model_UA']; // 인정/비인정
    $item_bending = $row['item_bending']; // 중분류
    $itemName = $row['itemName'];
    $item_spec = $row['item_spec'];
    $material = $row['material'];
    $widthsum = $row['widthsum'];
    $memo = $row['memo'];
    $imgdata = $row['imgdata'];
    $upload_dir = '../bending/img/';
    
    // Calculate bending count
    $sumList = array_filter([
        $row['sum1'], $row['sum2'], $row['sum3'], 
        $row['sum4'], $row['sum5'], $row['sum6']
    ], function($v) { return $v !== false; });
    $bendingCount = count($sumList) > 0 ? (count($sumList) - 1) : 0;
    
    // Calculate other counts like in list.php
    $colorList = array_filter([
        $row['color1'], $row['color2'], $row['color3'], 
        $row['color4'], $row['color5'], $row['color6']
    ], function($v) { return $v !== false; });
    
    $AList = array_filter([
        $row['A1'], $row['A2'], $row['A3'], 
        $row['A4'], $row['A5'], $row['A6']
    ], function($v) { return $v !== false; });
    
    // Output row
    echo "<tr>";
    echo "<td class='text-center'>" . htmlspecialchars($item_sep) . "</td>";
    echo "<td class='text-center'>" . htmlspecialchars($model_UA) . "</td>";
    echo "<td class='text-center'>" . htmlspecialchars($item_bending) . "</td>";
    echo "<td class='text-center'>" . htmlspecialchars($itemName) . "</td>";
    echo "<td class='text-center'>" . htmlspecialchars($material) . "</td>";
    echo "<td class='text-center'>" . htmlspecialchars($item_spec) . "</td>";
    // 이미지(형상)
    echo "<td class='text-center'>";
    if (!empty($imgdata)) {
        echo "<img src='{$upload_dir}" . htmlspecialchars($imgdata) . "' alt='형상 이미지' style='max-width:100px; max-height:50px; height:auto; width:auto;'>";
    } else {
        echo "<span class='text-secondary'>이미지 없음</span>";
    }
    echo "</td>";
    echo "<td class='text-center'>" . $widthsum . "</td>";
    echo "<td class='text-center'>" . $bendingCount . "</td>";
    echo "<td class='text-center'>" . htmlspecialchars($memo) . "</td>";
    echo "<td class='text-center'>";
    echo "<button type='button' class='btn btn-primary btn-sm select-bending-item' data-num='" . $num . "'>";
    echo "<i class='bi bi-check-lg'></i> 선택";
    echo "</button>";
    echo "</td>";
    echo "</tr>";
}
?>
