<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDrive.php'; // 세션 등 여러가지 포함됨 파일 포함	

if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    sleep(1);
    header("Location:" . $WebSite . "login/login_form.php");
    exit;
}

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

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

if ($mode === 'update' && $num) { 
    try {
        $sql = "SELECT * FROM " . $tablename . " WHERE num=?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);

        $content = $row['content'];  // 저장된 content 값을 가져옴
        include '_row.php';
		// 콤마 제거 후 숫자로 변환
		$amount = floatval(str_replace(',', '', $row['amount']));
    } catch (PDOException $Exception) {
        echo "오류: " . $Exception->getMessage();
        exit;
    }
} else if ($mode === 'copy' && $num) {
    try {
        $sql = "SELECT * FROM " . $tablename . " WHERE num=?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);

        $content = $row['content'];
        include '_row.php';
        $amount = floatval(str_replace(',', '', $row['amount']));
        $mode = 'insert'; // 복사 모드에서는 새로운 항목으로 등록
        $registDate = date('Y-m-d'); // 현재 날짜로 설정
    } catch (PDOException $Exception) {
        echo "오류: " . $Exception->getMessage();
        exit;
    }
} else {
    include '_request.php';
    $mode = 'insert';
    $registDate = date('Y-m-d');
    $inoutsep = '지출';
    $amount = 0;
    $content = '';  // 기본값 설정
}

$title_message = ($mode === 'update') ? '금전출납부 수정 #' . $num : '금전출납부 신규 등록' ;

// Bankbook options
$bankbookOptions = [];
$jsonFile = $_SERVER['DOCUMENT_ROOT'] . "/account_juil/accoutlist.json";
$accounts = [];
$selectedAccount = null;

if (file_exists($jsonFile)) {
    $jsonContent = file_get_contents($jsonFile);
    $accounts = json_decode($jsonContent, true);
    if (is_array($accounts) && !empty($accounts)) {
        // 선택된 계좌 또는 기본 계좌(첫 번째) 설정
        $selectedAccountIndex = isset($_REQUEST['selected_account']) ? intval($_REQUEST['selected_account']) : 0;
        $selectedAccount = $accounts[$selectedAccountIndex] ?? $accounts[0];
        
        // bankbookOptions 배열에 계좌 정보 추가
        foreach ($accounts as $account) {
            $displayText = $account['company'] . ' ' . $account['number'];
            if (!empty($account['memo'])) {
                $displayText .= ' (' . $account['memo'] . ')';
            }
            $bankbookOptions[] = $displayText;
        }
    }
}

// 전자어음은 별도로 처리하므로 JSON 배열에는 추가하지 않음

// 수입/지출 계정 정보 가져오기
include 'fetch_options.php';

if($inoutsep == '수입')	
	$options = $incomeOptions;
  elseif($inoutsep == '최초전월이월')
	$options = $incomeOptions;
  else
	  $options = $expenseOptions;
  
// 선택된 항목의 세부항목 가져오기
$selectedKey = $content ?? null; // URL의 'key' 매개변수로 전달
$details = null;

if ($selectedKey) {
	// 수입에서 검색
	if (isset($jsonData['수입'][$selectedKey])) {
		$details = $jsonData['수입'][$selectedKey]['하위계정'];
	}
	// 지출에서 검색
	if (isset($jsonData['지출'][$selectedKey])) {
		$details = $jsonData['지출'][$selectedKey]['하위계정'];
	}
}  

// '개인대출'과 '주일기업' 등 키만 추출
$Suboptions = [];
if ($details) {
    foreach ($details as $detail) {
        foreach ($detail as $key => $value) {
            $Suboptions[] = $key;
        }
    }
}

// 항목의 세부항목 수정시 처리하는 구문
if (isset($_POST['action']) && $_POST['action'] === 'getSubOptions') {
    $selectedKey = $_POST['selectedKey'] ?? null;

    $subOptions = [];
    if ($selectedKey) {
        if (isset($incomeOptions[$selectedKey]) && isset($jsonData['수입'][$selectedKey]['하위계정'])) {
            $subOptions = $jsonData['수입'][$selectedKey]['하위계정'];
        } elseif (isset($expenseOptions[$selectedKey]) && isset($jsonData['지출'][$selectedKey]['하위계정'])) {
            $subOptions = $jsonData['지출'][$selectedKey]['하위계정'];
        } elseif (isset($incomeOptions[$selectedKey]) && isset($jsonData['최초전월이월'][$selectedKey]['하위계정'])) {
            $subOptions = $jsonData['최초전월이월'][$selectedKey]['하위계정'];
        }
    }

	// $Suboptions 배열을 키를 기준으로 오름차순 정렬
	ksort($Suboptions); 
	
    echo json_encode(['subOptions' => $subOptions], JSON_UNESCAPED_UNICODE);
    exit;
}

// echo '<pre>';
// print_r($Suboptions);
// echo '</pre>';
// echo '<pre>';
// print_r($contentSub);
// echo '</pre>';

//print_r($details[);
// $options = array_merge($incomeOptions, $expenseOptions);

// $options 배열을 키를 기준으로 오름차순 정렬
ksort($options); 

// $Suboptions 배열을 키를 기준으로 오름차순 정렬
ksort($Suboptions); 

require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDriveSecond.php'; // attached, image에 대한 정보 불러오기  

// echo '<pre>';   
// print_r($savefilename_arr);
// echo '</pre>';

// echo '<pre>';   
// print_r($$bankbookOptions );
// echo '</pre>';
?>


<input type="hidden" id="update_log" name="update_log" value="<?=$update_log?>">
<input type="hidden" id="first_writer" name="first_writer" value="<?=$first_writer?>">

<div class="container-fluid">
    <div class="d-flex align-items-center justify-content-center">
        <div class="card justify-content-center w-100">
            <div class="card-header text-center">
                <span class="text-center fs-5"><?=$title_message?></span>
            </div>
            <div class="card-body">
                <div class="row justify-content-center text-center">
                    <div class="d-flex align-items-center justify-content-center ">
                        <table class="table table-bordered ">
                            <tbody>
                                <tr>
                                    <td class="text-center fw-bold" style="width:13%">등록일자</td>
                                    <td class="text-center" colspan="3" style="width:37%">
                                        <input type="date" class="form-control noborder-input w110px" id="registDate" name="registDate" value="<?=$registDate?>">
                                    </td>
                                    <td class="text-center  fw-bold" style="width:13%">구분</td>
                                    <td class="text-center" colspan="3" style="width:37%">
                                        <div class="d-flex align-items-center justify-content-center">
                                            <input type="radio" class="form-check-input mx-2" id="premonthly" name="inoutsep" value="최초전월이월" <?= $inoutsep === '최초전월이월' ? 'checked' : '' ?>>
                                            <label for="premonthly" class="form-check-label ">최초전월이월</label>
                                            &nbsp;&nbsp;
                                            <input type="radio" class="form-check-input mx-2" id="income" name="inoutsep" value="수입" <?= $inoutsep === '수입' ? 'checked' : '' ?>>
                                            <label for="income" class="form-check-label ">수입</label>
                                            &nbsp;&nbsp;
                                            <input type="radio" class="form-check-input mx-2" id="expense" name="inoutsep" value="지출" <?= $inoutsep === '지출' ? 'checked' : '' ?>>
                                            <label for="expense" class="form-check-label ">지출</label>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-center fw-bold">계좌</td>
                                    <td class="text-center" colspan="7">
                                        <div class="d-flex align-items-center align-items-center">
                                            <select class="form-select w-auto" style="font-size: 0.8rem;height: 32px;" id="bankbook" name="bankbook">
                                                <?php 
                                                // _row.php에서 설정된 $bankbook 변수 사용
                                                $currentBankbook = isset($bankbook) ? $bankbook : '';
                                                
                                                // JSON 계좌 옵션들 추가
                                                foreach ($bankbookOptions as $option): 
                                                    $isSelected = ($currentBankbook === $option);
                                                ?>
                                                    <option value="<?= htmlspecialchars($option) ?>" <?= $isSelected ? 'selected' : '' ?>><?= htmlspecialchars($option) ?></option>
                                                <?php endforeach; ?>
                                                
                                                <!-- 전자어음 옵션 추가 (JSON에 없어도 항상 표시) -->
                                                <option value="전자어음" <?= $currentBankbook === '전자어음' ? 'selected' : '' ?>>전자어음</option>
                                            </select>
                                            <div id="endorsementDateContainer" class="ms-2" style="display: <?= $currentBankbook === '전자어음' ? 'inline-block' : 'none' ?>">
                                                <span class="form-label mx-5 fw-bold text-primary" style="font-size: 0.8rem; margin: 0;">배서일자</span>
                                                <input type="date" class="ms-5 form-control noborder-input" id="endorsementDate" name="endorsementDate" value="<?= $endorsementDate ?>" style="width: 110px; font-size: 0.8rem; height: 32px;">
                                            </div>
                                            <button type="button" id="selectElectronicBillBtn" class="btn btn-outline-primary btn-sm ms-2" style="display: <?= $currentBankbook === '전자어음' ? 'inline-block' : 'none' ?>">
                                                <i class="bi bi-search"></i> 전자어음 선택
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-center  fw-bold" >항목</td>
                                    <td class="text-center" colspan="3">
                                        <div class="row d-flex align-items-center justify-content-start">
                                        <select class="form-select w200px p-2" style="margin-left:15px; font-size: 0.8rem;height: 35px;" id="content" name="content">
                                            <?php foreach ($options as $key => $value): ?>
                                                <option value="<?= htmlspecialchars($key) ?>" <?= $content === $key ? 'selected' : '' ?>><?= htmlspecialchars($key) ?></option>
                                            <?php endforeach; ?>
                                        </select>
										<span class="text-start" style="margin-left:15px; font-size: 0.8rem;"   id="content_description">
											<?= $options[$content] ?? '' ?>
										</span>
                                        </div>
                                    </td>
								<td class="text-center  fw-bold" >세부항목</td>
								<td colspan="3" class="text-center">
                                    <select class="form-select w-auto" style="font-size: 0.8rem;height: 32px;" id="contentSub" name="contentSub">
										<?php foreach ($Suboptions as $value): // 키를 사용하지 않고 값만 사용 ?>
											<option value="<?= htmlspecialchars($value) ?>" <?= $contentSub === $value ? 'selected' : '' ?>>
												<?= htmlspecialchars($value) ?>
											</option>
										<?php endforeach; ?>
									</select>
								</td>

                                </tr>
                                <tr>
                                    <td class="text-center  fw-bold">상세 내역</td>
                                    <td class="text-start" colspan="7">
                                        <input type="text" class="form-control text-start  noborder-input" id="content_detail" name="content_detail" value="<?=$content_detail?>" autocomplete="off">
                                    </td>
                                </tr>
                                <tr>
                                <td class="text-center  fw-bold" >금액</td>
                                <td class="text-center w200px">
                                    <input
                                        type="text"
                                        class="form-control  text-end  fw-bold noborder-input "
                                        id="amount"
                                        name="amount"
                                        value="<?= (isset($amount) && $amount != 0) ? number_format($amount) : '' ?>"
                                        autocomplete="off"
                                        onkeyup="inputNumberFormat(this)"
                                    >
                                </td>
                                <td class="text-center text-end text-secondary w60px" >PNum</td>
                                <td class="text-center w100px">
                                    <input
                                        type="text"
                                        class="form-control  text-end  noborder-input "
                                        id="parentEBNum"
                                        name="parentEBNum"
                                        value="<?= (isset($parentEBNum))  ?$parentEBNum : '' ?>"
                                        autocomplete="off"
                                    >
                                </td>
                                    <td class="text-center  fw-bold" style="width:100px;">거래처코드</td>
                                    <td class="text-start">
                                        <input type="text" class="form-control  text-start  noborder-input w120px" id="secondordnum" name="secondordnum" value="<?= isset($secondordnum) ? $secondordnum : '' ?>"   autocomplete="off"  >
                                    </td>
                                    <td class="text-center  fw-bold" style="width:100px;">만기일자</td>
                                    <td class="text-start">
                                        <input type="date" class="form-control  text-start  noborder-input w120px" id="dueDate" name="dueDate" value="<?= isset($dueDate) ? $dueDate : '' ?>"   autocomplete="off"  >
                                    </td>
                                </tr>                                
                            </tbody>
                        </table>
                    </div>
                </div>
<?php
// 삽입 위치: form 하단, </div></div> 직전
// try {
//     $imgSt = $pdo->prepare(
//         "SELECT picname 
//            FROM picuploads 
//           WHERE tablename = ? 
//             AND parentnum = ? 
//             AND item = 'image'"
//     );
//     $imgSt->execute([$tablename, $num]);
//     $files = $imgSt->fetchAll(PDO::FETCH_COLUMN);
//     if ($files) {
//         echo '<div class="mt-3"><strong>첨부 이미지</strong></div>';
//         echo '<div id="displayImage" class="d-flex flex-wrap gap-2">';
//         echo '</div>';
//     }
// } catch (Exception $e) {
//     // 이미지 섹션 로드 실패 시 무시
// }
// // 삽입 위치: form 하단, </div></div> 직전
try {
    $imgSt = $pdo->prepare(
        "SELECT picname 
           FROM picuploads 
          WHERE tablename = ? 
            AND parentnum = ? 
            AND item = 'image'"
    );
    $imgSt->execute([$tablename, $num]);
    $files = $imgSt->fetchAll(PDO::FETCH_COLUMN);
    if ($files) {
        echo '<div class="mt-3"><strong>첨부 이미지</strong></div>';
        echo '<div class="d-flex flex-wrap gap-2">';
        foreach ($files as $fileId) {
            $thumb = getThumbnail($fileId, $service) 
                   ?: "https://drive.google.com/uc?id={$fileId}";
            $imageId = $fileId; // 고유한 이미지 ID 생성
            // $link ="https://drive.google.com/uc?id={$fileId}";            
            $link ="https://drive.google.com/file/d/{$fileId}/view?usp=drivesdk";            
            echo '<div>';
            echo "  <a href=\"#\" onclick=\"openTmpImagePopup('{$link}', '{$imageId}'); return false;\">";
            echo "    <img id=\"{$imageId}\" src=\"{$thumb}\" style=\"width:100px; height:auto;\" class=\"img-thumbnail\" />";
            echo '  </a>';
            echo '</div>';
        }
        echo '</div>';
    }
} catch (Exception $e) {
    // 이미지 섹션 로드 실패 시 무시
}
?>


                <div class="d-flex justify-content-center">
                    <button type="button" id="saveBtn" class="btn btn-dark btn-sm me-3">
                       <i class="bi bi-floppy-fill"></i> 저장
                    </button>
                    <?php if($mode != 'insert') { ?>
                    <button type="button" id="copyBtn" class="btn btn-primary btn-sm me-3">
                        <i class="bi bi-files"></i> 복사
                    </button>
                    <button type="button" id="deleteBtn" class="btn btn-danger btn-sm me-3">
                        <i class="bi bi-trash"></i>  삭제 
                    </button>
                    <?php } ?>
                    <button type="button" id="closeBtn" class="btn btn-outline-dark btn-sm me-2">
                        &times; 닫기
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 전자어음 선택 모달 -->
<div id="electronicBillModal" class="modal fade" tabindex="-1" aria-labelledby="electronicBillModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-fullscreen">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="electronicBillModalLabel">배서일자가 없는 전자어음 선택</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-hover" id="electronicBillTable">
                        <thead class="table-secondary">
                            <tr>
                                <th>번호</th>
                                <th>등록일자</th>
                                <th>항목</th>
                                <th>세부항목</th>
                                <th>상세내용</th>
                                <th>금액</th>
                                <th>만기일자</th>
                                <th>선택</th>
                            </tr>
                        </thead>
                        <tbody id="electronicBillTableBody">
                            <!-- 데이터가 여기에 로드됩니다 -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">닫기</button>
            </div>
        </div>
    </div>
</div>
