<?php
// admin.php
require_once 'config.php';

// تنظیمات ادمین
define('ADMIN_USERNAME', 'admin');
define('ADMIN_PASSWORD', 'admin123');

// بررسی درخواست لاگین
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'login') {
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        
        if ($username === ADMIN_USERNAME && $password === ADMIN_PASSWORD) {
            $_SESSION['admin_logged_in'] = true;
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $error = 'نام کاربری یا رمز عبور اشتباه است';
        }
    } elseif (isAdminLoggedIn()) {
        // ارسال پاسخ به کاربر
        if ($_POST['action'] === 'send_reply') {
            $userId = $_POST['user_id'] ?? '';
            $message = $_POST['message'] ?? '';
            
            if (!empty($userId) && !empty($message)) {
                saveMessage($userId, $message, true);
                $success = 'پاسخ با موفقیت ارسال شد';
            }
        }
    }
}

// خروج از پنل ادمین
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin.php');
    exit;
}

// اگر ادمین لاگین نکرده، فرم لاگین نشان داده شود
if (!isAdminLoggedIn()) {
    ?>
    <!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>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <style>
            * {
                box-sizing: border-box;
                margin: 0;
                padding: 0;
                font-family: 'Vazirmatn', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            }
            
            body {
                background: linear-gradient(135deg, #1a1a2e, #16213e);
                color: #fff;
                min-height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 20px;
            }
            
            .login-container {
                width: 100%;
                max-width: 400px;
                background: rgba(255, 255, 255, 0.1);
                backdrop-filter: blur(10px);
                padding: 30px;
                border-radius: 15px;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            }
            
            .login-title {
                text-align: center;
                margin-bottom: 25px;
                font-size: 28px;
                color: #6e8efb;
            }
            
            .form-group {
                margin-bottom: 20px;
            }
            
            .form-group label {
                display: block;
                margin-bottom: 8px;
                font-weight: 600;
            }
            
            .form-control {
                width: 100%;
                padding: 12px 15px;
                border: 1px solid rgba(255, 255, 255, 0.2);
                border-radius: 10px;
                font-size: 16px;
                background: rgba(255, 255, 255, 0.1);
                color: #fff;
                transition: border-color 0.3s;
            }
            
            .form-control:focus {
                border-color: #6e8efb;
                outline: none;
                box-shadow: 0 0 0 3px rgba(110, 142, 251, 0.2);
            }
            
            .btn {
                padding: 12px 20px;
                border: none;
                border-radius: 10px;
                cursor: pointer;
                font-weight: 600;
                transition: all 0.3s;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                text-decoration: none;
                width: 100%;
            }
            
            .btn-primary {
                background: linear-gradient(90deg, #6e8efb, #a777e3);
                color: white;
            }
            
            .btn-primary:hover {
                background: linear-gradient(90deg, #5a7de0, #9666d8);
                transform: translateY(-2px);
            }
            
            .alert {
                padding: 12px 15px;
                border-radius: 10px;
                margin-bottom: 20px;
                font-weight: 600;
            }
            
            .alert-error {
                background-color: rgba(255, 0, 0, 0.2);
                color: #ff6b6b;
                border: 1px solid rgba(255, 0, 0, 0.3);
            }
        </style>
    </head>
    <body>
        <div class="login-container">
            <h1 class="login-title">ورود به پنل مدیریت</h1>
            
            <?php if (isset($error)): ?>
                <div class="alert alert-error"><?= $error ?></div>
            <?php endif; ?>
            
            <form method="POST">
                <input type="hidden" name="action" value="login">
                <div class="form-group">
                    <label for="username">نام کاربری:</label>
                    <input type="text" id="username" name="username" class="form-control" required>
                </div>
                
                <div class="form-group">
                    <label for="password">رمز عبور:</label>
                    <input type="password" id="password" name="password" class="form-control" required>
                </div>
                
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-sign-in-alt"></i>
                    ورود به پنل
                </button>
            </form>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// دریافت داده‌ها
$users = getUsers();
$selectedUserId = $_GET['user_id'] ?? ($users[0]['id'] ?? '');
$userMessages = $selectedUserId ? getUserMessages($selectedUserId) : [];
$selectedUser = $selectedUserId ? getUserById($selectedUserId) : null;
?>
<!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>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #6e8efb;
            --secondary: #a777e3;
            --dark: #1a1a2e;
            --light: #f8f9fa;
            --success: #28a745;
            --danger: #dc3545;
            --warning: #ffc107;
            --info: #17a2b8;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Vazirmatn', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        body {
            background-color: #f5f7fb;
            font-family: 'Vazirmatn', sans-serif;
        }
        
        .admin-container {
            display: flex;
            min-height: 100vh;
        }
        
        .sidebar {
            width: 300px;
            background: var(--dark);
            color: white;
            padding: 20px;
            overflow-y: auto;
        }
        
        .main-content {
            flex: 1;
            padding: 20px;
            background: #f0f2f5;
        }
        
        .header {
            background: white;
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .user-list {
            background: white;
            border-radius: 10px;
            padding: 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        
        .user-item {
            padding: 12px 15px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .user-item:hover {
            background-color: #f8f9fa;
        }
        
        .user-item.active {
            background-color: #e9ecef;
            border-right: 3px solid var(--primary);
        }
        
        .user-info {
            display: flex;
            flex-direction: column;
        }
        
        .user-name {
            font-weight: 600;
        }
        
        .user-meta {
            font-size: 12px;
            color: #6c757d;
        }
        
        .unread-count {
            background: var(--primary);
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
        }
        
        .chat-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            height: calc(100vh - 100px);
        }
        
        .chat-header {
            padding: 15px 20px;
            background: white;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }
        
        .message {
            margin-bottom: 15px;
            padding: 10px 15px;
            border-radius: 10px;
            max-width: 80%;
            animation: fadeIn 0.3s ease;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .user-message {
            background: white;
            color: #333;
            margin-right: auto;
            border: 1px solid #ddd;
        }
        
        .admin-message {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
            margin-left: auto;
        }
        
        .message-info {
            font-size: 12px;
            opacity: 0.7;
            margin-bottom: 5px;
        }
        
        .chat-input {
            padding: 15px;
            background: white;
            border-top: 1px solid #eee;
            display: flex;
        }
        
        .chat-input input {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 20px;
            outline: none;
        }
        
        .chat-input button {
            margin-right: 10px;
            padding: 10px 20px;
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
            border: none;
            border-radius: 20px;
            cursor: pointer;
        }
        
        .btn-logout {
            background: var(--danger);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
        }
        
        .alert {
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        
        .alert-success {
            background-color: rgba(40, 167, 69, 0.2);
            color: #28a745;
            border: 1px solid rgba(40, 167, 69, 0.3);
        }
        
        .alert-error {
            background-color: rgba(220, 53, 69, 0.2);
            color: #dc3545;
            border: 1px solid rgba(220, 53, 69, 0.3);
        }
        
        @media (max-width: 992px) {
            .admin-container {
                flex-direction: column;
            }
            
            .sidebar {
                width: 100%;
                height: 300px;
            }
        }
    </style>
</head>
<body>
    <div class="admin-container">
        <div class="sidebar">
            <h2 style="margin-bottom: 20px;">کاربران</h2>
            <div class="user-list">
                <?php if (empty($users)): ?>
                    <p style="text-align: center; padding: 20px; color: #6c757d;">هیچ کاربری وجود ندارد</p>
                <?php else: ?>
                    <?php foreach ($users as $user): 
                        $messages = getUserMessages($user['id']);
                        $unread = 0;
                        foreach ($messages as $msg) {
                            if (!$msg['is_admin'] && !isset($msg['seen'])) {
                                $unread++;
                            }
                        }
                    ?>
                        <div class="user-item <?= $user['id'] === $selectedUserId ? 'active' : '' ?>" 
                             onclick="window.location.href='admin.php?user_id=<?= $user['id'] ?>'">
                            <div class="user-info">
                                <div class="user-name"><?= htmlspecialchars($user['name']) ?></div>
                                <div class="user-meta">
                                    <?= date('Y/m/d H:i', $user['last_seen']) ?>
                                </div>
                            </div>
                            <?php if ($unread > 0): ?>
                                <div class="unread-count"><?= $unread ?></div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
        
        <div class="main-content">
            <div class="header">
                <h2>پنل مدیریت پشتیبانی</h2>
                <a href="admin.php?logout=1" class="btn-logout">
                    <i class="fas fa-sign-out-alt"></i> خروج
                </a>
            </div>
            
            <?php if (isset($success)): ?>
                <div class="alert alert-success"><?= $success ?></div>
            <?php endif; ?>
            
            <?php if (isset($error)): ?>
                <div class="alert alert-error"><?= $error ?></div>
            <?php endif; ?>
            
            <?php if ($selectedUser): ?>
                <div class="chat-container">
                    <div class="chat-header">
                        <div class="user-info">
                            <div class="avatar" style="background-color: #6e8efb; color: white; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; border-radius: 50%;">
                                <?= mb_substr($selectedUser['name'], 0, 1, 'UTF-8') ?>
                            </div>
                            <div>
                                <div class="user-name"><?= htmlspecialchars($selectedUser['name']) ?></div>
                                <div class="status">
                                    <div class="status-indicator"></div>
                                    <span>آخرین بازدید: <?= date('H:i', $selectedUser['last_seen']) ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="chat-messages" id="chatMessages">
                        <?php foreach ($userMessages as $message): ?>
                            <div class="message <?= $message['is_admin'] ? 'admin-message' : 'user-message' ?>">
                                <div class="message-info">
                                    <?= $message['is_admin'] ? 'شما' : htmlspecialchars($selectedUser['name']) ?>
                                    • <?= date('H:i', $message['timestamp']) ?>
                                </div>
                                <?= nl2br(htmlspecialchars($message['message'])) ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <form method="POST" class="chat-input">
                        <input type="hidden" name="action" value="send_reply">
                        <input type="hidden" name="user_id" value="<?= $selectedUserId ?>">
                        <input type="text" name="message" placeholder="پاسخ خود را بنویسید..." required>
                        <button type="submit">
                            <i class="fas fa-paper-plane"></i> ارسال
                        </button>
                    </form>
                </div>
            <?php else: ?>
                <div style="text-align: center; padding: 40px; background: white; border-radius: 10px;">
                    <i class="fas fa-comments fa-3x" style="color: #6c757d; margin-bottom: 15px;"></i>
                    <p>لطفاً یک کاربر را برای مشاهده گفتگو انتخاب کنید</p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // اسکرول به پایین چت
        window.onload = function() {
            const chatMessages = document.getElementById('chatMessages');
            if (chatMessages) {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        };
    </script>
</body>
</html>