<?php
require_once '/var/www/html/alarm/alarm_functions.php';

$alarms = getAlarms();
$soundList = getSoundList();
?>

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>알람</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #7FFFD4;
            color: #333;
            margin: 0;
            padding: 0;
        }

        .container {
            width: 80%;
            max-width: 800px;
            margin: 200px auto;
            background-color: #fff;
            padding: 40px;
            border-radius: 30px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        h1, h2 {
            text-align: center;
            color: #20B2AA;
        }

        label {
            font-size: 16px;
            margin: 10px 0;
            display: block;
        }

        input[type="text"], input[type="time"], select {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            border: 1px solid #ddd;
            box-sizing: border-box;
        }

        button {
            background-color: #FF6347;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 10px;
            font-size: 16px;
            cursor: pointer;
            margin-top: 20px;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #FF4500;
        }

        .alarm-list {
            list-style-type: none;
            padding: 0;
        }

        .alarm-list li {
            padding: 10px;
            background-color: #fafafa;
            margin: 10px 0;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .alarm-list a {
            color: #FF6347;
            text-decoration: none;
        }

        .alarm-list a:hover {
            text-decoration: underline;
        }

        .button-container {
            display: flex;
            justify-content: center;
            gap: 10px;
        }

    </style>
    <script>
let currentAudio = null;  // 현재 재생 중인 Audio 객체를 추적

function restrictDateInput(input) {
    let value = input.value.replace(/[^0-9]/g, '');
    if (value.length > 4) {
        value = value.substring(0, 4);
    }
    if (value.length >= 3) {
        value = value.substring(0, 2) + ":" + value.substring(2);
    }
    input.value = value;

    if (value.length === 5) {
        let [month, day] = value.split(":").map(num => parseInt(num, 10));
        if (month > 12) month = 12;
        if (month < 1) month = 1;
        const maxDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        let maxDay = maxDays[month - 1];
        if (day > maxDay) day = maxDay;
        if (day < 1) day = 1;
        input.value = `${String(month).padStart(2, '0')}:${String(day).padStart(2, '0')}`;
    }
}

// 알람 작동 로직
const alarms = <?php echo json_encode($alarms); ?>;
const checkAlarms = () => {
    const now = new Date();
    alarms.forEach((alarm, index) => {
        const [monthDay, time] = alarm.time.split(' ');
        const [month, day] = monthDay.split(':').map(Number);
        const [hour, minute] = time.split(':').map(Number);

        // 알람 시간 도달 여부 확인
        const alarmDate = new Date(now.getFullYear(), month - 1, day, hour, minute);
        if (now >= alarmDate && now - alarmDate < 60000) { // 1분 이내만 작동
            playAlarm(alarm.sound);
            alarms.splice(index, 1); // 작동한 알람 제거
        }
    });
};

// 알람 사운드 재생
const playAlarm = (sound) => {
    if (currentAudio === null) {  // 이미 오디오가 재생 중이지 않은 경우에만
        currentAudio = new Audio(`/alarm/sounds/${sound}`);
        currentAudio.play();  // 사운드 먼저 재생

        // 화면에 알람 메시지를 띄운다.
        showNotification(`알람 시간입니다! 사운드: ${sound}`);
    }
};
// 화면에 알림 메시지 띄우기
const showNotification = (message) => {
    const notification = document.createElement('div');
    notification.style.position = 'fixed';
    notification.style.top = '20px';
    notification.style.left = '50%';
    notification.style.transform = 'translateX(-50%)';
    notification.style.padding = '10px 20px';
    notification.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    notification.style.color = 'white';
    notification.style.borderRadius = '5px';
    notification.style.fontSize = '16px';
    notification.style.zIndex = '9999';
    notification.innerText = message;

    document.body.appendChild(notification);

    // 6초 후 알림 제거
    setTimeout(() => {
        notification.remove();
    }, 6000);
};


        // 현재 재생 중인 알람을 멈추는 함수
        const stopCurrentAudio = () => {
            if (currentAudio !== null) {
                currentAudio.pause();  // 현재 재생 중인 오디오를 멈추고
                currentAudio.currentTime = 0;  // 다시 처음부터 재생될 수 있도록 초기화
                currentAudio = null;  // 현재 오디오 객체를 초기화
                alert("노래를 멈춥니다.");
            } else {
                alert("노래를 멈춥니다.");
            }
        };

        // 주기적으로 알람 확인
        setInterval(checkAlarms, 5000);
    </script>


    <script>
        // 우클릭 방지
        document.addEventListener('contextmenu', function(event) {
            event.preventDefault();
        });
    </script>
</head>
<body>
    <div class="container">
        <h1>알람 설정 페이지</h1>

        <form method="post" action="alarm_functions.php">
            <label for="date_time">날짜 (월:일)</label>
            <input type="text" id="date_time" name="date_time" maxlength="5" placeholder="MM-DD" oninput="restrictDateInput(this);" required>

            <label for="time">시간 (오전/오후 시:분)</label>
            <input type="time" id="time" name="time" required>

            <label for="sound">사운드:</label>
            <select id="sound" name="sound" required>
                <?php if (!empty($soundList)): ?>
                    <?php foreach ($soundList as $sound): ?>
                        <option value="<?php echo htmlspecialchars($sound); ?>"><?php echo htmlspecialchars($sound); ?></option>
                    <?php endforeach; ?>
                <?php else: ?>
                    <option disabled>사운드 파일 없음</option>
                <?php endif; ?>
            </select>

            <button type="submit" name="add_alarm">알람 추가</button>
            <button type="button" onclick="stopCurrentAudio()">현재 알람 정지</button>
        </form>

        <h2>설정된 알람</h2>
        <ul class="alarm-list">
            <?php if (empty($alarms)): ?>
                <li>설정된 알람이 없습니다.</li>
            <?php else: ?>
                <?php foreach ($alarms as $index => $alarm): ?>
                    <li>
                        <?php echo htmlspecialchars($alarm['time']); ?> - [사운드] <?php echo htmlspecialchars($alarm['sound']); ?>
                        <a href="alarm_functions.php?delete=<?php echo $index; ?>">삭제</a>
                    </li>
                <?php endforeach; ?>
            <?php endif; ?>
        </ul>
    </div>
</body>
</html>
