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

$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';
$num = isset($_REQUEST['num']) ? $_REQUEST['num'] : '';

header("Content-Type: application/json");
include '_request.php';
$tablename = 'work';

// 테이블 데이터 JSON 파싱
$accountList_jsondata = isset($_POST['accountList']) ? json_decode($_POST['accountList'], true) : null;
$claimList_jsondata = isset($_POST['claimList']) ? json_decode($_POST['claimList'], true) : null;
$equipmentList_jsondata = isset($_POST['equipmentList']) ? json_decode($_POST['equipmentList'], true) : null;

// 테이블 데이터 JSON 파싱
$estimateList_jsondata = isset($_POST['estimateList']) ? json_decode($_POST['estimateList'], true) : null;

$before_estimateList_jsondata = $estimateList_jsondata;

// Determine work state
$state_work = 0;
if (substr($workday, 0, 2) == "20") $state_work = 1;
if (substr($endworkday, 0, 2) == "20") $state_work = 2;

$workStatus = "계약전";
switch ($state_work) {    
    case 1:
        $workStatus = "시공중";
        break;
    case 2:
        $workStatus = "시공완료";  
        break;
    default:
        $workStatus = "착공전";
        break;
}

// Determine AS state
$state_as = 0;
if (substr($asday, 0, 2) == "20") $state_as = 1;
if (substr($asproday, 0, 2) == "20") $state_as = 2;
if (substr($asendday, 0, 2) == "20") $state_as = 3;

$as_state = "미접수";
switch ($state_as) {
    case 1:
        $as_state = "접수완료";
        break;
    case 2:
        $as_state = "처리예약";
        break;
    case 3:
        $as_state = "처리완료";
        break;
}

$state_cablework = 0;
if (substr($cableday, 0, 2) == "20") $state_cablework = 1;
if (substr($endcableday, 0, 2) == "20") $state_cablework = 2;

$cableworkStatus = "";
switch ($state_cablework) {
    case 1:
        $cableworkStatus = "결선중";
        break;
    case 2:
        $cableworkStatus = "결선완료";
        break;
    default:
        $cableworkStatus = "";  // 기본값으로 빈 문자열
        break;
}

// 파일 업로드 처리
$files = $_FILES["upfile"];
$row_indices_for_upfile = isset($_POST['row_index_for_upfile']) && is_array($_POST['row_index_for_upfile']) ? $_POST['row_index_for_upfile'] : [];
$upload_dir = '../uploads/';

$file_index_array = [];
$deleted_files = isset($_POST['del_file']) && is_array($_POST['del_file']) ? $_POST['del_file'] : [];

if ($mode !== "delete") {
	foreach ($estimateList_jsondata as $key => &$row) {
		$row_index = $row['row_index']; // 현재 행의 인덱스
		$file_index_array[] = $row['row_index']; // 현재 행의 인덱스

		// 파일 삭제 처리
		if (in_array($row_index, $deleted_files)) {
			if (!empty($row['col6'])) { // col6에 저장된 파일 이름이 있는 경우
				$file_to_delete = $upload_dir . $row['col6'];
				if (file_exists($file_to_delete)) {
					unlink($file_to_delete); // 파일 삭제
				}
			}
			$row['col5'] = '';  // 파일 이름을 비움
			$row['col6'] = '';  // 서버에 저장된 파일 이름을 비움
		} else {
			// 파일 업로드 처리
			if (in_array($row_index, $row_indices_for_upfile)) {
				$file_index = array_search($row_index, $row_indices_for_upfile);
				if (!empty($files['name'][$file_index])) {
					if ($files['error'][$file_index] === UPLOAD_ERR_OK) {
						$file_name = basename($files['name'][$file_index]);
						$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
						$new_file_name = date("Y_m_d_H_i_s") . "_" . $row_index . "." . $file_ext;
						$uploaded_file_path = $upload_dir . $new_file_name;

						if (move_uploaded_file($files['tmp_name'][$file_index], $uploaded_file_path)) {
							// 파일이 성공적으로 업로드된 경우에만 col5와 col6을 업데이트
							$row['col5'] = $file_name;
							$row['col6'] = $new_file_name;
						} else {
							echo json_encode(['error' => '파일 업로드 실패']);
							exit;
						}
					} elseif ($files['error'][$file_index] !== UPLOAD_ERR_NO_FILE) {
						// 오류 처리 코드...
					}
				}
			} else {
				// 파일이 업로드되지 않은 경우 기존 col5, col6 값을 유지하도록 합니다.
				$row['col5'] = $row['col5'] ?? '';  // 기존 값 유지
				$row['col6'] = $row['col6'] ?? '';  // 기존 값 유지
			}
		}
	}

}
// 전달된 데이터를 디버그로 출력
// file_put_contents('php://stderr', "Updated estimateList_jsondata: " . print_r($estimateList_jsondata, true));

// 모든 변수를 $searchtag에 추가
$searchtag = $workStatus . ' ' .
             $id . ' ' .
             $name . ' ' .
             $nick . ' ' .
             $subject . ' ' .
             $content . ' ' .
             $is_html . ' ' .
             $accountnote . ' ' .
             $totalbill . ' ' .
             $workplacename . ' ' .
             $chargedperson . ' ' .
             $address . ' ' .
             $firstord . ' ' .
             $firstordman . ' ' .
             $firstordmantel . ' ' .
             $secondord . ' ' .
             $secondordman . ' ' .
             $secondordmantel . ' ' .
             $worklist . ' ' .
             $motormaker . ' ' .
             $power . ' ' .
             $worker . ' ' .
             $cablestaff . ' ' .
             $asman . ' ' .
             $asorderman . ' ' .
             $asordermantel . ' ' .
             $aslist . ' ' .
             $asresult . ' ' .
             $ashistory . ' ' .
             $comment . ' ' .
             $claimperson . ' ' .
             $claimtel . ' ' .
             $as_state . ' ' .
             $as_refer . ' ' .
             $change_worklist . ' ' .
             $checkbox . ' ' .
             $checkstep . ' ' .
             $checkreceivable . ' ' .
             $asfee . ' ' .
             $asfee_estimate . ' ' .
             $as_check . ' ' .
             $outputmemo . ' ' .			 
			 $certifiedInspector .  // 부착
			 $cableworkStatus . 
			 $equipmentList . 
			 $motorwirestatus .  // 모터전원 유무선
			 $checkbond .  // 채권추심
			 $site_agent .  // 현장대리인
             $aswriter ;

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

// 처음에 컬럼을 잘못 만들어서 계속 따라다닌다. subject가 workplacename 의미
$subject= $workplacename;

require_once("../lib/mydb.php");
$pdo = db_connect();

if ($mode == "modify") {
    $update_day = date("Y-m-d");

    try {
        $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " " . $update_log . "&#10";
        $pdo->beginTransaction();
        $sql = "UPDATE $DB.$tablename SET subject=?, content=?, is_html=?, receivable=?, workplacename=?, chargedperson=?, 
                address=?, firstord=?, firstordman=?, firstordmantel=?, secondord=?, 
                secondordman=?, secondordmantel=?, worklist=?, motormaker=?, power=?, 
                workday=?, worker=?, cableday=?, cablestaff=?, 
                asday=?, asorderman=?, asordermantel=?, aslist=?, asresult=?, ashistory=?, comment=?, endworkday=?, endcableday=?, 
                totalbill=?, accountnote=?, asproday=?, asendday=?, asman=?,                                 
                claimperson=?, claimtel=?, workStatus=?, as_state=?, regist_day=?, sum_bill=?, sum_receivable=?, sum_deposit=?, sum_claimamount=?, sum_estimate=?, as_refer=?, 
                change_worklist=?, checkbox=?, checkstep=?, asfee=?, asfee_estimate=?, promiseday=?, as_check=?, outputmemo=?, aswriter=?, setdate=?, 
                as_step=?, update_day=?, is_deleted=?, searchtag=?, update_log=?,
				accountList=?, estimateList=?, claimList=?,
				issued_receivable=?, issued_amount = ?, decided_estimate = ?, total_receivable = ?, warrantyFromDate = ?, warrantyToDate = ?, warrantyPeriod = ?, total_deposit=? ,
				cableworkStatus = ?, certifiedInspector = ?, certifiedLabelAttachedDate = ? , equipmentList=? , checkreceivable=?, motorwirestatus = ?, checkbond = ?, warrantyMemo =?, site_agent = ?				
                WHERE num=? LIMIT 1";
 
        $params = [
            $subject, $content, $is_html, $receivable, $workplacename, $chargedperson, $address, $firstord, $firstordman, $firstordmantel,
			$secondord, $secondordman, $secondordmantel, $worklist, $motormaker, $power, $workday, $worker, $cableday, $cablestaff, 
			$asday, $asorderman, $asordermantel, $aslist, $asresult, $ashistory, $comment, $endworkday, $endcableday, $totalbill,
			$accountnote, $asproday, $asendday, $asman, $claimperson, $claimtel, $workStatus, $as_state, $regist_day, $sum_bill,
			$sum_receivable, $sum_deposit, $sum_claimamount, $sum_estimate, $as_refer, $change_worklist, $checkbox, $checkstep, $asfee, $asfee_estimate,
			$promiseday, $as_check, $outputmemo, $aswriter, $setdate, $as_step, $update_day, $is_deleted, $searchtag, $update_log, json_encode($accountList_jsondata), json_encode($estimateList_jsondata),json_encode($claimList_jsondata), $issued_receivable, 
			$issued_amount, $decided_estimate, $total_receivable, $warrantyFromDate, $warrantyToDate, $warrantyPeriod, $total_deposit, $cableworkStatus, $certifiedInspector, $certifiedLabelAttachedDate,$equipmentList, $checkreceivable, $motorwirestatus, $checkbond, $warrantyMemo, $site_agent, $num
        ];

        $stmh = $pdo->prepare($sql);
        $stmh->execute($params);
        $pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        echo json_encode(['error' => $Exception->getMessage()]);
        exit;
    }
}

if ($mode == "insert") {
    // Insert new record
    try {
        $regist_day = date("Y-m-d");
        $update_day = date("Y-m-d");
        $update_log = date("Y-m-d H:i:s") . " - " . $_SESSION["name"] . " ";
$pdo->beginTransaction();
$sql = "INSERT INTO $DB.$tablename (id, name, nick, subject, workplacename, content, is_html,                                
        receivable, chargedperson, address, firstord, firstordman, firstordmantel, secondord, 
        secondordman, secondordmantel, worklist, motormaker, power, workday, worker, cableday, cablestaff, 
        asday, asorderman, asordermantel, aslist, asresult, ashistory, comment,                 
        totalbill, accountnote, asproday, asendday, asman,                         
        claimperson, claimtel, workStatus, as_state, sum_bill, sum_receivable, sum_deposit, sum_claimamount, sum_estimate, as_refer, change_worklist, checkbox, checkstep, asfee, asfee_estimate, promiseday, as_check, outputmemo, aswriter, setdate, 
        as_step, regist_day, update_day, is_deleted, searchtag, update_log, accountList, estimateList, claimList,issued_receivable, issued_amount, decided_estimate, total_receivable, warrantyFromDate, warrantyToDate, warrantyPeriod, total_deposit,
		endworkday, endcableday, cableworkStatus , certifiedInspector , certifiedLabelAttachedDate, equipmentList , checkreceivable, motorwirestatus , checkbond, warrantyMemo, site_agent
    ) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
            ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 			
			?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";

$params = [
    $_SESSION["userid"], $_SESSION["name"], $_SESSION["name"], $subject, $workplacename, $content, $is_html, $receivable, $chargedperson, $address,
	$firstord, $firstordman, $firstordmantel, $secondord, $secondordman, $secondordmantel, $worklist, $motormaker, $power, $workday, 
	$worker, $cableday, $cablestaff, $asday, $asorderman, $asordermantel, $aslist, $asresult, $ashistory, $comment,            
    $totalbill, $accountnote, $asproday, $asendday, $asman, $claimperson, $claimtel, $workStatus, $as_state, $sum_bill,
	$sum_receivable, $sum_deposit, $sum_claimamount, $sum_estimate, $as_refer, $change_worklist, $checkbox, $checkstep, $asfee, $asfee_estimate, 
	$promiseday, $as_check, $outputmemo, $aswriter, $setdate, $as_step, $regist_day, $update_day, $is_deleted, $searchtag, $update_log, json_encode($accountList_jsondata), json_encode($estimateList_jsondata), json_encode($claimList_jsondata),
    $issued_receivable, $issued_amount, $decided_estimate, $total_receivable, $warrantyFromDate, $warrantyToDate, $warrantyPeriod, $total_deposit, $endworkday, $endcableday,
	$cableworkStatus, $certifiedInspector, $certifiedLabelAttachedDate, $equipmentList, $checkreceivable, $motorwirestatus, $checkbond, $warrantyMemo, $site_agent
];

		$stmh = $pdo->prepare($sql);
		$stmh->execute($params);
		$pdo->commit();
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        echo json_encode(['error' => $Exception->getMessage()]);
        exit;
    }
}

if ($mode == "delete") {
    try {
        $pdo->beginTransaction();  // 트랜잭션 시작
        $query = "UPDATE " . $DB . ".{$tablename} SET is_deleted=1 WHERE num=? LIMIT 1";
        $stmh = $pdo->prepare($query);
        $params = [$num];
        $stmh->execute($params);
        $pdo->commit();  // 데이터 변경 사항을 커밋
    } catch (PDOException $Exception) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();  // 오류 발생 시 롤백
        }
        print "오류: " . $Exception->getMessage();
    }
}

if ($mode == "insert" || $mode == "copy") {
    try {
        $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"]; 
    } catch (PDOException $Exception) {
        error_log("오류: " . $Exception->getMessage());  // 오류 로깅
        echo "시스템 오류가 발생했습니다. 관리자에게 문의하세요.";  // 사용자 친화적 메시지
    } 
}
    
$data = [   
 'num' => $num,
 'mode' => $mode
 // '$row_indices_for_upfile' => $row_indices_for_upfile,
 // '$file_index_array' => $file_index_array,
 // '$before_estimateList_jsondata' => $before_estimateList_jsondata,
 // '$estimateList_jsondata' => $estimateList_jsondata
]; 
 
echo json_encode($data, JSON_UNESCAPED_UNICODE);
?>
