<?php
// estimate/fetch_unitprice.php
$DB = 'chandj';
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();	

// 오류 표시 및 로그 설정
error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors',     '1');
ini_set('error_log',      $_SERVER['DOCUMENT_ROOT'] . '/php_errors.log');

if (!function_exists('searchBracketSize')) {
    /**
     * 중량과 (선택적) 인치로 모터용량을 판별하고 브라켓 사이즈 반환
     *
     * @param float|string $motorWeight 중량 (col13)
     * @param int|string|null $bracketInch 인치 (col22), 없으면 중량만으로 판단
     * @param array $itemList 인터페이스 일치용, 사용하지 않음
     * @return string 브라켓 사이즈 (예: '530*320')
     */
    function searchBracketSize($motorWeight, $bracketInch = null) {
        $weight = floatval($motorWeight);
        $inch = is_numeric($bracketInch) ? intval($bracketInch) : 0;

        $motorCapacity = 0;

        if ($inch > 0) {
            // 중량 + 인치 기준 판단 (철재 기준)
            if (
                ($inch == 4 && $weight <= 300) ||
                ($inch == 5 && $weight <= 246) ||
                ($inch == 6 && $weight <= 208)
            ) {
                $motorCapacity = 300;
            } elseif (
                ($inch == 4 && $weight > 300 && $weight <= 400) ||
                ($inch == 5 && $weight > 246 && $weight <= 327) ||
                ($inch == 6 && $weight > 208 && $weight <= 277)
            ) {
                $motorCapacity = 400;
            } elseif (
                ($inch == 5 && $weight > 327 && $weight <= 500) ||
                ($inch == 6 && $weight > 277 && $weight <= 424) ||
                ($inch == 8 && $weight <= 324)
            ) {
                $motorCapacity = 500;
            } elseif (
                ($inch == 5 && $weight > 500 && $weight <= 600) ||
                ($inch == 6 && $weight > 424 && $weight <= 508) ||
                ($inch == 8 && $weight > 324 && $weight <= 388)
            ) {
                $motorCapacity = 600;
            } elseif (
                ($inch == 6 && $weight > 600 && $weight <= 800) ||
                ($inch == 6 && $weight > 508 && $weight <= 800) ||
                ($inch == 8 && $weight > 388 && $weight <= 611)
            ) {
                $motorCapacity = 800;
            } elseif (
                ($inch == 6 && $weight > 800 && $weight <= 1000) ||
                ($inch == 8 && $weight > 611 && $weight <= 1000)
            ) {
                $motorCapacity = 1000;
            }
        } else {
            // 인치가 없으면 중량만으로 판단
            if ($weight <= 300) {
                $motorCapacity = 300;
            } elseif ($weight <= 400) {
                $motorCapacity = 400;
            } elseif ($weight <= 500) {
                $motorCapacity = 500;
            } elseif ($weight <= 600) {
                $motorCapacity = 600;
            } elseif ($weight <= 800) {
                $motorCapacity = 800;
            } elseif ($weight <= 1000) {
                $motorCapacity = 1000;
            }
        }

        // 용량별 브라켓 사이즈 매핑
        if (in_array($motorCapacity, [300, 400])) {
            return '530*320';
        } elseif (in_array($motorCapacity, [500, 600])) {
            return '600*350';
        } elseif (in_array($motorCapacity, [800, 1000])) {
            return '690*390';
        }

        return '530*320'; // 브라켓 사이즈 기본값
    }
}


/**
 * 원격에서 품목별 단가를 가져옵니다.
 *
 * fetch_price.php 에 POST 요청을 보낸 뒤,
 * { success: true, data: [ { code: 'col2', price: 'col13' }, … ] }
 * 형태로 반환된 data 만을 꺼내어 리턴합니다.
 *
 * @param string $tableName 테이블 이름 (예: 'item_list')
 * @param array  $codes     조회할 item 코드 목록 (예: ['스크린','마구리',…])
 * @return array            [ ['code'=>string,'price'=>string], … ] 또는 빈 배열
 */
if (!function_exists('fetchPricesFromTable')) {
    function fetchPricesFromTable(string $tableName, array $codes): array {
        $url      = '/estimate/fetch_price.php';
        $postData = [
            'tablename' => $tableName,
            'codes'     => json_encode($codes, JSON_UNESCAPED_UNICODE),
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST,        true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER,  ['Content-Type: application/x-www-form-urlencoded']);

        $response = curl_exec($ch);
        if ($response === false) {
            error_log('fetchPricesFromTable cURL error: ' . curl_error($ch));
            curl_close($ch);
            return [];
        }
        curl_close($ch);

        $decoded = json_decode($response, true);
        if (
            !is_array($decoded)
            || empty($decoded['success'])
            || !isset($decoded['data'])
            || !is_array($decoded['data'])
        ) {
            error_log('fetchPricesFromTable invalid response: ' . print_r($decoded, true));
            return [];
        }

        // data 부분만 리턴
        return $decoded['data'];
    }
}

// 비인정 자재 가격 가져오기
if (!function_exists('unapprovedSlatPrice')) {
    function unapprovedSlatPrice($itemList, $search1, $search2) {
        // col1은 의미없어서 검색에서 제외시킴
        $totalPrice = 0;
        foreach ($itemList as $item) {
            if ($item['col2'] == $search2) {
                $totalPrice = intval(str_replace(',', '', $item['col15']));
                break;
            }
        }
        return $totalPrice;
    }
}

// 비인정 slat 코드 가져오기
if (!function_exists('unapprovedSlatCode')) {
    function unapprovedSlatCode($itemList, $search2) {        
        foreach ($itemList as $item) {
            if ($item['col2'] === $search2) {
                $code = $item['col14']; // 14번째 열 비인정 품목코드
                return $code;
            }
        }
        return '';
    }
}

// slat 가격 가져오기
if (!function_exists('slatPrice')) {
    function slatPrice($itemList, $search1, $search2) {
        // col1은 의미없어서 검색에서 제외시킴
        $totalPrice = 0;
        foreach ($itemList as $item) {
            if ($item['col2'] == $search2) {
                $totalPrice = intval(str_replace(',', '', $item['col13']));
                break;
            }
        }
        return $totalPrice;
    }
}

// slat 코드 가져오기
if (!function_exists('slatCode')) {
    function slatCode($itemList, $search2) {        
        foreach ($itemList as $item) {
            if ($item['col2'] === $search2) {
                $code = $item['col14']; // 14번째 열 비인정 품목코드
                return $code;
            }
        }
        return '';
    }
}

// 샤프트 가격 계산 및 카운트 추가 함수
if (!function_exists('addShaftPrice')) {
    function addShaftPrice($column, $itemList, $size, $length, &$sum_shaft_price, &$shaft_counts) {
        $shaft_price = calculateShaft($column, $itemList, $size, $length);
        if ($shaft_price > 0) {
            $sum_shaft_price += $shaft_price;
            if (!isset($shaft_counts[$length])) {
                $shaft_counts[$length] = 0;
            }
            $shaft_counts[$length]++;
        }
    }
}

// 각파이프
if (!function_exists('calculatePipe')) {
    function calculatePipe($itemList, $searchOption1, $searchOption2) {
        $totalPrice = 0;
        foreach ($itemList as $item) {
            if (
                intval(str_replace(',', '', $item['col4'])) == intval($searchOption1) &&
                intval(str_replace(',', '', $item['col2'])) == intval($searchOption2)
            ) {
                $totalPrice += intval(str_replace(',', '', $item['col8']));
                break;
            }
        }
        return $totalPrice;
    }
}

// shaft 가격
if (!function_exists('calculateShaft')) {
    function calculateShaft($itemSel, $itemList, $searchOption1, $searchOption2) {
        $totalPrice = 0;
        $value = intval($itemSel);
        foreach ($itemList as $item) {
            if (
                $value > 0 &&
                $item['col4'] == $searchOption1 &&
                floatval($item['col10']) == floatval($searchOption2) / 1000
            ) {
                $totalPrice += intval(str_replace(',', '', $item['col19'])) * $value;
                break;
            }
        }
        return $totalPrice;
    }
}

// 가이드레일 가격
if (!function_exists('calculateGuidrail')) {
    function calculateGuidrail($itemSel, $itemList, $searchOption1, $searchOption2) {
        $totalPrice = 0;
        $value = intval($itemSel);
        foreach ($itemList as $item) {
            if (
                $value > 0 &&
                $item['col1'] == $searchOption1 &&
                $item['col2'] == $searchOption2
            ) {
                $totalPrice += intval(str_replace(',', '', $item['col17'])) * intval($value) / 3490;
                break;
            }
        }
        return $totalPrice;
    }
}

// 스크린 모터 브라켓 받침용 앵글 가격
if (!function_exists('calculateAngle')) {
    function calculateAngle($itemSel, $itemList, $searchOption) {
        $totalPrice = 0;
        $surang = intval($itemSel);
        foreach ($itemList as $item) {
            if ($surang > 0 && $item['col2'] === $searchOption) {
                $totalPrice += intval(str_replace(',', '', $item['col19']));
                break;
            }
        }
        return $totalPrice;
    }
}

// 스크린 모터 브라켓 받침용 브라켓 크기로 가져오기
if (!function_exists('calculateAngleBracket')) {
    function calculateAngleBracket($itemSel, $itemList, $searchOption) {
        $totalPrice = 0;
        $surang = intval($itemSel);
        foreach ($itemList as $item) {
            if ($surang > 0 && $item['col3'] === $searchOption) {
                $totalPrice += intval(str_replace(',', '', $item['col19']));
                break;
            }
        }
        return $totalPrice;
    }
}

// 철재모터 브라켓 받침용 브라켓 크기로 가져오기
if (!function_exists('calculateAngleBracket_slat')) {
    function calculateAngleBracket_slat($itemSel, $itemList, $searchOption) {
        $totalPrice = 0;
        $surang = intval($itemSel);
        foreach ($itemList as $item) {
            if ($surang > 0 && $item['col3'] === $searchOption) {
                $totalPrice += intval(str_replace(',', '', $item['col19']));
                break;
            }
        }
        return $totalPrice;
    }
}

// 앵글 3T, 4T 부자재용
if (!function_exists('calculateMainAngle')) {
    function calculateMainAngle($itemSel, $itemList, $searchOption1, $searchOption2) {
        $totalPrice = 0;
        $surang = intval($itemSel);
        foreach ($itemList as $item) {
            if (
                $surang > 0 &&
                $item['col4'] === $searchOption1 &&
                $item['col10'] === $searchOption2
            ) {
                $totalPrice += intval(str_replace(',', '', $item['col19'])) * $surang; // 앵글 테이블 판매가 20% 열의 값
                break;
            }
        }
        return $totalPrice;
    }
}

// 연동제어기(뒷박스포함) 가격 추출하기
if (!function_exists('calculateControllerSpec')) {
    function calculateControllerSpec($itemSel, $itemList, $searchOption) {
        $totalPrice = 0;
        $controller = intval($itemSel);
        foreach ($itemList as $item) {
            if ($controller > 0 && $item['col2'] === $searchOption) {
                $totalPrice += intval(str_replace(',', '', $item['col13']));
                break;
            }
        }
        return $totalPrice;
    }
}

// 모터용량 추출하기
if (!function_exists('calculateMotorSpec')) {
    function calculateMotorSpec($item, $weight, $BracketInch) {
        $ItemSel = (substr($item['col4'], 0, 2) === 'KS' || substr($item['col4'], 0, 2) === 'KW')
            ? '스크린' : '철재';

        $motorCapacity = 0;
        // 조건별 계산
        if (
            ($ItemSel === '스크린' && $BracketInch == 4 && $weight <= 150) ||
            ($ItemSel === '스크린' && $BracketInch == 5 && $weight <= 123) ||
            ($ItemSel === '스크린' && $BracketInch == 6 && $weight <= 104)
        ) {
            $motorCapacity = 150;
        } elseif (
            ($ItemSel === '스크린' && $BracketInch == 4 && $weight > 150 && $weight <= 300) ||
            ($ItemSel === '스크린' && $BracketInch == 5 && $weight > 123 && $weight <= 246) ||
            ($ItemSel === '스크린' && $BracketInch == 6 && $weight > 104 && $weight <= 208) ||
            ($ItemSel === '철재' && $BracketInch == 4 && $weight <= 300) ||
            ($ItemSel === '철재' && $BracketInch == 5 && $weight <= 246) ||
            ($ItemSel === '철재' && $BracketInch == 6 && $weight <= 208)
        ) {
            $motorCapacity = 300;
        } elseif (
            ($ItemSel === '스크린' && $BracketInch == 4 && $weight > 300 && $weight <= 400) ||
            ($ItemSel === '스크린' && $BracketInch == 5 && $weight > 246 && $weight <= 327) ||
            ($ItemSel === '스크린' && $BracketInch == 6 && $weight > 208 && $weight <= 300) ||
            ($ItemSel === '철재' && $BracketInch == 4 && $weight > 300 && $weight <= 400) ||
            ($ItemSel === '철재' && $BracketInch == 5 && $weight > 246 && $weight <= 327) ||
            ($ItemSel === '철재' && $BracketInch == 6 && $weight > 208 && $weight <= 277)
        ) {
            $motorCapacity = 400;
        } elseif (
            ($ItemSel === '스크린' && $BracketInch == 5 && $weight > 327 && $weight <= 500) ||
            ($ItemSel === '스크린' && $BracketInch == 6 && $weight > 300 && $weight <= 424) ||
            ($ItemSel === '철재' && $BracketInch == 5 && $weight > 400 && $weight <= 500) ||
            ($ItemSel === '철재' && $BracketInch == 5 && $weight > 327 && $weight <= 500) ||
            ($ItemSel === '철재' && $BracketInch == 6 && $weight > 277 && $weight <= 424) ||
            ($ItemSel === '철재' && $BracketInch == 8 && $weight <= 324)
        ) {
            $motorCapacity = 500;
        } elseif (
            ($BracketInch == 5 && $weight > 500 && $weight <= 600) ||
            ($BracketInch == 6 && $weight > 424 && $weight <= 508) ||
            ($BracketInch == 8 && $weight > 324 && $weight <= 388)
        ) {
            $motorCapacity = 600;
        } elseif (
            ($ItemSel === '철재' && $BracketInch == 6 && $weight > 600 && $weight <= 800) ||
            ($ItemSel === '철재' && $BracketInch == 6 && $weight > 508 && $weight <= 800) ||
            ($ItemSel === '철재' && $BracketInch == 8 && $weight > 388 && $weight <= 611)
        ) {
            $motorCapacity = 800;
        } elseif (
            ($ItemSel === '철재' && $BracketInch == 6 && $weight > 800 && $weight <= 1000) ||
            ($ItemSel === '철재' && $BracketInch == 8 && $weight > 611 && $weight <= 1000)
        ) {
            $motorCapacity = 1000;
        }

        return $motorCapacity;
    }
}

// 무게 기준 모터 용량 계산
if (!function_exists('calculateMotorKG')) {
    function calculateMotorKG($col1, $col2, $col3) {
        $weight = $col1;
        $bracketInch = $col2;
        $E8 = substr($col3, 0, 2) === 'KS' ? '스크린' : '철재';
        return calculateMotorSpec(['col4' => $E8], $weight, $bracketInch);
    }
}


// 스크린용 브라켓 크기 집계
if (!function_exists('calculateBracket')) {
    function calculateBracket($decodedEstimateList) {
        $bracketSizes = [];
        foreach ($decodedEstimateList as $item) {
            $size = $item['col20'];
            $surang = $item['col14'];
            if (isset($bracketSizes[$size])) {
                $bracketSizes[$size]['quantity'] += $surang;
            } else {
                if(!empty($size)){
                    $bracketSizes[$size] = ['size' => $size, 'quantity' => $surang];
                }
            }
        }
        return ['bracketSizes' => $bracketSizes];
    }
}

// 철재 슬라트용 브라켓 크기 집계
if (!function_exists('calculateBracket_slat')) {
    function calculateBracket_slat($decodedEstimateList) {
        $bracketSizes = [];
        foreach ($decodedEstimateList as $item) {
            $size = $item['col21'];
            $surang = $item['col15'];
            if (isset($bracketSizes[$size])) {
                $bracketSizes[$size]['quantity'] += $surang;
            } else {
                if(!empty($size)){
                    $bracketSizes[$size] = ['size' => $size, 'quantity' => $surang];
                }
            }
        }
        return ['bracketSizes' => $bracketSizes];
    }
}
// 슬라트용 브라켓 앵글 크기 집계
if (!function_exists('calculateBracketAngle_slat')) {
    function calculateBracketAngle_slat($decodedEstimateList) {
        $bracketAngleSizes = [];
        foreach ($decodedEstimateList as $item) {
            $size = $item['col23'];
            if (isset($bracketAngleSizes[$size])) {
                $bracketAngleSizes[$size]['quantity']++;
            } else {
                $bracketAngleSizes[$size] = ['size' => $size, 'quantity' => 1];
            }
        }
        return ['bracketAngleSizes' => $bracketAngleSizes];
    }
}

// 스크린용 브라켓 앵글 크기 집계
if (!function_exists('calculateBracketAngle')) {
    function calculateBracketAngle($decodedEstimateList) {
        $bracketAngleSizes = [];
        foreach ($decodedEstimateList as $item) {
            $size = $item['col22'];
            if (isset($bracketAngleSizes[$size])) {
                $bracketAngleSizes[$size]['quantity']++;
            } else {
                $bracketAngleSizes[$size] = ['size' => $size, 'quantity' => 1];
            }
        }
        return ['bracketAngleSizes' => $bracketAngleSizes];
    }
}

// 슬라트용 모터 스펙 합계
if (!function_exists('calculateMotorSpecifications_slat')) {
    function calculateMotorSpecifications_slat(array $decodedEstimateList): array {
        // 1) 1~12번 칼럼 합계 초기화
        $cols      = array_fill(1, 12, 0);
        $motorCaps = [];

        // 2) col20 값 → colN 맵핑 테이블 (스크린용과 동일)
        $capacityMap = [
            150  => 1,   // 150K → col1_sum
            300  => 2,   // 300K → col2_sum
            400  => 3,   // 400K → col3_sum
            500  => 4,   // 500K → col4_sum
            600  => 5,   // 600K → col5_sum
            800  => 6,   // 800K → col6_sum
            1000 => 7,   // 1000K → col7_sum
        ];

        foreach ($decodedEstimateList as $item) {
            // 3) 각 컬럼 값 추출
            $weight = floatval(preg_replace('/[^\d.]/', '', $item['col20'] ?? '')); // col20에서 숫자만
            $inch   = intval($item['col22'] ?? 0);
            $qty    = floatval($item['col15'] ?? 0);  // 수량
            $col8   = floatval($item['col16'] ?? 0);
            $col9   = floatval($item['col17'] ?? 0);
            $col10  = floatval($item['col18'] ?? 0);
            $col11  = intval($item['col15'] ?? 0);
            $col12  = $col11 * 4;

            // 4) 기존 calculateMotorSpec 호출
            $caps = calculateMotorSpec($item, $weight, $inch);
            if ($caps) {
                $motorCaps[] = $caps;
            }

            // 5) col20 에서 정수 추출 → 맵에서 인덱스 찾아 누적
            $capNumber = intval(preg_replace('/[^\d]/', '', $item['col20'] ?? ''));
            if (isset($capacityMap[$capNumber])) {
                $idx       = $capacityMap[$capNumber];
                $cols[$idx] += $qty;
            }

            // 6) 나머지 col8~col12 누적 (수량 곱하기)
            $cols[8]  += $col8   ;
            $cols[9]  += $col9   ;
            $cols[10] += $col10  ;
            $cols[11] += $col11  ;
            $cols[12] += $col12  ;
        }

        // 7) 결과 리턴
        return [
            'col1_sum'        => $cols[1],
            'col2_sum'        => $cols[2],
            'col3_sum'        => $cols[3],
            'col4_sum'        => $cols[4],
            'col5_sum'        => $cols[5],
            'col6_sum'        => $cols[6],
            'col7_sum'        => $cols[7],
            'col8_sum'        => $cols[8],
            'col9_sum'        => $cols[9],
            'col10_sum'       => $cols[10],
            'col11_sum'       => $cols[11],
            'col12_sum'       => $cols[12],
            'motorCapacities' => $motorCaps,
        ];
    }
}


// 스크린용 모터 스펙 합계
if (!function_exists('calculateMotorSpecifications')) {
    function calculateMotorSpecifications(array $decodedEstimateList): array {
        // 1) 1~12번 칼럼 합계용 배열 초기화
        $cols = array_fill(1, 12, 0);
        $motorCaps = [];

        // 2) col19 값→colN 맵핑 테이블
        $capacityMap = [
            150  => 1,   // 150K → col1_sum
            300  => 2,   // 300K → col2_sum
            400  => 3,   // 400K → col3_sum
            500  => 4,   // 500K → col4_sum
            600  => 5,   // 600K → col5_sum
            800  => 6,   // 800K → col6_sum
            1000 => 7,   // 1000K → col7_sum
        ];

        foreach ($decodedEstimateList as $item) {
            $qty   = floatval($item['col14'] ?? 0);    // 수량
            $col8  = floatval($item['col15'] ?? 0);
            $col9  = floatval($item['col16'] ?? 0);
            $col10 = floatval($item['col17'] ?? 0);
            $col11 = intval($item['col14'] ?? 0);
            $col12 = $col11 * 4;

            // (기존) calculateMotorSpec 로 모터용량 구하기
            $kg   = floatval(preg_replace('/[^\d.]/','', $item['col19'] ?? ''));
            $inch = intval($item['col21'] ?? 0);
            $caps = calculateMotorSpec($item, $kg, $inch);
            if ($caps) {
                $motorCaps[] = $caps;
            }

            // 3) col19 에서 숫자만 뽑아서 정수로 변환
            $capNumber = intval(preg_replace('/[^\d]/','', $item['col19'] ?? ''));
            if (isset($capacityMap[$capNumber])) {
                // 해당 칼럼 인덱스에 수량 누적
                $idx = $capacityMap[$capNumber];
                $cols[$idx] += $qty;
            }
            // 4) 나머지 col8~col12 누적
            $cols[8]  += $col8  ;
            $cols[9]  += $col9  ;
            $cols[10] += $col10 ;
            $cols[11] += $col11 ;
            $cols[12] += $col12 ;
        }

        // 5) 결과 리턴
        return [
            'col1_sum'        => $cols[1],
            'col2_sum'        => $cols[2],
            'col3_sum'        => $cols[3],
            'col4_sum'        => $cols[4],
            'col5_sum'        => $cols[5],
            'col6_sum'        => $cols[6],
            'col7_sum'        => $cols[7],
            'col8_sum'        => $cols[8],
            'col9_sum'        => $cols[9],
            'col10_sum'       => $cols[10],
            'col11_sum'       => $cols[11],
            'col12_sum'       => $cols[12],
            'motorCapacities' => $motorCaps,
        ];
    }
}



// 모터 단가 조회
if (!function_exists('getPriceForMotor')) {
    function getPriceForMotor($capacity, $itemList) {
        $capacity = preg_replace('/[^0-9]/', '', $capacity);
        foreach ($itemList as $item) {
            $itemCap = preg_replace('/[^0-9]/', '', $item['col2']);
            if ($itemCap == $capacity) {
                return intval(str_replace(',', '', $item['col13']));
            }
        }
        return 0;
    }
}

// 원격 단가 페치
if (!function_exists('fetchPricesFromTable')) {
    function fetchPricesFromTable($tableName, $codes) {
        $url = '/estimate/fetch_price.php';
        $postData = [
            'tablename' => $tableName,
            'codes'     => json_encode($codes)
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
        $response = curl_exec($ch);
        if ($response === false) {
            $err = curl_error($ch);
            curl_close($ch);
            return ['error' => $err];
        }
        curl_close($ch);
        return json_decode($response, true);
    }
}

// 숫자 → 한글 변환
if (!function_exists('number_to_korean')) {
    function number_to_korean($number) {
        $nums = ['', '일','이','삼','사','오','육','칠','팔','구'];
        $units = ['', '십','백','천','만','억','조'];
        $str = '';
        $s = strval($number);
        $len = strlen($s);
        for ($i=0;$i<$len;$i++){
            $d = intval($s[$i]);
            $pos = $len-$i-1;
            if ($d>0){
                $str .= $nums[$d].$units[$pos];
            }
        }
        return $str;
    }
}

// 특정 문자 마지막만 남기고 제거
if (!function_exists('removeAllButLastOccurrence')) {
    function removeAllButLastOccurrence($string, $target) {
        $last = strrpos($string, $target);
        if ($last === false) return $string;
        $before = substr($string,0,$last);
        $after  = substr($string,$last);
        return str_replace($target,'',$before).$after;
    }
}

// 스크린 단가 조회
if (!function_exists('getScreenUnitPrice')) {
    function getScreenUnitPrice(PDO $pdo): float {
        $sql = "SELECT col13 FROM item_list WHERE col2 = '스크린' LIMIT 1";
        $stmt = $pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? floatval(str_replace(',', '', $result['col13'])) : 0;
    }
}

// 자재 단가 조회 (케이스, 연기차단재, 마구리, 앵글 등)
if (!function_exists('getMaterialPrices')) {
    function getMaterialPrices(PDO $pdo): array {
        $prices = [
            'shutterBox' => [],
            'boxSmoke' => 0,
            'maguri' => [],
            'angleBracket' => 0,
            'rail' => 0,
            'railSmoke' => 0,
            'bottomBar' => 0,
            'mainAngle' => 0
        ];

        // 케이스 단가
        $sql = "SELECT col2, col13 FROM item_list WHERE col1 = '케이스'";
        $stmt = $pdo->query($sql);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $prices['shutterBox'][$row['col2']] = floatval(str_replace(',', '', $row['col13']));
        }

        // 연기차단재 단가
        $sql = "SELECT col13 FROM item_list WHERE col2 = '연기차단재' LIMIT 1";
        $stmt = $pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $prices['boxSmoke'] = $result ? floatval(str_replace(',', '', $result['col13'])) : 0;

        // 마구리 단가
        $sql = "SELECT col2, col13 FROM item_list WHERE col1 = '마구리'";
        $stmt = $pdo->query($sql);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $prices['maguri'][$row['col2']] = floatval(str_replace(',', '', $row['col13']));
        }

        // 모터받침용 앵글 단가
        $sql = "SELECT col13 FROM item_list WHERE col2 = '모터받침용 앵글' LIMIT 1";
        $stmt = $pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $prices['angleBracket'] = $result ? floatval(str_replace(',', '', $result['col13'])) : 0;

        // 가이드레일 단가
        $sql = "SELECT col13 FROM item_list WHERE col2 = '가이드레일' LIMIT 1";
        $stmt = $pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $prices['rail'] = $result ? floatval(str_replace(',', '', $result['col13'])) : 0;

        // 레일용 연기차단재 단가
        $sql = "SELECT col13 FROM item_list WHERE col2 = '레일용 연기차단재' LIMIT 1";
        $stmt = $pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $prices['railSmoke'] = $result ? floatval(str_replace(',', '', $result['col13'])) : 0;

        // 하장바 단가
        $sql = "SELECT col13 FROM item_list WHERE col2 = '하장바' LIMIT 1";
        $stmt = $pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $prices['bottomBar'] = $result ? floatval(str_replace(',', '', $result['col13'])) : 0;

        // 앵글3T 단가
        $sql = "SELECT col13 FROM item_list WHERE col2 = '앵글3T' LIMIT 1";
        $stmt = $pdo->query($sql);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $prices['mainAngle'] = $result ? floatval(str_replace(',', '', $result['col13'])) : 0;

        return $prices;
    }
}

// 샤프트 단가 조회
if (!function_exists('getShaftPrices')) {
    function getShaftPrices(PDO $pdo): array {
        $prices = [];
        $sql = "SELECT col4, col13 FROM item_list WHERE col1 = '샤프트'";
        $stmt = $pdo->query($sql);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $prices[$row['col4']] = floatval(str_replace(',', '', $row['col13']));
        }
        return $prices;
    }
}

// 모터 단가 조회
if (!function_exists('getMotorPrices')) {
    function getMotorPrices(PDO $pdo): array {
        $prices = [];
        $sql = "SELECT col2, col13 FROM item_list WHERE col1 = '모터'";
        $stmt = $pdo->query($sql);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $prices[$row['col2']] = floatval(str_replace(',', '', $row['col13']));
        }
        return $prices;
    }
}

// 제어기 단가 조회
if (!function_exists('getControllerPrices')) {
    function getControllerPrices(PDO $pdo): array {
        $prices = [];
        $sql = "SELECT col2, col13 FROM item_list WHERE col1 = '제어기'";
        $stmt = $pdo->query($sql);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $prices[$row['col2']] = floatval(str_replace(',', '', $row['col13']));
        }
        return $prices;
    }
}

// 파이프 단가 조회
if (!function_exists('getPipePrices')) {
    function getPipePrices(PDO $pdo): array {
        $prices = [];
        $sql = "SELECT col2, col13 FROM item_list WHERE col1 = '파이프'";
        $stmt = $pdo->query($sql);
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $prices[$row['col2']] = floatval(str_replace(',', '', $row['col13']));
        }
        return $prices;
    }
}

// 제어기 단위 가격 계산
if (!function_exists('getControllerUnit')) {
    function getControllerUnit(int $qty, array $prices, string $type): float {
        if ($qty <= 0) {
            return 0;
        }

        // 제어기 유형별 키 매핑
        $typeMap = [
            '매립형' => '매립형',
            '노출형' => '노출형',
            '뒷박스' => '뒷박스'
        ];

        $key = $typeMap[$type] ?? '';
        if (empty($key) || !isset($prices[$key])) {
            return 0;
        }

        return $prices[$key] * $qty;
    }
}

// 샤프트 컬럼명에서 규격 추출
if (!function_exists('getShaftSpecFromCol')) {
    function getShaftSpecFromCol(string $col): string {
        // 컬럼명과 규격 매핑
        $specMap = [
            'col59' => '1000',
            'col60' => '3000',
            'col61' => '4000',
            'col62' => '5000',
            'col63' => '6000',
            'col64' => '8000',
            'col65' => '10000'
        ];

        return $specMap[$col] ?? '';
    }
}

?>
