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

$mode = $_POST['mode'] ?? '';
$num = $_POST['num'] ?? '';

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

$car_table = 'juilcar';
// 차량 리스트 불러오기
$car_sql = "SELECT vehicle_number FROM " . $DB . "." . $car_table . " WHERE is_deleted IS NULL ORDER BY manufacturing_date ASC, purchase_date ASC";
$car_stmh = $pdo->query($car_sql);
$car_list = $car_stmh->fetchAll(PDO::FETCH_ASSOC);

$title_message = ($mode === 'modify') ? '차량운행일지 수정' : (($mode === 'copy') ? '차량운행일지 복사' : '차량운행일지 신규 등록');

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

        include '_row.php';
    } catch (PDOException $Exception) {
        echo "오류: ".$Exception->getMessage();
        exit;
    }
}
// 출발지↔도착지 변경 복사
else if ($mode === 'copyDestination' && $num) {
    try {
        $sql = "SELECT * FROM ". $DB . "." . $tablename . " WHERE num=?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);      
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);

        include '_row.php';
        $mode = 'copyDestination';    
        $num = null;

		// 출발지 도착지 변경해줌
		// 출발지와 도착지 값을 서로 바꾸기 위해 임시 변수 사용
		$temp = $row['departure'];
		$departure = $row['destination'];
		$destination = $temp;

		// 출근/퇴근 서로 바꾸기
		if($usage_purpose == '출근') {	
			$usage_purpose = '퇴근';
		} else if($usage_purpose == '퇴근') {
			$usage_purpose = '출근';
		}

    } catch (PDOException $Exception) {
        echo "오류: ".$Exception->getMessage();
        exit;
    }
}
else if ($mode === 'copy' && $num) {
    try {
        $sql = "SELECT * FROM ". $DB . "." . $tablename . " WHERE num=?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);      
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);

        include '_row.php';
        $mode = 'copy';    
        $num = null;
    } catch (PDOException $Exception) {
        echo "오류: ".$Exception->getMessage();
        exit;
    }
}
else {
    include '_request.php';
    $mode = 'insert';    
    $use_date = date('Y-m-d');
	

    // 🔹 신규 작성 시 현재 사용자 정보 불러오기
    $user_name = $_SESSION["name"] ?? '';
	
	// print $user_name;

    if (!empty($user_name)) {
        $member_sql = "SELECT part, position, name FROM " . $DB . ".member WHERE name = ?";
        $member_stmh = $pdo->prepare($member_sql);
        $member_stmh->bindValue(1, $user_name, PDO::PARAM_STR);
        $member_stmh->execute();
        $member_info = $member_stmh->fetch(PDO::FETCH_ASSOC);

        if ($member_info) {
            $department = $member_info['part'] ?? '';
            $position = $member_info['position'] ?? '';
            $caruser_name = $member_info['name'] ?? '';
        }
    }
	// 차량관리에 정보가 있으면 불러오기
    if (!empty($user_name)) {
        $juilcar_sql = "SELECT vehicle_number FROM " . $DB . ".juilcar WHERE responsible_person = ?";
        $juilcar_stmh = $pdo->prepare($juilcar_sql);
        $juilcar_stmh->bindValue(1, $user_name, PDO::PARAM_STR);
        $juilcar_stmh->execute();
        $juilcar_info = $juilcar_stmh->fetch(PDO::FETCH_ASSOC);

        if ($juilcar_info) {
            $car_number = $juilcar_info['vehicle_number'] ?? '';
        }
    }
}
?>

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

		<div class="container-fluid">
			<div class="d-flex align-items-center justify-content-center">
				<div class="card w-100" >
					<div class="card-header text-center align-items-center">
						<div class="d-flex align-items-center justify-content-center m-2">
							<span class="text-center fs-5 mx-3"><?=$title_message?> #<?=$num?></span>
								<button type="button"  data-num="<?=$num?>" class="btn btn-outline-dark btn-sm me-5" id="showlogBtn"   >								
									 Log 기록
								</button>
						</div>
					</div>
			<div class="card-body">
			<div class="d-flex justify-content-center">
			<table class="table table-bordered">
				<tbody>
					<tr>
						<td class="fw-bold">사용일자</td>
						<td><input type="date" id="use_date" name="use_date" class="form-control  " value="<?= $use_date ?>"></td>
						<td class="fw-bold">차량번호</td>
						<td>
							<select id="car_number" name="car_number" class="form-select"  style="font-size: 0.7rem; height: 30px;">
								<option value="">(선택)</option>
								<?php foreach ($car_list as $car): ?>
									<option value="<?= $car['vehicle_number'] ?>" <?= ($car_number === $car['vehicle_number']) ? 'selected' : '' ?>>
										<?= $car['vehicle_number'] ?>
									</option>
								<?php endforeach; ?>
							</select>
						</td>
					</tr>
					<tr>
						<td class="fw-bold">부서</td>
						<td><input type="text" id="department" name="department" class="form-control  " value="<?= $department ?>"></td>
						<td class="fw-bold">직책</td>
						<td><input type="text" id="position" name="position" class="form-control  " value="<?= $position ?>"></td>
					</tr>
					<tr>
						<td class="fw-bold">사용자</td>
						<td><input type="text" id="caruser_name" name="caruser_name" class="form-control  " value="<?= $caruser_name ?>"></td>
						<td class="text-primary fw-bold" >사용목적</td>
						<td>
							<select id="usage_purpose" name="usage_purpose" class="form-select text-primary fw-bold" style="font-size: 0.7rem; height: 30px;">
								<option value="">(선택)</option>
								<?php 
								$usage_options = ['출근', '퇴근', '현장', '비업무용'];
								foreach ($usage_options as $option): ?>
									<option value="<?= $option ?>" <?= ($usage_purpose === $option) ? 'selected' : '' ?>>
										<?= $option ?>
									</option>
								<?php endforeach; ?>
							</select>
						</td>

					</tr>
					<tr>
						<td class="fw-bold">출발지</td>		
						<td><input type="text" id="departure" name="departure" class="form-control   text-start" value="<?= $departure ?>"></td>
						<td class="fw-bold"> 도착지 </td>
						<td><input type="text" id="destination" name="destination" class="form-control   text-start" value="<?= $destination ?>"></td>
					</tr>
					<tr>
						<td class="fw-bold">운행내역</td>
						<td colspan="3"><input type="text" id="operation_details" name="operation_details" class="form-control   text-start" value="<?= $operation_details ?>"></td>
					</tr>
					<tr>
						<td class="fw-bold">주행거리 (km)</td>
						<td><input type="number" step="1" min="0" id="driving_distance" name="driving_distance" class="form-control   text-end" value="<?= $driving_distance ?>"></td>
						<td class="fw-bold">월간 누적거리(km)</td>
						<td><input type="text" id="arrival_cumulative_distance" name="arrival_cumulative_distance" readonly class="form-control   text-end text-danger fw-bold" value="<?= is_numeric($arrival_cumulative_distance) ? number_format($arrival_cumulative_distance) : $arrival_cumulative_distance ?>"></td>
					</tr>
					<tr>
						<td class="fw-bold">비고</td>
						<td colspan="3"><input type="text" id="note" name="note" class="form-control   text-start" value="<?= $note ?>"></td>
					</tr>
				</tbody>
			</table>
		</div>
                <div class="d-flex justify-content-center">
                    <button type="button" id="saveBtn" class="btn btn-dark btn-sm mx-1">
                        <i class="bi bi-floppy-fill"></i> 저장
                    </button>
                    <?php if($mode != 'insert' && $mode != 'copy' && $mode != 'copyDestination') { ?>
                    <button type="button" id="copyDestinationBtn" class="btn btn-primary btn-sm mx-1">
                        <i class="bi bi-copy"> </i> 출발↔도착 변경 복사
                    </button>					
                    <button type="button" id="copyBtn" class="btn btn-primary btn-sm mx-1" >
                        <i class="bi bi-copy"> </i> 복사 
                    </button>					
					<button type="button" id="deleteBtn" class="btn btn-danger btn-sm mx-1">
                        <i class="bi bi-trash"></i>  삭제 
                    </button>
                    <?php } ?>
                    <button type="button" id="closeBtn" class="btn btn-outline-dark btn-sm mx-1">
                        &times; 닫기
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
