<?php
// تنظیمات رمز عبور مشترک
$shared_password = "1234"; // رمزی که کاربران باید وارد کنند

// بررسی لاگین
session_start();
$is_logged_in = false;
$username = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    $pass = $_POST['password'] ?? '';
    $user = trim($_POST['username'] ?? '');
    if ($pass === $shared_password && !empty($user)) {
        $_SESSION['chat_user'] = $user;
        $_SESSION['chat_auth'] = true;
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

if (isset($_SESSION['chat_auth']) && $_SESSION['chat_auth'] === true) {
    $is_logged_in = true;
    $username = $_SESSION['chat_user'] ?? 'کاربر';
}

// اگر کاربر لاگین نیست، فرم ورود را نمایش بده
if (!$is_logged_in) {
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ورود به چت</title>
    <style>
        @font-face {
            font-family: 'Yekan';
            src: url('fonts/yekan.ttf') format('ttf'); /* فونت یکان باید در کنار فایل باشد */
            font-weight: normal;
            font-style: normal;
        }
        body {
            font-family: 'Yekan', Tahoma, sans-serif;
            background-color: #121212;
            color: #ffffff;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        .login-box {
            background: #1e1e1e;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.5);
            width: 300px;
            text-align: center;
        }
        input {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border-radius: 5px;
            border: 1px solid #333;
            background: #2c2c2c;
            color: white;
            box-sizing: border-box;
            font-family: 'Yekan', Tahoma, sans-serif;
        }
        button {
            width: 100%;
            padding: 10px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-family: 'Yekan', Tahoma, sans-serif;
            font-size: 1rem;
        }
        button:hover { background: #0056b3; }
    </style>
</head>
<body>
    <div class="login-box">
        <h2>ورود به چت</h2>
        <form method="POST">
            <input type="text" name="username" placeholder="نام کاربری (مثلاً علی)" required>
            <input type="password" name="password" placeholder="رمز ورود" required>
            <button type="submit" name="login">ورود</button>
        </form>
    </div>
</body>
</html>
<?php
    exit;
}
?>

<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>چت روم شابوف</title>
    <style>
        /* تنظیمات کلی و فونت */
        @font-face {
            font-family: 'Yekan';
            src: url('Yekan.woff2') format('woff2'); /* مسیر فونت */
            font-weight: normal;
            font-style: normal;
        }
        * { box-sizing: border-box; outline: none; -webkit-tap-highlight-color: transparent; }
        
        body {
            margin: 0;
            padding: 0;
            background-color: #000000; /* مشکی */
            font-family: 'Yekan', Tahoma, sans-serif;
            color: #ffffff;
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        /* هدر */
        header {
            background-color: #1a1a1a;
            padding: 10px 15px;
            border-bottom: 1px solid #333;
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 60px;
            flex-shrink: 0;
        }
        .header-title { font-weight: bold; font-size: 1.1rem; }
        .logout-btn { background: #d32f2f; color: white; border: none; padding: 5px 10px; border-radius: 4px; cursor: pointer; font-family: inherit; }

        /* ناحیه پیام‌ها */
        #chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
            display: flex;
            flex-direction: column;
            gap: 10px;
            scroll-behavior: smooth;
        }

        /* استایل پیام‌ها */
        .message {
            max-width: 75%;
            padding: 10px 14px;
            border-radius: 12px;
            position: relative;
            font-size: 0.95rem;
            line-height: 1.5;
            word-wrap: break-word;
            animation: fadeIn 0.5s ease-out;
            box-shadow: 0 1px 2px rgba(0,0,0,0.3);
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* پیام خودکار (سمت راست) */
        .message.mine {
            align-self: flex-end;
            background-color: #2d2d2d; /* طوسی تیره */
            border-bottom-right-radius: 2px;
            color: #fff;
        }

        /* پیام دیگران (سمت چپ) */
        .message.others {
            align-self: flex-start;
            background-color: #3e3e3e; /* خاکستری روشن‌تر */
            border-bottom-left-radius: 2px;
            color: #eee;
        }

        .msg-info {
            display: flex;
            justify-content: space-between;
            font-size: 0.75rem;
            margin-bottom: 4px;
            opacity: 0.7;
        }
        .msg-sender { font-weight: bold; }
        .msg-time { font-size: 0.7rem; direction: ltr; }

        .msg-content img {
            max-width: 100%;
            border-radius: 8px;
            margin-top: 5px;
            display: block;
        }
        .msg-sticker {
            font-size: 3rem;
            line-height: 1;
        }

        /* فوتر و ورودی */
        footer {
            background-color: #1a1a1a;
            padding: 10px;
            border-top: 1px solid #333;
            display: flex;
            align-items: center;
            gap: 8px;
            flex-shrink: 0;
        }

        .tool-btn {
            background: none;
            border: none;
            color: #aaa;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            transition: 0.2s;
        }
        .tool-btn:hover { background-color: #333; color: #fff; }
        
        #message-input {
            flex: 1;
            background-color: #2c2c2c;
            border: 1px solid #444;
            color: white;
            padding: 10px;
            border-radius: 20px;
            font-family: inherit;
        }
        #send-btn {
            background-color: #007bff;
            color: white;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        #send-btn:hover { background-color: #0056b3; }

        /* استیکر پنل */
        #sticker-panel {
            display: none;
            background: #222;
            padding: 10px;
            grid-template-columns: repeat(5, 1fr);
            gap: 10px;
            border-top: 1px solid #333;
        }
        #sticker-panel.active { display: grid; }
        .sticker-item {
            font-size: 2rem;
            text-align: center;
            cursor: pointer;
            padding: 5px;
            border-radius: 5px;
        }
        .sticker-item:hover { background: #333; }

        /* اسکرول بار زیبا */
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: #000; }
        ::-webkit-scrollbar-thumb { background: #444; border-radius: 3px; }

        /* نوتیفیکیشن */
        .toast {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 10px 20px;
            border-radius: 20px;
            z-index: 1000;
            display: none;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>

<header>
    <div class="header-title">چت روم</div>
    <form method="POST" style="margin:0;">
        <button type="submit" name="logout" class="logout-btn">خروج</button>
    </form>
</header>

<div id="chat-container">
    <!-- پیام‌ها اینجا لود می‌شوند -->
</div>

<div id="sticker-panel">
    <div class="sticker-item" onclick="sendSticker('😀')">😀</div>
    <div class="sticker-item" onclick="sendSticker('😂')">😂</div>
    <div class="sticker-item" onclick="sendSticker('😍')">😍</div>
    <div class="sticker-item" onclick="sendSticker('🤔')">🤔</div>
    <div class="sticker-item" onclick="sendSticker('😎')">😎</div>
    <div class="sticker-item" onclick="sendSticker('😭')">😭</div>
    <div class="sticker-item" onclick="sendSticker('👍')">👍</div>
    <div class="sticker-item" onclick="sendSticker('👎')">👎</div>
    <div class="sticker-item" onclick="sendSticker('🎉')">🎉</div>
    <div class="sticker-item" onclick="sendSticker('❤️')">❤️</div>
</div>

<footer>
    <input type="file" id="image-input" accept="image/*" style="display: none;">
    <button class="tool-btn" onclick="document.getElementById('image-input').click()" title="ارسال عکس">
        <!-- آیکون تصویر SVG -->
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
    </button>
    
    <button class="tool-btn" onclick="toggleStickers()" title="استیکر">
        <!-- آیکون استیکر SVG -->
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><path d="M8 14s1.5 2 4 2 4-2 4-2"></path><line x1="9" y1="9" x2="9.01" y2="9"></line><line x1="15" y1="9" x2="15.01" y2="9"></line></svg>
    </button>

    <input type="text" id="message-input" placeholder="پیام خود را بنویسید..." autocomplete="off">
    
    <button id="send-btn" onclick="sendMessage()">
        <!-- آیکون ارسال SVG -->
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
    </button>
</footer>

<div id="toast" class="toast"></div>

<!-- فایل صدا -->
<audio id="notif-sound" src="notification.mp3"></audio>

<script>
    const currentUser = "<?php echo $username; ?>";
    const chatContainer = document.getElementById('chat-container');
    const messageInput = document.getElementById('message-input');
    const imageInput = document.getElementById('image-input');
    let lastMsgId = 0;

    // درخواست مجوز نوتیفیکیشن
    if ("Notification" in window && Notification.permission !== "granted") {
        Notification.requestPermission();
    }

    // لود اولیه پیام‌ها
    function loadMessages() {
        fetch('api.php?action=get&last_id=' + lastMsgId)
            .then(response => response.json())
            .then(data => {
                if (data.messages && data.messages.length > 0) {
                    data.messages.forEach(msg => {
                        appendMessage(msg);
                        lastMsgId = msg.id;
                    });
                    scrollToBottom();
                }
            });
    }

    // اضافه کردن پیام به صفحه
    function appendMessage(msg) {
        const isMine = msg.username === currentUser;
        const div = document.createElement('div');
        div.className = `message ${isMine ? 'mine' : 'others'}`;
        
        let contentHtml = '';
        if (msg.type === 'text') {
            contentHtml = msg.content;
        } else if (msg.type === 'image') {
            contentHtml = `<img src="${msg.content}" alt="image">`;
        } else if (msg.type === 'sticker') {
            contentHtml = `<div class="msg-sticker">${msg.content}</div>`;
        }

        // فرمت زمان 24 ساعته
        const time = msg.time.split(' ')[1]; // فرض بر فرمت YYYY-MM-DD HH:MM:SS

        div.innerHTML = `
            <div class="msg-info">
                <span class="msg-sender">${isMine ? 'شما' : msg.username}</span>
                <span class="msg-time">${time}</span>
            </div>
            <div class="msg-content">${contentHtml}</div>
        `;
        
        chatContainer.appendChild(div);

        // پخش صدا و نوتیفیکیشن برای پیام دیگران
        if (!isMine) {
            playSound();
            showNotification(msg.username, msg.type === 'text' ? msg.content : 'پیام جدید');
        }
    }

    function scrollToBottom() {
        chatContainer.scrollTop = chatContainer.scrollHeight;
    }

    function sendMessage() {
        const text = messageInput.value.trim();
        if (!text) return;
        
        fetch('api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=send&type=text&content=${encodeURIComponent(text)}`
        }).then(() => {
            messageInput.value = '';
            loadMessages(); // بروزرسانی سریع
        });
    }

    function sendSticker(emoji) {
        fetch('api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=send&type=sticker&content=${encodeURIComponent(emoji)}`
        }).then(() => {
            toggleStickers();
            loadMessages();
        });
    }

    // آپلود عکس
    imageInput.addEventListener('change', function() {
        const file = this.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('action', 'send');
            formData.append('type', 'image');
            formData.append('image', file);

            fetch('api.php', {
                method: 'POST',
                body: formData
            }).then(() => {
                loadMessages();
            });
        }
    });

    function toggleStickers() {
        document.getElementById('sticker-panel').classList.toggle('active');
    }

    function playSound() {
        const audio = document.getElementById('notif-sound');
        audio.currentTime = 0;
        audio.play().catch(e => console.log('Audio play failed', e));
    }

    function showNotification(title, body) {
        if (document.hidden && Notification.permission === "granted") {
            new Notification(title, { body: body, icon: '' });
        } else {
            // نمایش توست داخلی اگر صفحه باز است
            const toast = document.getElementById('toast');
            toast.textContent = `پیام جدید از ${title}`;
            toast.style.display = 'block';
            setTimeout(() => { toast.style.display = 'none'; }, 3000);
        }
    }

    // ارسال با اینتر
    messageInput.addEventListener('keypress', function (e) {
        if (e.key === 'Enter') sendMessage();
    });

    // پولینگ (بررسی پیام جدید هر 1 ثانیه)
    setInterval(loadMessages, 1000);

    // لود اولیه
    loadMessages();

    // هندل کردن خروج
    if (document.querySelector('button[name="logout"]')) {
        document.querySelector('button[name="logout"]').addEventListener('click', function() {
            // فرم سابمیت می‌شود و سشن در PHP نابود می‌شود
        });
    }
</script>

<?php
// هندل کردن خروج در سمت سرور
if (isset($_POST['logout'])) {
    session_destroy();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}
?>
</body>
</html>