<?php
session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Check if messages table exists, if not create it
    try {
        $check = $db->query("SELECT 1 FROM messages LIMIT 1");
    } catch (Exception $e) {
        // Table doesn't exist, create it
        $create_table = "CREATE TABLE IF NOT EXISTS messages (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            email VARCHAR(255),
            phone VARCHAR(20),
            message TEXT NOT NULL,
            is_read BOOLEAN DEFAULT FALSE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
        
        $db->exec($create_table);
        
        // Insert sample data
        $insert = "INSERT INTO messages (name, email, phone, message, is_read) VALUES
            ('أحمد محمد', 'ahmed@example.com', '01012345678', 'أريد الاستفسار عن منتجات العناية بالبشرة المتوفرة لديكم', 0),
            ('فاطمة علي', 'fatma@example.com', '01098765432', 'هل يمكنني إلغاء طلبي رقم #123؟', 1),
            ('محمود حسن', 'mahmoud@example.com', '01123456789', 'متى سيتم توصيل طلبي؟ لقد مر 3 أيام', 0)";
        $db->exec($insert);
    }
    
    // Get messages/support tickets
    $query = "SELECT * FROM messages ORDER BY created_at DESC LIMIT 50";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "خطأ: " . $e->getMessage();
    $messages = [];
}

$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['mark_read'])) {
    try {
        $msg_id = $_POST['message_id'];
        $query = "UPDATE messages SET is_read = 1 WHERE id = ?";
        $stmt = $db->prepare($query);
        $stmt->execute([$msg_id]);
        $message = 'تم تحديث حالة الرسالة!';
        header("Location: index.php");
        exit;
    } catch (Exception $e) {
        $message = "خطأ: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>الدعم الفني - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
            <div class="flex items-center justify-between px-6 py-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-900">الدعم الفني</h1>
                </div>
            </div>
        </header>

        <div class="p-6">
            <?php if (isset($error)): ?>
                <div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6">
                    <p class="text-sm text-red-700"><?php echo $error; ?></p>
                </div>
            <?php endif; ?>

            <?php if ($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <p class="text-sm text-green-700"><?php echo $message; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics Cards -->
            <?php
                $total_messages = count($messages);
                $unread_messages = count(array_filter($messages, fn($m) => empty($m['is_read'])));
                $read_messages = $total_messages - $unread_messages;
            ?>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">إجمالي الرسائل</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo $total_messages; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-envelope text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">غير مقروءة</p>
                            <p class="text-2xl font-bold text-orange-600"><?php echo $unread_messages; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-envelope-open text-orange-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">مقروءة</p>
                            <p class="text-2xl font-bold text-green-600"><?php echo $read_messages; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Messages List -->
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="px-6 py-5 border-b border-gray-200">
                    <h3 class="text-xl font-semibold text-gray-900">رسائل الدعم</h3>
                </div>
                <div class="divide-y divide-gray-200">
                    <?php if (!empty($messages)): ?>
                        <?php foreach ($messages as $msg): ?>
                            <div class="p-6 hover:bg-gray-50 <?php echo empty($msg['is_read']) ? 'bg-blue-50' : ''; ?>">
                                <div class="flex items-start justify-between">
                                    <div class="flex-1">
                                        <div class="flex items-center gap-3 mb-2">
                                            <h4 class="font-semibold text-gray-900"><?php echo htmlspecialchars($msg['name'] ?? 'عميل'); ?></h4>
                                            <?php if (empty($msg['is_read'])): ?>
                                                <span class="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-orange-100 text-orange-800">
                                                    <i class="fas fa-circle text-orange-600 text-xs ml-1"></i>جديد
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="flex items-center gap-4 text-sm text-gray-600 mb-3">
                                            <?php if (!empty($msg['email'])): ?>
                                                <span><i class="fas fa-envelope ml-1"></i><?php echo htmlspecialchars($msg['email']); ?></span>
                                            <?php endif; ?>
                                            <?php if (!empty($msg['phone'])): ?>
                                                <span><i class="fas fa-phone ml-1"></i><?php echo htmlspecialchars($msg['phone']); ?></span>
                                            <?php endif; ?>
                                            <span><i class="fas fa-clock ml-1"></i><?php echo date('Y-m-d H:i', strtotime($msg['created_at'])); ?></span>
                                        </div>
                                        <p class="text-gray-700"><?php echo htmlspecialchars($msg['message'] ?? $msg['content'] ?? ''); ?></p>
                                    </div>
                                    <?php if (empty($msg['is_read'])): ?>
                                        <form method="POST" class="mr-4">
                                            <input type="hidden" name="message_id" value="<?php echo $msg['id']; ?>">
                                            <button type="submit" name="mark_read" class="text-blue-600 hover:text-blue-700">
                                                <i class="fas fa-check-circle text-xl"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="p-12 text-center">
                            <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                                <i class="fas fa-inbox text-4xl text-gray-400"></i>
                            </div>
                            <h3 class="text-xl font-semibold text-gray-700 mb-2">لا توجد رسائل</h3>
                            <p class="text-gray-500">لم يتم استلام أي رسائل دعم حتى الآن</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
