<?php
declare(strict_types=1);

error_reporting(E_ALL);
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', $_SERVER['DOCUMENT_ROOT'].'/php_errors.log');

header('Content-Type: application/json; charset=utf-8');

$DB = 'chandj'; // 데이터베이스 이름 설정
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();	

// 데이터베이스 선택
$pdo->exec("USE `$DB`");

// 테이블 이름 설정
$tablename = 'estimate';

require_once $_SERVER['DOCUMENT_ROOT'].'/estimate/fetch_unitprice.php'; // 보조 함수 정의된 파일 포함 (예: addShaftPrice 등)

/**
 * 값이 비어있거나 null이거나 0인지 체크하는 함수
 * @param mixed $value 체크할 값
 * @return bool true면 비어있거나 null이거나 0, false면 유효한 값
 */
function isEmptyOrZero($value): bool {
    $trimmed = trim((string)$value);
    return $trimmed === '' || $trimmed === '0' || $trimmed === null;
}

function calculateScreenAmount($details, $inspectionFee, $pdo, $checkboxOptions = []): array {        
    // 체크박스 옵션에서 각 값을 추출
    $steel = $checkboxOptions['steel'] ?? '0';
    $motor = $checkboxOptions['motor'] ?? '0';
    $warranty = $checkboxOptions['warranty'] ?? '';
    $slatcheck = $checkboxOptions['slatcheck'] ?? '0';
    $partscheck = $checkboxOptions['partscheck'] ?? '0';
    
    $result = [];
    $total_amount = 0;
    $counter = 0;
    $sums = [];
    $itemDetails = []; // 각 행의 항목별 금액을 저장할 배열

    foreach ($details as $item) {
        if (isset($item['col4']) && !empty($item['col14'])) {
            // 각 행의 항목별 금액을 저장할 배열 초기화
            $itemTitle = floatval($item['col5']);        
            $su = floatval($item['col14']);         //수량            
            $rowItemDetails = [
                '검사비' => (int)$inspectionFee * $su,
                '주자재(스크린)' => 0,
                '모터' => 0,
                '매립/노출 연동제어기(뒷박스 있는 경우 포함)' => 0,
                '케이스' => 0,
                '케이스용 연기차단재' => 0,
                '케이스 마구리' => 0,
                '모터 받침용 앵글' => 0,
                '가이드레일' => 0,
                '레일용 연기차단재' => 0,
                '하장바' => 0,
                'L바' => 0,
                '보강평철' => 0,
                '감기샤프트' => 0,
                '무게평철12T (2000)' => 0,
                '환봉(3000)' => 0,
                '각파이프 총액' => 0,
                '앵글' => 0,
                'TotalAmount' => '',  // 전체금액 합계
                'slatcheck' => $slatcheck,
                'partscheck' => $partscheck,
                'steel' => $steel,
                'motor' => $motor,
                'warranty' => $warranty
            ];
            
            // 검사비 추가
            $sums[$counter] = $inspectionFee * $su;
     
            if($itemTitle == '실리카')
                $itemTitle = '스크린';
            else
                $itemTitle = '와이어';

            // 주자재 계산            
            $tablename = 'price_raw_materials';
            $query = "SELECT itemList FROM $tablename WHERE is_deleted IS NULL OR is_deleted = 0 ORDER BY registedate DESC LIMIT 1"; // 최신 1개의 데이터만 가져오기
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $price_raw_materials = 0;
            foreach ($rows as $row) {
                $itemList = json_decode($row['itemList'], true);
                $price_raw_materials = slatPrice($itemList, '스크린', '실리카');
                if(!empty($price_raw_materials)) 
                    break;
            }

            // 면적 계산
            // 견적서를 스크린 900 높이로 계산함. 기본 350 + 550 추가로 더해줌
            $height = !empty($item['col11_SH']) ? floatval($item['col11_SH']) : floatval($item['col11']);
            $width = !empty($item['col10_SW']) ? floatval($item['col10_SW']) : floatval($item['col10']);
            $calculateHeight = $height + 550;
            $area = $width * $calculateHeight / 1000000;

            // 스크린 가격 계산
            $screen_price = floatval($price_raw_materials * round($area,2));
            $rowItemDetails['주자재(스크린)'] = $screen_price * $su;
            $sums[$counter] += $rowItemDetails['주자재(스크린)'];
            
            // 모터 견적가 포함 검색
            $motor_supplier = $item['col18_brand'];
            // 모터 가격 계산
            $tablename = 'price_motor';
            $query = "SELECT itemList FROM $tablename WHERE is_deleted IS NULL OR is_deleted = 0 ORDER BY NUM LIMIT 1";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $itemList = json_decode($row['itemList'], true);

            $motorSpec = $item['col19'];
            $motorSpec = preg_replace('/[a-zA-Z]/', '', $motorSpec);
            $motorUnit_price = getPriceForMotor($motorSpec, $itemList);
            if($motor_supplier == '경동(견적가포함)' && $motor == '1') { // 모터체크박스
                $rowItemDetails['모터'] = $motorUnit_price * $su;
                $sums[$counter] += $rowItemDetails['모터'];
            }            

            // 연동제어기 가격 계산
            $price1 = calculateControllerSpec($item['col15'], $itemList, '매립형');
            $price2 = calculateControllerSpec($item['col16'], $itemList, '노출형');
            $price3 = calculateControllerSpec($item['col17'], $itemList, '뒷박스');
            $controller_price = $price1* floatval($item['col15']) + $price2* floatval($item['col16']) + $price3* floatval($item['col17']);
            $rowItemDetails['매립/노출 연동제어기(뒷박스 있는 경우 포함)'] = $controller_price ;
            $sums[$counter] += $rowItemDetails['매립/노출 연동제어기(뒷박스 있는 경우 포함)'];

            // 케이스 가격 계산
            $tablename = 'BDmodels';
            $query = "SELECT * FROM $tablename";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            $shutterBoxprices = [];
            
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $prodcode = $row['model_name'] ?? '';
                $spec = $row['spec'] ?? '';
                $seconditem = $row['seconditem'] ?? '';
                $unitprice = $row['unitprice'] ?? 0;
                $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
                $unitprice_value = floatval($unitprice_clean);

                if ($seconditem == '케이스' && $unitprice_value > 0) {
                    $shutterBoxprices[$spec] = $unitprice_value;
                }
            }

            if ($item['col36'] === 'custom') {
                $dimension = $item['col36_custom'];
            } else {
                $dimension = $item['col36'];
            }

            $shutter_price = 0;
            if (array_key_exists($dimension, $shutterBoxprices)) {
                $shutter_price = ($shutterBoxprices[$dimension] / 1000);
            } else {
                $basicbox_price = round($shutterBoxprices['500*380'], 2);
                $basicbox_pricePermeter = $basicbox_price/(500*380/1000);
                list($boxwidth, $boxheight) = explode('*', $dimension);
                $shutter_price = $basicbox_pricePermeter * floatval($boxwidth) * floatval($boxheight) / 1000;
                if($basicbox_price > $shutter_price) {
                    $shutter_price = $basicbox_price ;
                }
            }

            $total_length = round(floatval($item['col37']) / 1000, 2);
            if($item['col36'] !=='' && $steel == '1') { // 절곡체크박스
                $rowItemDetails['케이스'] = round($shutter_price * $total_length * 1000) * $su; // *1000, 소수점 제거
                $sums[$counter] += $rowItemDetails['케이스'];
            }
            else {
                $rowItemDetails['케이스'] = 0;             
            }

            // 가이드레일 가격 계산 (screen_view_original.php와 동일하게)
            $guidrailPrices = [];
            $tablename = 'BDmodels';
            $query = "SELECT * FROM $tablename";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $prodcode = $row['model_name'] ?? '';
                $spec = $row['spec'] ?? '';
                $seconditem = $row['seconditem'] ?? '';
                $load_finishingType = $row['finishing_type'] ?? '';
                $unitprice = $row['unitprice'] ?? 0;
                $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
                $unitprice_value = floatval($unitprice_clean);
                if ($seconditem == '가이드레일') {
                    $key = $prodcode . '|' . $load_finishingType . '|' . $spec;
                    $guidrailPrices[$key] = $unitprice_value;
                }
            }
            $finishing = $item['col7'];
            $guideType = $item['col6'];
            $modelCode = $item['col4'];
            $baseKey = $modelCode . '|' . $finishing;
            $guidrail_price = 0;
            if (strpos($guideType, '혼합') !== false) {
                preg_match_all('/\d{2,4}\*\d{2,4}/', $guideType, $matches);
                if (!empty($matches[0]) && count($matches[0]) == 2) {
                    $wallKey = $baseKey . '|' . $matches[0][0];
                    $sideKey = $baseKey . '|' . $matches[0][1];
                    $wallPrice = $guidrailPrices[$wallKey] ?? 0;
                    $sidePrice = $guidrailPrices[$sideKey] ?? 0;
                    $guidrail_price = ($wallPrice + $sidePrice); // 1개 세트 가격
                }
            } else if (strpos($guideType, '벽면') !== false || strpos($guideType, '측면') !== false) {
                preg_match('/\d{2,4}\*\d{2,4}/', $guideType, $match);
                if (!empty($match[0])) {
                    $guideSpec = $match[0];
                    $guideKey = $baseKey . '|' . $guideSpec;
                    $guidrail_price = ($guidrailPrices[$guideKey] ?? 0) * 2; // 2개 세트 가격
                }            
            } else {                
                $guidrail_price = 0; // 없음선택시                
            }
            $total_length = round(floatval($item['col23']) / 1000, 2);
            $guidrail_price = round($guidrail_price);
            $rowItemDetails['가이드레일'] = round($guidrail_price * $total_length) * $su;
            $sums[$counter] += $rowItemDetails['가이드레일'];

            // 샤프트 가격 계산
            $shaft_price = calculateShaftPrice($item, $pdo); // 샤프트 단품가격
            if($partscheck == '1') { // 부자재체크박스
                $rowItemDetails['감기샤프트'] = round($shaft_price) ;
                $sums[$counter] += $rowItemDetails['감기샤프트'];
            }
            else {
                $rowItemDetails['감기샤프트'] = 0;
            }

            // 부자재 가격 계산            
            // 각파이프 총액 계산
            $pipe_price_3000 = 0;
            $pipe_price_6000 = 0;
            $pipe_price_3000_surang = 0;
            $pipe_price_6000_surang = 0;
            $tablename = 'price_pipe';
            $query = "SELECT itemList FROM  $tablename WHERE (is_deleted IS NULL OR is_deleted = 0 OR is_deleted = '') ORDER BY NUM LIMIT 1";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $itemList = json_decode($row['itemList'], true);
            if ($itemList) {
                $pipe_price_3000 = calculatePipe($itemList, '1.4', '3000');
                $pipe_price_6000 = calculatePipe($itemList, '1.4', '6000');
            }
            $pipe_price_3000_surang = intval(str_replace(',', '', $item['col68']));
            $pipe_price_6000_surang = intval(str_replace(',', '', $item['col69']));
            $total_pipe_price = ($pipe_price_3000 * $pipe_price_3000_surang) + ($pipe_price_6000 * $pipe_price_6000_surang);

            // 무게평철12T (2000) 및 환봉(3000) 계산
            $baseWeightPlatePrice = 12000;
            $weight_plate_price = $baseWeightPlatePrice * intval($item['col57']);

            // 환봉가격
            $round_bar_price = 2000;
            $round_bar_surang = intval(str_replace(',', '', $item['col70']));

            // 절곡 체크와 연관된 것이 무게평철, 환봉이다.
            if($steel == '1') {
            $rowItemDetails['무게평철12T (2000)'] = round($weight_plate_price);
            $sums[$counter] += $rowItemDetails['무게평철12T (2000)'];
            $rowItemDetails['환봉(3000)'] = round($round_bar_price * $round_bar_surang);
            $sums[$counter] += $rowItemDetails['환봉(3000)'];
            }
            else {
                $rowItemDetails['무게평철12T (2000)'] = 0;
                $rowItemDetails['환봉(3000)'] = 0;
            }

            if($partscheck == '1') { // 부자재체크박스
                $rowItemDetails['각파이프 총액'] = round($total_pipe_price);
                $sums[$counter] += $rowItemDetails['각파이프 총액'];
            }
            else {
                $rowItemDetails['각파이프 총액'] = 0;
            }

            // 케이스용 연기차단재
            $boxSmokeBanPrices = 0;
            $tablename = 'BDmodels';
            $query = "SELECT * FROM $tablename";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $seconditem = $row['seconditem'] ?? '';
                $unitprice = $row['unitprice'] ?? 0;
                $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
                $unitprice_value = floatval($unitprice_clean);
                if ($seconditem == '케이스용 연기차단재' && $unitprice_value > 0) {
                    $boxSmokeBanPrices = $unitprice_value;
                }
            }
            $total_length = round(floatval($item['col37']) / 1000, 2);
            if($item['col36'] !=='' && $steel == '1') { // 절곡체크박스
                $rowItemDetails['케이스용 연기차단재'] = round($boxSmokeBanPrices * $total_length) * $su;
                $sums[$counter] += $rowItemDetails['케이스용 연기차단재'];
            }
            else {
                $rowItemDetails['케이스용 연기차단재'] = 0;
            }

            // 케이스 마구리
            $maguriPrices = 0;
            $maguriCol = $item['col45'];
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $seconditem = $row['seconditem'] ?? '';
                $spec = $row['spec'] ?? '';
                $unitprice = $row['unitprice'] ?? 0;
                $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
                $unitprice_value = floatval($unitprice_clean);
                if ($seconditem == '마구리' && $spec == $maguriCol && $unitprice_value > 0) {
                    $maguriPrices = $unitprice_value;
                }
            }
            if($item['col36'] !=='' && $steel == '1') { // 절곡체크박스
                $rowItemDetails['케이스 마구리'] = round($maguriPrices * $su);
                $sums[$counter] += $rowItemDetails['케이스 마구리'];
            }
            else {
                $rowItemDetails['케이스 마구리'] = 0;
            }

            // 모터 받침용 앵글
            $price_angle = 0;
            $tablename = 'price_angle';
            $query = "SELECT itemList FROM $tablename WHERE is_deleted IS NULL OR is_deleted = 0 ORDER BY NUM LIMIT 1";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $itemList = json_decode($row['itemList'], true);
            if ($itemList) {
                if(trim($item['col22']) != '' && trim($item['col22']) != '0' && !($slatcheck === '1' && $motor !== '1' && $steel !== '1' && $partscheck !== '1')) { // 슬랫체크박스, 모터체크박스, 절곡체크박스, 부자재체크박스 
                    $price_angle = calculateAngle($item['col14'], $itemList, '스크린용'); // 스크린은 정해져있음 간단함
                } 
            }
            
            $rowItemDetails['모터 받침용 앵글'] = round($price_angle * $su * 4);
            $sums[$counter] += $rowItemDetails['모터 받침용 앵글'];

            // 레일용 연기차단재
            $guiderailSmokeBanPrices = 0;
            $tablename = 'BDmodels';
            $query = "SELECT * FROM $tablename";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $seconditem = $row['seconditem'] ?? '';
                $unitprice = $row['unitprice'] ?? 0;
                $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
                $unitprice_value = floatval($unitprice_clean);
                if ($seconditem == '가이드레일용 연기차단재' && $unitprice_value > 0 && (!isEmptyOrZero($item['col31']) ||  !isEmptyOrZero($item['col32']) || !isEmptyOrZero($item['col33']) || !isEmptyOrZero($item['col34']) || !isEmptyOrZero($item['col35']))) {
                    $guiderailSmokeBanPrices = $unitprice_value;
                }
            }

            $total_length = floatval($item['col23']) / 1000;
            if($steel == '1') {
                $rowItemDetails['레일용 연기차단재'] = round($guiderailSmokeBanPrices * $total_length ) * 2 * $su;  // 결과값에 수량 곱하기
                $sums[$counter] += $rowItemDetails['레일용 연기차단재'];
            }
            else {
                $rowItemDetails['레일용 연기차단재'] = 0;
            }

            // 하장바
            $bottomBarPrices = 0;
            $tablename = 'BDmodels';
            $query = "SELECT * FROM $tablename";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $prodcode = $row['model_name'] ?? '';
                $seconditem = $row['seconditem'] ?? '';
                $load_finishingType = $row['finishing_type'] ?? '';
                $unitprice = $row['unitprice'] ?? 0;
                $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
                $unitprice_value = floatval($unitprice_clean);
                if ($prodcode == $item['col4'] && $seconditem == '하단마감재' && $item['col7'] == $load_finishingType && $unitprice_value > 0 && (!isEmptyOrZero($item['col49']) || !isEmptyOrZero($item['col50']))) {
                    $bottomBarPrices = $unitprice_value;
                }
            }
            $total_length = intval($item['col48']) * $su;
            $total_length = round($total_length / 1000, 2);
            if($steel == '1') {
                $rowItemDetails['하장바'] = round($bottomBarPrices * $total_length);
                $sums[$counter] += $rowItemDetails['하장바'];
            }
            else {
                $rowItemDetails['하장바'] = 0;
            }

            // L바
            $LBarPrices = 0;
            $tablename = 'BDmodels';
            $query = "SELECT * FROM $tablename";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $prodcode = $row['model_name'] ?? '';
                $seconditem = $row['seconditem'] ?? '';
                $unitprice = $row['unitprice'] ?? 0;
                $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
                $unitprice_value = floatval($unitprice_clean);
                if ($prodcode == $item['col4'] && $seconditem == 'L-BAR' && $unitprice_value > 0 && (!isEmptyOrZero($item['col52']) || !isEmptyOrZero($item['col53']))) {
                    $LBarPrices = $unitprice_value;
                }
            }
            $total_length = intval($item['col51']) * $su;
            $total_length = $total_length / 1000;
            if($steel == '1') { // 절곡체크박스
                $rowItemDetails['L바'] = round($LBarPrices * $total_length);
                $sums[$counter] += $rowItemDetails['L바'];
            }
            else {
                $rowItemDetails['L바'] = 0;
            }
            // 보강평철
            $bottomPlatePrices = 0;
            $tablename = 'BDmodels';
            $query = "SELECT * FROM $tablename";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $seconditem = $row['seconditem'] ?? '';
                $unitprice = $row['unitprice'] ?? 0;
                $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
                $unitprice_value = floatval($unitprice_clean);
                if ($seconditem == '보강평철' && $unitprice_value > 0 && (!isEmptyOrZero($item['col55']) || !isEmptyOrZero($item['col56']))) {
                    $bottomPlatePrices = $unitprice_value;
                }
            }
            $total_length = intval($item['col54']) * $su;
            $total_length = $total_length / 1000;
            if($steel == '1') {
                $rowItemDetails['보강평철'] = round($bottomPlatePrices * $total_length);      
                $sums[$counter] += $rowItemDetails['보강평철'];
            }
            else {
                $rowItemDetails['보강평철'] = 0;
            }
            
            // 앵글
            $mainangle_price = 0;
            $tablename = 'price_angle';
            $query = "SELECT itemList FROM  $tablename WHERE is_deleted IS NULL OR is_deleted = 0 ORDER BY NUM LIMIT 1";
            $stmt = $pdo->prepare($query);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_ASSOC);
            $itemList = json_decode($row['itemList'], true);

            if($partscheck == '1') { // 부자재체크박스
                $mainangle_price = calculateMainAngle(1, $itemList, '앵글3T', '2.5');
                $mainangle_surang = intval(str_replace(',', '', $item['col71']));
                $rowItemDetails['앵글'] = round($mainangle_price * $mainangle_surang);
                $sums[$counter] += $rowItemDetails['앵글'];
            }
            else {
                $rowItemDetails['앵글'] = 0;
            }

            // 모든 항목 소수점 없이 원단위로 변환
            foreach ($rowItemDetails as $k => $v) {
                $rowItemDetails[$k] = round($v);
            }

            // 전체금액 계산 (검사비 제외한 모든 항목의 합)
            $totalRowAmount = 0;
            foreach ($rowItemDetails as $key => $value) {
                if ($key !== 'TotalAmount' && 
                    $key !== 'slatcheck' && 
                    $key !== 'partscheck' && 
                    $key !== 'steel' && 
                    $key !== 'motor' && 
                    $key !== 'warranty') {
                    $totalRowAmount += $value;
                }
            }
            $rowItemDetails['TotalAmount'] = round($totalRowAmount);

            $total_amount += $sums[$counter];
            $itemDetails[] = $rowItemDetails; // 각 행의 항목별 금액 저장
            $counter++;
            $surangSum += $su;
        }
    }

    return [
        'total_amount' => $total_amount,
        'details' => $sums,
        'itemDetails' => $itemDetails,
        'surangSum' => $surangSum
    ];
}

function calculateGuideRailPrice(array $item, PDO $pdo): float {
    $tablename = 'BDmodels';
    $query = "SELECT * FROM $tablename";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    
    $guidrailPrices = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $prodcode = $row['model_name'] ?? '';
        $spec = $row['spec'] ?? '';
        $seconditem = $row['seconditem'] ?? '';
        $load_finishingType = $row['finishing_type'] ?? '';
        $unitprice = $row['unitprice'] ?? 0;
        $unitprice_clean = preg_replace('/[^0-9.]/', '', $unitprice);
        $unitprice_value = floatval($unitprice_clean);

        if ($seconditem == '가이드레일') {
            $key = $prodcode . '|' . $load_finishingType . '|' . $spec;
            $guidrailPrices[$key] = $unitprice_value;
        }
    }

    $modelCode = $item['col4'];
    $finishing = $item['col7'];
    $guideType = $item['col6'];
    $baseKey = $modelCode . '|' . $finishing;
    $guidrail_price = 0;

    if (strpos($guideType, '혼합형') !== false) {
        preg_match_all('/\d{2,4}\*\d{2,4}/', $guideType, $matches);
        if (!empty($matches[0]) && count($matches[0]) == 2) {
            $wallKey = $baseKey . '|' . $matches[0][0];
            $sideKey = $baseKey . '|' . $matches[0][1];
            $wallPrice = $guidrailPrices[$wallKey] ?? 0;
            $sidePrice = $guidrailPrices[$sideKey] ?? 0;
            $guidrail_price = ($wallPrice + $sidePrice);
        }
    } else {
        preg_match('/\d{2,4}\*\d{2,4}/', $guideType, $match);
        if (!empty($match[0])) {
            $guideSpec = $match[0];
            $guideKey = $baseKey . '|' . $guideSpec;
            $guidrail_price = ($guidrailPrices[$guideKey] ?? 0) * 2;
        }
    }

    return ceil($guidrail_price);
}

function calculateShaftPrice(array $item, PDO $pdo): float {
    $tablename = 'price_shaft';
    $query = "SELECT itemList FROM $tablename WHERE is_deleted IS NULL OR is_deleted = 0 ORDER BY NUM LIMIT 1";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $itemList = json_decode($row['itemList'], true);
    
    $sum_shaft_price = 0;
    $shaft_counts = [];

    addShaftPrice($item['col59'], $itemList, '3', '300', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col60'], $itemList, '4', '3000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col61'], $itemList, '4', '4500', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col62'], $itemList, '4', '6000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col63'], $itemList, '5', '6000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col64'], $itemList, '5', '7000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col65'], $itemList, '5', '8200', $sum_shaft_price, $shaft_counts);

    return $sum_shaft_price;
}
