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

header("Content-Type: application/json");

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

require_once($_SERVER['DOCUMENT_ROOT'] . "/common.php");

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

include '_request.php';
        
$status = $_REQUEST["status"] ?? '';               
$htmltext = $_REQUEST["htmltext"] ?? '';               

// 파일 업로드 처리 함수
function handleFileUpload($files, $num, $tablename, $item) {
    if (empty($files) || !is_array($files)) {
        return [];
    }
    
    $uploadedFiles = [];
    $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/' . $tablename . '/' . $item . '/';
    
    // 디렉토리가 없으면 생성
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    foreach ($files as $file) {
        if ($file['error'] === UPLOAD_ERR_OK) {
            try {
                // 파일명 중복 방지를 위한 타임스탬프 추가
                $timestamp = time();
                $filename = $timestamp . '_' . $file['name'];
                $filepath = $uploadDir . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $filepath)) {
                    $uploadedFiles[] = [
                        'filename' => $filename,
                        'realname' => $file['name'],
                        'size' => $file['size'],
                        'type' => $file['type'],
                        'path' => $filepath
                    ];
                }
            } catch (Exception $e) {
                error_log("파일 업로드 오류: " . $e->getMessage());
            }
        }
    }
    
    return $uploadedFiles;
}

// 이름찾아 결재 아이디 찾아내기
try {
    $membersql = "SELECT * FROM {$DB}.member WHERE name = ?";
    $stmh = $pdo->prepare($membersql); 
    $stmh->bindValue(1, trim($author), PDO::PARAM_STR); 
    $stmh->execute(); 
    $rowMember = $stmh->fetch(PDO::FETCH_ASSOC);

    // 조회된 데이터가 있는지 확인 후 설정
    $first_approval_id = trim($rowMember['first_approval_id']) ?? ''; // 값이 없으면 빈 문자열
    $first_approval_name = trim($rowMember['first_approval_name']) ?? '';

} catch (PDOException $Exception) {
    print "오류: " . $Exception->getMessage();
}

if ($mode == "modify") {      
    try {
        $sql = "select * from " . $DB . "." . $tablename . " where num=?";
        $stmh = $pdo->prepare($sql); 
        $stmh->bindValue(1, $num, PDO::PARAM_STR); 
        $stmh->execute(); 
        $row = $stmh->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        print "오류: " . $Exception->getMessage();
    }
	
	// 전자 결재에 보여질 내용 data 수정 update       
	
		$data = array(
			"author" => $author,
			"al_item" => $al_item,
			"al_askdatefrom" => $al_askdatefrom,
			"al_askdateto" => $al_askdateto,
			"al_usedday" => $al_usedday,
			"al_content" => $al_content,
			"e_line_id" => $e_line_id,
			"e_line" => $e_line,
			"approvalLines" => $approvalLines,
			"first_approval_name" => $first_approval_name,
			"first_approval_id" => $first_approval_id
		);

		$contents = json_encode($data, JSON_UNESCAPED_UNICODE);	
		
    try {
        $pdo->beginTransaction();   
        $sql = "update " . $DB . "." . $tablename . " set author_id=?, author=?, registdate=?, al_item=?, al_askdatefrom=?, al_askdateto=?, al_usedday=?, al_content=?, status=?, al_part=?, contents=?, al_company=? ";
        $sql .= " where num=? LIMIT 1";     
       	$stmh = $pdo->prepare($sql); 
		$stmh->bindValue(1, $author_id, PDO::PARAM_STR);  
		$stmh->bindValue(2, $author, PDO::PARAM_STR);  
		$stmh->bindValue(3, $registdate, PDO::PARAM_STR);  
		$stmh->bindValue(4, $al_item, PDO::PARAM_STR);  
		$stmh->bindValue(5, $al_askdatefrom, PDO::PARAM_STR);  
		$stmh->bindValue(6, $al_askdateto, PDO::PARAM_STR);      
		$stmh->bindValue(7, $al_usedday, PDO::PARAM_STR);        
		$stmh->bindValue(8, $al_content, PDO::PARAM_STR);        
		$stmh->bindValue(9, $status, PDO::PARAM_STR);          
		$stmh->bindValue(10, $al_part, PDO::PARAM_STR);           
		$stmh->bindValue(11, $contents, PDO::PARAM_STR);           
		$stmh->bindValue(12, $al_company, PDO::PARAM_STR);           
		$stmh->bindValue(13, $num, PDO::PARAM_STR);      
        
        $stmh->execute();
        $pdo->commit(); 
    } catch (PDOException $Exception) {
        $pdo->rollBack(); 
        print "오류: " . $Exception->getMessage();
    }                        
}


if ($mode == "insert") {    
    try {
        $pdo->beginTransaction();

        // Read and decode the JSON file
        // $jsonString = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/member/Company_approvalLine_.json');
        // $approvalLines = json_decode($jsonString, true);
		
        // Default values for e_line_id and e_line
		
		// $first_approval_id = isset($row["first_approval_id"]) ? $row["first_approval_id"] : '';
		// $first_approval_name = isset($row["first_approval_name"]) ? $row["first_approval_name"] : '';	
		
        $e_line_id = $first_approval_id;
        $e_line = $first_approval_name ;

        // // Check if decoded JSON is an array and process it
        // if (is_array($approvalLines)) {
            // foreach ($approvalLines as $line) {
                // if ($al_company == $line['savedName']) {  // 회사이름이 같으면 결재라인 지정 결재라인은 회사명으로 만든다
                    // foreach ($line['approvalOrder'] as $order) {
                        // $e_line_id .= $order['user-id'] . '!';
                        // $e_line .= $order['name'] . '!';
                    // }
                    // break;
                // }
            // }
        // }

        // Set status based on the part
        $status ='send';
		$e_title = '연차신청';
		
// 전자 결재에 보여질 내용 data 수정 update       

		$data = array(
			"author" => $author,
			"al_item" => $al_item,
			"al_askdatefrom" => $al_askdatefrom,
			"al_askdateto" => $al_askdateto,
			"al_usedday" => $al_usedday,
			"al_content" => $al_content,
			"e_line_id" => $e_line_id,
			"e_line" => $e_line,
			"approvalLines" => $approvalLines,
			"first_approval_name" => $first_approval_name,
			"first_approval_id" => $first_approval_id
		);

		$contents = json_encode($data, JSON_UNESCAPED_UNICODE);		
		
		$eworks_item = '연차';

        // SQL statement with additional fields for e_line_id, e_line, and status
        $sql = "INSERT INTO " . $DB . "." . $tablename . " (author_id, author, registdate, al_item, al_askdatefrom, al_askdateto, al_usedday, al_content, status,  al_part, e_line_id, e_line, e_title, contents, eworks_item, al_company) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $author_id, PDO::PARAM_STR);  
        $stmh->bindValue(2, $author, PDO::PARAM_STR);  
        $stmh->bindValue(3, $registdate, PDO::PARAM_STR);  
        $stmh->bindValue(4, $al_item, PDO::PARAM_STR);  
        $stmh->bindValue(5, $al_askdatefrom, PDO::PARAM_STR);  
        $stmh->bindValue(6, $al_askdateto, PDO::PARAM_STR);      
        $stmh->bindValue(7, $al_usedday, PDO::PARAM_STR);        
        $stmh->bindValue(8, $al_content, PDO::PARAM_STR);        
        $stmh->bindValue(9, $status, PDO::PARAM_STR);          
        $stmh->bindValue(10, $al_part, PDO::PARAM_STR);  
        $stmh->bindValue(11, rtrim($e_line_id, '!'), PDO::PARAM_STR);
        $stmh->bindValue(12, rtrim($e_line, '!'), PDO::PARAM_STR);        
        $stmh->bindValue(13, $e_title, PDO::PARAM_STR);
        $stmh->bindValue(14, $contents, PDO::PARAM_STR);
        $stmh->bindValue(15, $eworks_item, PDO::PARAM_STR);
        $stmh->bindValue(16, $al_company, PDO::PARAM_STR);

        $stmh->execute();
        $pdo->commit();
        
        // 신규 레코드 번호 가져오기
        $sql = "SELECT num FROM {$DB}.{$tablename} ORDER BY num DESC LIMIT 1";
        $stmh = $pdo->prepare($sql);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);
        $num = $row["num"];
        
        // 임시 키가 있는 경우 picuploads 테이블에서 임시키를 정식 num으로 업데이트
        if (!empty($temp_key)) {
            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, $temp_key, PDO::PARAM_STR);
                $stmh->execute();
                $pdo->commit();
            } catch (PDOException $Exception) {
                $pdo->rollBack();
                error_log("임시키 업데이트 오류: " . $Exception->getMessage());
            }
        }
        
    } catch (PDOException $Exception) {
        $pdo->rollBack();
        print "오류: " . $Exception->getMessage();
    }
}

if ($mode == "delete") {      
    try {
        $pdo->beginTransaction();   
        $sql = "update " . $DB . "." . $tablename . " set is_deleted=? ";
        $sql .= " where num=? LIMIT 1";     
        $stmh = $pdo->prepare($sql); 
        $stmh->bindValue(1, true, PDO::PARAM_STR);  
        $stmh->bindValue(2, $num, PDO::PARAM_STR);  // Binding the $num variable

        $stmh->execute();
        $pdo->commit(); 
    } catch (PDOException $Exception) {
        $pdo->rollBack(); 
        print "오류: " . $Exception->getMessage();
    }    
    
	$e_line_id = null;
	$e_line = null;
	$approvalLines = null;
	$company = null;

	$data = array(
		"registdate" => $registdate,
		"status" => $status,
		"num" => $num,
		"mode" => $mode,
		"e_line_id" => $e_line_id,
		"e_line" => $e_line,
		"approvalLines" => $approvalLines,
		"first_approval_name" => $first_approval_name,
		"first_approval_id" => $first_approval_id,
		"al_company" => $al_company,
		"al_part" => $al_part,
	);

	
}

echo(json_encode($data, JSON_UNESCAPED_UNICODE));
?>
