<?php
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
header("Content-Type: application/json");


$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';
$num = isset($_REQUEST['num']) ? $_REQUEST['num'] : '';
$tablename = isset($_REQUEST['tablename']) ? $_REQUEST['tablename'] : '';
$tablename_sub = 'output_extra';
isset($_REQUEST["timekey"])  ? $timekey=$_REQUEST["timekey"] :  $timekey='';   // 신규데이터에 생성할때 임시저장키  

include '_request.php';

if (isset($_REQUEST["regist_state"])) { // 등록하면 1로 설정 접수상태
    $regist_state = $_REQUEST["regist_state"];
} else {
    $regist_state = "등록";
    $motor_state = "등록";
}
// 완료처리시 모터는 준비완료 문구 넣어줌

if($regist_state == '완료')
	$motor_state = "준비완료";

// json 형태는 저장할때 주의해야 한다.
if (isset($_POST['screenlist'])) {
    $screen_jsondata = json_decode($_POST['screenlist'], true);
} else {
    // Error handling or fallback
    $screen_jsondata = null;
}

// json 형태는 저장할때 주의해야 한다.
if (isset($_POST['slatlist'])) {
    $slat_jsondata = json_decode($_POST['slatlist'], true);
} else {
    // Error handling or fallback
    $slat_jsondata = null;
}

if (isset($_POST['estimateList'])) {
    $estimateList_jsondata = json_decode($_POST['estimateList'], true);
} else {
    // Error handling or fallback
    $estimateList_jsondata = null;
}

if (isset($_POST['estimateSlatList'])) {
    $estimateSlatList_jsondata = json_decode($_POST['estimateSlatList'], true);
} else {
    // Error handling or fallback
    $estimateSlatList_jsondata = null;
}

if (isset($_POST['estimateList_auto'])) {
    $estimateList_auto_jsondata = json_decode($_POST['estimateList_auto'], true);
} else {
    // Error handling or fallback
    $estimateList_auto_jsondata = null;
}

if (isset($_POST['estimateSlatList_auto'])) {
    $estimateSlatList_auto_jsondata = json_decode($_POST['estimateSlatList_auto'], true);
} else {
    // Error handling or fallback
    $estimateSlatList_auto_jsondata = null;
}

if (isset($_POST['etcList'])) {
    $etcList_jsondata = json_decode($_POST['etcList'], true);
} else {
    // Error handling or fallback
    $etcList_jsondata = null;
}

if (isset($_POST['screen_unapprovedList'])) {
    $screen_unapprovedList_jsondata = json_decode($_POST['screen_unapprovedList'], true);
} else {
    // Error handling or fallback
    $screen_unapprovedList_jsondata = null;
}

if (isset($_POST['slat_unapprovedList'])) {
    $slat_unapprovedList_jsondata = json_decode($_POST['slat_unapprovedList'], true);
} else {
    // Error handling or fallback
    $slat_unapprovedList_jsondata = null;
}

if (isset($_POST['motorList'])) {
    $motorList_jsondata = json_decode($_POST['motorList'], true);
} else {
    // Error handling or fallback
    $motorList_jsondata = null;
}

if (isset($_POST['bendList'])) {
    $bendList_jsondata = json_decode($_POST['bendList'], true);
} else {
    // Error handling or fallback
    $bendList_jsondata = null;
}

if (isset($_POST['controllerList'])) {
    $controllerList_jsondata = json_decode($_POST['controllerList'], true);
} else {
    // Error handling or fallback
    $controllerList_jsondata = null;
}

if (isset($_POST['accountList'])) {
    $accountList_jsondata = json_decode($_POST['accountList'], true);
} else {
    // Error handling or fallback
    $accountList_jsondata = null;
}

if (isset($_POST['deliveryfeeList'])) {
    $deliveryfeeList_jsondata = json_decode($_POST['deliveryfeeList'], true);
} else {
    // Error handling or fallback
    $deliveryfeeList_jsondata = null;
}

if (isset($_POST['detailJson'])) {
    $detailJson_jsondata = json_decode($_POST['detailJson'], true);
} else {
    // Error handling or fallback
    $detailJson_jsondata = null;
}

// 모든 변수를 하나의 문자열로 합칩니다.
$searchtag = $outworkplace . ' ' .
    $orderman . ' ' .
    $outputplace . ' ' .
    $receiver . ' ' .
    $phone . ' ' .
    $comment . ' ' .
    $root . ' ' .
    $steel . ' ' .
    $motor . ' ' .
    $secondord . ' ' .
    $secondordman . ' ' .
    $prodCode . ' ' .
    $warrantyNum . ' ' .
    $warranty . ' ' .
    $lotNum . ' ' .
    $displayText . ' ' .
    $delivery;

// 마지막 공백 제거
$searchtag = rtrim($searchtag, ' ');

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


try {
    if ($mode == "insert" || $mode == "copy") {

        $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " ";
        $pdo->beginTransaction();

        $sql = "INSERT INTO $DB.$tablename (outdate, indate, orderman, outworkplace, outputplace, 
                receiver, phone, comment, con_num, root, 
                steel, motor,  delivery, regist_state, searchtag, 
                update_log, bend_state, motor_state, screen, screen_su, 
                screen_m2, screenlist, slat, slat_su, slat_m2, 
                slatlist, updatecomment, secondord, secondordman, secondordmantel, 
                secondordnum, prodCode, warrantyNum, orderdate, lotNum, 
                warranty, ACIregDate, ACIaskDate, ACIdoneDate, ACImemo, 
                ACIcheck, deliveryfeeList, ACIgroupCode, ACIgroupName, estimate_num, 
                devMode, displayText, slatcheck, partscheck, requestBendingASSY) ";
        $sql .= " VALUES (?, ?, ?, ?, ?,       ?, ?, ?, ?, ?,        ?, ?, ?, ?, ?,        ?, ?, ?, ?, ?,   
                          ?, ?, ?, ?, ?,       ?, ?, ?, ?, ?,        ?, ?, ?, ?, ?,        ?, ?, ?, ?, ?, 
                          ?, ?, ?, ?, ?,       ?, ?, ?, ?, ?)";

        $stmh = $pdo->prepare($sql);

        $stmh->execute([
            $outdate, $indate, $orderman, $outworkplace, $outputplace, 
            $receiver, $phone, $comment, $con_num, $root, 
            $steel, $motor, $delivery, $regist_state, $searchtag, 
            $update_log, $bend_state, $motor_state, $screen, $screen_su, 
            $screen_m2, json_encode($screen_jsondata), $slat, $slat_su, $slat_m2,
            json_encode($slat_jsondata), $updatecomment, $secondord, $secondordman, $secondordmantel,
            $secondordnum, $prodCode, $warrantyNum, $orderdate, $lotNum,
            $warranty, $ACIregDate, $ACIaskDate, $ACIdoneDate, $ACImemo, 
            $ACIcheck, json_encode($deliveryfeeList_jsondata), $ACIgroupCode, $ACIgroupName, $estimate_num, 
            $devMode, $displayText, $slatcheck, $partscheck, $requestBendingASSY
        ]);

        $output_num = $pdo->lastInsertId();

        // output_extra 저장
        $sql2 = "INSERT INTO $DB.$tablename_sub (
            parent_num, detailJson, estimateTotal, EstimateFirstSum, EstimateUpdatetSum, 
            EstimateDiffer, estimateSurang, estimateList, estimateSlatList, estimateList_auto, 
            estimateSlatList_auto, pjnum, major_category, position, makeWidth, 
            makeHeight, maguriWing, screen_unapprovedList, slat_unapprovedList, motorList, 
            bendList, etcList, inspectionFee, controllerList, accountDate, 
            accountList, ET_unapproved, ET_total, EstimateDiscountRate, EstimateDiscount,
            EstimateFinalSum
        ) VALUES (?, ?, ?, ?, ?,    ?, ?, ?, ?, ?,    ?, ?, ?, ?, ?,    ?, ?, ?, ?, ?,   ?, ?, ?, ?, ?,    ?, ?, ?, ?, ?,      ?)";

        $stmh2 = $pdo->prepare($sql2);
        $stmh2->execute([
            $output_num, json_encode($detailJson_jsondata), intval(str_replace(',', '', $estimateTotal)),
            intval(str_replace(',', '', $EstimateFirstSum)), intval(str_replace(',', '', $EstimateUpdatetSum)), intval(str_replace(',', '', $EstimateDiffer)),
            $estimateSurang, json_encode($estimateList_jsondata), json_encode($estimateSlatList_jsondata), json_encode($estimateList_auto_jsondata), json_encode($estimateSlatList_auto_jsondata),
            $pjnum, $major_category, $position, $makeWidth, $makeHeight, $maguriWing,
            json_encode($screen_unapprovedList_jsondata), json_encode($slat_unapprovedList_jsondata),
            json_encode($motorList_jsondata), json_encode($bendList_jsondata), json_encode($etcList_jsondata), 
            intval(str_replace(',', '', $inspectionFee)), json_encode($controllerList_jsondata), $accountDate, json_encode($accountList_jsondata),
            intval(str_replace(',', '', $ET_unapproved)), intval(str_replace(',', '', $ET_total)), 
            floatval(str_replace(',', '', $EstimateDiscountRate)), intval(str_replace(',', '', $EstimateDiscount)), intval(str_replace(',', '', $EstimateFinalSum))    
        ]);

        $pdo->commit();

        if ($timekey != '') {
            $pdo->beginTransaction();   
            $sql = "update ".$DB.".picuploads set parentnum=? where parentnum=? ";
            $stmh = $pdo->prepare($sql); 
            $stmh->execute([$output_num, $timekey]);
            $pdo->commit(); 
        }

        $num = $output_num;
    } else if ($mode == "modify") {
        $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " 수정 ";
        $pdo->beginTransaction();

        $sql = "UPDATE $DB.$tablename SET outdate=?, indate=?, orderman=?, outworkplace=?, outputplace=?, receiver=?, phone=?, comment=?, con_num=?, root=?, steel=?, motor=?, ";
        $sql .= "delivery=?, regist_state=?, searchtag=?, update_log=?, bend_state=?, motor_state=?, screen=?, screen_su=?, screen_m2=?, screenlist=?, slat=?, ";
        $sql .= "slat_su=?, slat_m2=?, slatlist=?, updatecomment=?, secondord=?, secondordman=?, secondordmantel=?, secondordnum=?, prodCode=?, warrantyNum=?, orderdate=?, ";
        $sql .= "lotNum=?, warranty=?, ACIregDate=?, ACIaskDate=?, ACIdoneDate=?, ACImemo=?, ACIcheck=?, deliveryfeeList=?, ACIgroupCode=?, ACIgroupName=?, estimate_num=?, devMode=?, displayText=?, slatcheck=?, partscheck=?, requestBendingASSY=? WHERE num=?";

        $stmh = $pdo->prepare($sql);
        $stmh->execute([
            $outdate, $indate, $orderman, $outworkplace, $outputplace, $receiver, $phone, $comment, $con_num, $root, $steel, $motor, $delivery,
            $regist_state, $searchtag, $update_log, $bend_state, $motor_state, $screen, $screen_su, $screen_m2, json_encode($screen_jsondata),
            $slat, $slat_su, $slat_m2, json_encode($slat_jsondata), $updatecomment, $secondord, $secondordman, $secondordmantel, $secondordnum,
            $prodCode, $warrantyNum, $orderdate, $lotNum,
            $warranty, $ACIregDate, $ACIaskDate, $ACIdoneDate, $ACImemo, $ACIcheck,
            json_encode($deliveryfeeList_jsondata), $ACIgroupCode, $ACIgroupName, $estimate_num, $devMode, $displayText, $slatcheck, $partscheck, $requestBendingASSY, $num
        ]);	

        // output_extra update
        $sql2 = "UPDATE $DB.$tablename_sub SET detailJson=?, estimateTotal=?, EstimateFirstSum=?, EstimateUpdatetSum=?, EstimateDiffer=?, estimateSurang=?, ";
        $sql2 .=" estimateList=?, estimateSlatList=?, estimateList_auto=?, estimateSlatList_auto=?, pjnum=?, major_category=?, position=?, makeWidth=?, makeHeight=?, ";
        $sql2 .=" maguriWing=?, screen_unapprovedList=?, slat_unapprovedList=?, motorList=?, bendList=?,  etcList=?, inspectionFee=?, controllerList=?, accountDate=?, accountList=?, ";
        $sql2 .=" ET_unapproved=?, ET_total=?, EstimateDiscountRate=?, EstimateDiscount=?, EstimateFinalSum=? ";
        $sql2 .=" WHERE parent_num = ? ";

        $stmh2 = $pdo->prepare($sql2);
        $stmh2->execute([
            json_encode($detailJson_jsondata), intval(str_replace(',', '', $estimateTotal)),
            intval(str_replace(',', '', $EstimateFirstSum)), intval(str_replace(',', '', $EstimateUpdatetSum)), intval(str_replace(',', '', $EstimateDiffer)),
            $estimateSurang, json_encode($estimateList_jsondata), json_encode($estimateSlatList_jsondata), json_encode($estimateList_auto_jsondata), json_encode($estimateSlatList_auto_jsondata),
            $pjnum, $major_category, $position, $makeWidth, $makeHeight, $maguriWing,
            json_encode($screen_unapprovedList_jsondata), json_encode($slat_unapprovedList_jsondata),
            json_encode($motorList_jsondata), json_encode($bendList_jsondata), json_encode($etcList_jsondata), 
            intval(str_replace(',', '', $inspectionFee)), json_encode($controllerList_jsondata), 
            $accountDate, json_encode($accountList_jsondata), intval(str_replace(',', '', $ET_unapproved)), intval(str_replace(',', '', $ET_total)),
            floatval(str_replace(',', '', $EstimateDiscountRate)), intval(str_replace(',', '', $EstimateDiscount)), intval(str_replace(',', '', $EstimateFinalSum)), $num 
        ]);

        $pdo->commit();
    } else if ($mode == "delete") {
        $pdo->beginTransaction();
        $sql = "UPDATE $DB.$tablename SET is_deleted='1' WHERE num=?";
        $stmh = $pdo->prepare($sql);
        $stmh->execute([$num]);

        // output_extra 논리 삭제
        $sql2 = "DELETE FROM $DB.$tablename_sub WHERE parent_num = ?";
        $stmh2 = $pdo->prepare($sql2);
        $stmh2->execute([$num]);
        $pdo->commit();
		
	     // 첨부파일 삭제
		try{									
		 $pdo->beginTransaction();
		 $sql1 = "delete from {$DB}.picuploads where parentnum = ? and tablename = ? ";  
		 $stmh1 = $pdo->prepare($sql1);
		 $stmh1->bindValue(1,$num, PDO::PARAM_STR);      		 
		 $stmh1->bindValue(2,$tablename, PDO::PARAM_STR);      
		 $stmh1->execute();  
		 $pdo->commit();		 
		 } catch (Exception $ex) {
			$pdo->rollBack();
			// print "오류: ".$Exception->getMessage();
            throw new Exception($ex->getMessage());
	   } 
    }

    if ($mode == "insert" || $mode == "copy") {
        $sql = "SELECT * FROM $DB.$tablename ORDER BY num DESC LIMIT 1";
        $stmh = $pdo->prepare($sql);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);
        $num = $row["num"];
			

		// 신규데이터인 경우 첨부파일/첨부이미지 추가한 것이 있으면 parentid 변경해줌
		// 신규데이터인경우 num을 추출한 후 view로 보여주기

		if ($mode == "insert" && $timekey != '') {
		  try{
				$pdo->beginTransaction();   
				$sql = "update ".$DB.".picuploads set parentnum=? where parentnum=? ";
				$stmh = $pdo->prepare($sql); 
				$stmh->bindValue(1, $num, PDO::PARAM_STR);          
				$stmh->bindValue(2, $timekey, PDO::PARAM_STR);   
				$stmh->execute();
				$pdo->commit(); 
				} catch (PDOException $Exception) {
				   $pdo->rollBack();
				   // print "오류: ".$Exception->getMessage();
                   throw new Exception($Exception->getMessage());
			   }                         	
			}                         	
			
    }

    $data = [
        'num' => $num,
        'mode' => $mode,
        'prodCode' => $prodCode
    ];

    echo json_encode($data, JSON_UNESCAPED_UNICODE);
} catch (PDOException $Exception) {
    error_log("오류: " . $Exception->getMessage());
    http_response_code(500);
    echo json_encode(['error' => $Exception->getMessage()]);
} catch (Exception $e) {
    error_log("오류: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
?>
