<?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 calculateSlatAmount($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) {
        $su = floatval($item['col15']); // 수량(철재는 col15)
        if (isset($item['col5']) && !empty($item['col5'])) {
            // 각 행의 항목별 금액을 저장할 배열 초기화
            $rowItemDetails = [
                '검사비' => (int)$inspectionFee * $su,
                '주자재(슬랫)' => 0,
                '조인트바' => 0,
                '모터' => 0,
                '매립/노출 연동제어기(뒷박스 있는 경우 포함)' => 0,
                '케이스' => 0,
                '케이스용 연기차단재' => 0,
                '케이스 마구리' => 0,
                '모터 받침용 앵글' => 0,
                '가이드레일' => 0,
                '레일용 연기차단재' => 0,
                '하장바' => 0,
                '감기샤프트' => 0,
                '각파이프 총액' => 0,                
                '앵글' => 0,
                'TotalAmount' => 0  ,  // 전체금액 합계
                'slatcheck' => $slatcheck,
                'partscheck' => $partscheck,
                'steel' => $steel,
                'motor' => $motor,
                'warranty' => $warranty
            ];

            $sums[$counter] = $inspectionFee * $su; // 검사비 합계
            $rowItemDetails['TotalAmount'] = $sums[$counter] ;

            // 주자재(슬랫) 및 조인트바 단가
            $tablename_mainslat = 'price_raw_materials';            
            $query = "SELECT itemList FROM $tablename_mainslat 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;
            $price_jointbar = 0;
            foreach ($rows as $row) {
                $itemList = json_decode($row['itemList'], true);
                $price_raw_materials = slatPrice($itemList, '슬랫', '방화');
                if(!empty($price_raw_materials)) break;
            }
            foreach ($rows as $row) {
                $itemList = json_decode($row['itemList'], true);
                $price_jointbar = slatPrice($itemList, '슬랫', '조인트바');
                if(!empty($price_jointbar)) break;
            }

            // 면적 계산 (철재는 높이+400)
            $calculateHeight = floatval($item['col9']) + 400;
            $area = floatval($item['col10']) * $calculateHeight / 1000000;

            // 면적 계산            
            $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 + 50;  // 기본 350 + 50 = 400 개념임
            $area = $width * $calculateHeight / 1000000;            

            // 주자재(슬랫) 가격
            if($slatcheck == '1') {
                $slat_price = floatval($price_raw_materials * round($area,2));
            }
            else {
                $slat_price = 0;
            }
            $rowItemDetails['주자재(슬랫)'] = $slat_price * $su;
            $sums[$counter] += round($rowItemDetails['주자재(슬랫)']);
            $rowItemDetails['TotalAmount'] += $rowItemDetails['주자재(슬랫)'] ;

            // 조인트바 가격 (슬랫 공식 적용)
            if($slatcheck == '1') {            
                $jointbar_price = intval($price_jointbar) * floatval($item['col76']) ;
                $rowItemDetails['조인트바'] = $jointbar_price;
                $sums[$counter] += round($rowItemDetails['조인트바']);
                $rowItemDetails['TotalAmount'] += $rowItemDetails['조인트바'] ;
            }
            else {
                $jointbar_price = 0;
            }

            // 모터 가격
            // 모터 견적가 포함 여부 확인
            $motor_supplier = $item['col19_brand'];

            // 모터 단가 데이터 로드
            $tablename_motor = 'price_motor';
            $query = "SELECT itemList FROM $tablename_motor 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 ($motor_supplier === '경동(견적가포함)' && $motor == '1') {
                // 모터 가격 계산
                $motorSpec = $item['col20'];
                $motorSpec = preg_replace('/[a-zA-Z]/', '', $motorSpec);
                $motorUnit_price = getPriceForMotor($motorSpec, $itemList);
                $rowItemDetails['모터'] = round($motorUnit_price * $su);
                $sums[$counter] += $rowItemDetails['모터'];
                $rowItemDetails['TotalAmount'] += $rowItemDetails['모터'];
            }
            
            // 연동제어기 가격 계산 단가표의 2번 열의 매립형/노출형/뒷박스 타입 추출
            $price1 = calculateControllerSpec($item['col16'], $itemList, '매립형');
            $price2 = calculateControllerSpec($item['col17'], $itemList, '노출형');
            $price3 = calculateControllerSpec($item['col18'], $itemList, '뒷박스');

            $controller_price = 
                $price1 * floatval($item['col16']) + 
                $price2 * floatval($item['col17']) + 
                $price3 * floatval($item['col18']);

            $rowItemDetails['매립/노출 연동제어기(뒷박스 있는 경우 포함)'] = round($controller_price);
            $sums[$counter] += $rowItemDetails['매립/노출 연동제어기(뒷박스 있는 경우 포함)'];
            $rowItemDetails['TotalAmount']  += $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['col37'] === 'custom') {
                $dimension = $item['col37_custom'];
            } else {
                $dimension = $item['col37'];
            }

            $shutter_price = 0;
            if (array_key_exists($dimension, $shutterBoxprices)) {
                $shutter_price = ($shutterBoxprices[$dimension] / 1000);
            } else {
                $basicbox_price = round($shutterBoxprices['650*550'], 2);
                $basicbox_pricePermeter = $basicbox_price/(650*550/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['col38']) / 1000, 2); // 철재는 col38


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

            // 가이드레일 가격 (철재는 col24)
            $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['col24']) / 1000, 2);
            $guidrail_price = round($guidrail_price);
            if($steel == '1') {
            $rowItemDetails['가이드레일'] = round($guidrail_price * $total_length * $su) ;
                $sums[$counter] += round($rowItemDetails['가이드레일']);
                $rowItemDetails['TotalAmount']  += $rowItemDetails['가이드레일'] ;
            }
            else {
                $rowItemDetails['가이드레일'] = 0;
            }

            // 샤프트 가격 계산
            $shaft_price = calculateShaftPrice($item, $pdo);
            if($partscheck == '1') {
                $rowItemDetails['감기샤프트'] = round($shaft_price);
                $sums[$counter] += round($rowItemDetails['감기샤프트']);
                $rowItemDetails['TotalAmount']  += $rowItemDetails['감기샤프트'] ;
            }
            else {
                $rowItemDetails['감기샤프트'] = 0;
            }

            // 각파이프 총액 계산 (slat_view_original.php와 동일하게)
            $pipe_price_3000 = 0;
            $pipe_price_6000 = 0;
            $pipe_price_3000_surang = intval(str_replace(',', '', $item['col74']));
            $pipe_price_6000_surang = intval(str_replace(',', '', $item['col75']));
            $tablename = 'price_pipe';
            $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) {
                $pipe_price_3000 = calculatePipe($itemList, '1.4', '3000');
                $pipe_price_6000 = calculatePipe($itemList, '1.4', '6000');
            }
            $total_pipe_price = ($pipe_price_3000 * $pipe_price_3000_surang) + ($pipe_price_6000 * $pipe_price_6000_surang);
            if($partscheck == '1') {
                $rowItemDetails['각파이프 총액'] = $total_pipe_price;
                $sums[$counter] += round($rowItemDetails['각파이프 총액']);
                $rowItemDetails['TotalAmount']  += $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 = round(floatval($unitprice_clean));
                if ($seconditem == '케이스용 연기차단재' && $unitprice_value > 0) {
                    $boxSmokeBanPrices = $unitprice_value;
                }
            }
            $boxSmokeBanPrices = round($boxSmokeBanPrices);
            $total_length = round(floatval($item['col38']) / 1000,2);
            if($steel == '1') { // 절곡체크박스
                $rowItemDetails['케이스용 연기차단재'] = round($boxSmokeBanPrices * $total_length) * $su;
                $sums[$counter] += round($rowItemDetails['케이스용 연기차단재']);
                $rowItemDetails['TotalAmount']  += $rowItemDetails['케이스용 연기차단재'] ;
            }
            else {
                $rowItemDetails['케이스용 연기차단재'] = 0;
            }

            // 케이스 마구리
            $maguriPrices = 0;
            $maguriCol = $item['col46'];
            $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($maguriPrices > 0 && !empty($item['col47']) && $steel == '1') {  // 절곡체크박스
                 $rowItemDetails['케이스 마구리'] = $maguriPrices * $su;
                $sums[$counter] += round($rowItemDetails['케이스 마구리']);
                $rowItemDetails['TotalAmount']  += $rowItemDetails['케이스 마구리'] ;
            }

            // 모터 받침용 앵글
            $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(empty($item['col21'])){
                $bracket_size = searchBracketSize($item['col13'], $item['col22']);
            }else{
                $bracket_size = $item['col21'];
            }
            // $rowItemDetails['모터중량']  = $item['col13'];
            // $rowItemDetails['모터인치']  = $item['col22'];
            $rowItemDetails['브라켓크기']  = $bracket_size;
            if ($itemList) {
                // 브라켓크기가 정해져있지 않으면 없음으로 처리
                if(trim($item['col23']) != '' && trim($item['col23']) != '0') { // 앵글사이즈가 있으면 계산한다.
                    $price_angle = calculateAngleBracket_slat($item['col15'], $itemList, $bracket_size ); //철재모터 스크린과 다름 수량,리스트,브라켓 크기 전달
                }
            }
            $price_angle = round($price_angle);
            $rowItemDetails['모터 받침용 앵글'] = $price_angle * $su * 4;
            $sums[$counter] += round($rowItemDetails['모터 받침용 앵글']);
            $rowItemDetails['TotalAmount']  += $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['col32']) || !isEmptyOrZero($item['col33']) || !isEmptyOrZero($item['col34']) || !isEmptyOrZero($item['col35']) || !isEmptyOrZero($item['col36']) )) {
                    $guiderailSmokeBanPrices = $unitprice_value;
                }
            }
            $guiderailSmokeBanPrices = round($guiderailSmokeBanPrices);
            $total_length = round(floatval($item['col24']) / 1000, 2);
            if($steel == '1') {
            $rowItemDetails['레일용 연기차단재'] = $guiderailSmokeBanPrices * $total_length * $su;
                $sums[$counter] += round($rowItemDetails['레일용 연기차단재']);
                $rowItemDetails['TotalAmount']  += $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['col50']) || !isEmptyOrZero($item['col51']))) {
                    $bottomBarPrices = $unitprice_value;
                }
            }
            $total_length = intval($item['col49']) ;
            $total_length = round($total_length / 1000, 2) * $su;   
            if($steel == '1') {
                $rowItemDetails['하장바'] = round($bottomBarPrices * $total_length);
                $sums[$counter] += round($rowItemDetails['하장바']);
                $rowItemDetails['TotalAmount']  += $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);

            $mainangle_price = calculateMainAngle(1, $itemList, '앵글4T', '2.5');
            $mainangle_surang = intval(str_replace(',', '', $item['col77']));
            if($partscheck == '1') {
                $rowItemDetails['앵글'] = round($mainangle_price * $mainangle_surang);
                $sums[$counter] += $rowItemDetails['앵글'];            
                $rowItemDetails['TotalAmount']  += $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 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['col61'], $itemList, '4', '3000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col62'], $itemList, '4', '4500', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col63'], $itemList, '4', '6000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col64'], $itemList, '5', '6000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col65'], $itemList, '5', '7000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col66'], $itemList, '5', '8200', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col67'], $itemList, '6', '3000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col68'], $itemList, '6', '6000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col69'], $itemList, '6', '7000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col70'], $itemList, '6', '8000', $sum_shaft_price, $shaft_counts);
    addShaftPrice($item['col71'], $itemList, '8', '8200', $sum_shaft_price, $shaft_counts);

    return $sum_shaft_price;
}

// === 실행 ===
// try {
//     if (empty($_POST['estimateList'])) {
//         throw new Exception('estimateList 파라미터가 없습니다.');
//     }
//     $details = json_decode((string)$_POST['estimateList'], true);
//     if (!is_array($details)) {
//         throw new Exception('JSON 파싱 오류');
//     }
//     $pdo = db_connect();
//     $inspectionFee = $_POST['inspectionFee'] ?? '0';
//     $result = calculateSlatAmount($details, $inspectionFee, $pdo);
    
//     // Transform the result into the expected format
//     $response = [
//         'success' => true,
//         'data' => [
//             'details' => $result['details'],            
//             'itemDetails' => $result['itemDetails'],
//             'surangSum' => $result['surangSum']
//         ]
//     ];
    
//     echo json_encode($response, JSON_UNESCAPED_UNICODE);

// } catch (Exception $e) {
//     error_log('get_screen_amount ERROR: '.$e->getMessage());
//     echo json_encode(['success' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE);
// }
