<?php
/**
 * support.php - Admin support dashboard
 */

require_once 'config.php';
checkAdminAuth();

// Handle reply
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply'])) {
    $ticket_id = (int)$_POST['ticket_id'];
    $message = trim($_POST['message']);
    
    if (!empty($message)) {
        $stmt = $conn->prepare("INSERT INTO support_messages (ticket_id, sender, message) VALUES (?, 'admin', ?)");
        $stmt->bind_param("is", $ticket_id, $message);
        $stmt->execute();
        
        // Update ticket status if needed
        $conn->query("UPDATE support_tickets SET status = 'in_progress' WHERE id = $ticket_id");
    }
    
    header("Location: support.php?ticket=$ticket_id");
    exit;
}

// Get all tickets
$tickets = $conn->query("
    SELECT t.*, 
           (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id AND sender = 'customer' AND is_read = 0) as unread,
           (SELECT message FROM support_messages WHERE ticket_id = t.id ORDER BY id DESC LIMIT 1) as last_msg
    FROM support_tickets t
    ORDER BY 
        CASE t.status
            WHEN 'open' THEN 1
            WHEN 'in_progress' THEN 2
            WHEN 'closed' THEN 3
        END,
        t.created_at DESC
");

// Get single ticket if selected
$selected_ticket = null;
$messages = null;

if (isset($_GET['ticket'])) {
    $ticket_id = (int)$_GET['ticket'];
    
    $selected_ticket = $conn->query("SELECT * FROM support_tickets WHERE id = $ticket_id")->fetch_assoc();
    
    if ($selected_ticket) {
        // Mark messages as read
        $conn->query("UPDATE support_messages SET is_read = 1 WHERE ticket_id = $ticket_id AND sender = 'customer'");
        
        $messages = $conn->query("
            SELECT *, DATE_FORMAT(created_at, '%H:%i') as time 
            FROM support_messages 
            WHERE ticket_id = $ticket_id 
            ORDER BY created_at ASC
        ");
    }
}

$page_title = 'الدعم الفني';
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
:root {
    --primary: #F57C00;
    --primary-soft: #FFF3E0;
}

.support-container {
    display: flex;
    height: calc(100vh - 100px);
    background: white;
    border-radius: 15px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.tickets-sidebar {
    width: 350px;
    border-left: 1px solid #e0e0e0;
    overflow-y: auto;
}

.ticket-item {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: 0.2s;
}

.ticket-item:hover {
    background: #f8f9fa;
}

.ticket-item.active {
    background: var(--primary-soft);
    border-right: 3px solid var(--primary);
}

.ticket-item.unread {
    background: #fff3e0;
}

.ticket-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 5px;
}

.ticket-id {
    font-weight: 700;
    color: var(--primary);
}

.ticket-priority {
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 0.7rem;
    font-weight: 600;
}

.priority-high { background: #ffebee; color: #c62828; }
.priority-medium { background: #fff3e0; color: #f57c00; }
.priority-low { background: #e8f5e9; color: #2e7d32; }

.unread-badge {
    background: var(--primary);
    color: white;
    padding: 2px 6px;
    border-radius: 12px;
    font-size: 0.65rem;
    margin-left: 5px;
}

.chat-area {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.chat-header {
    padding: 15px;
    background: #f8f9fa;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #fafafa;
}

.message {
    margin-bottom: 15px;
    max-width: 70%;
}

.message.customer { margin-left: auto; }
.message.admin { margin-right: auto; }

.message-bubble {
    padding: 12px 16px;
    border-radius: 18px;
    position: relative;
}

.message.customer .message-bubble {
    background: var(--primary);
    color: white;
    border-top-left-radius: 5px;
}

.message.admin .message-bubble {
    background: white;
    border: 1px solid #e0e0e0;
    border-top-right-radius: 5px;
}

.message-time {
    font-size: 0.65rem;
    color: #999;
    margin-top: 3px;
}

.message-attachment {
    max-width: 200px;
    margin-top: 5px;
    cursor: pointer;
}

.message-attachment img {
    width: 100%;
    border-radius: 5px;
}

.reply-box {
    padding: 15px;
    border-top: 1px solid #e0e0e0;
}

.reply-form {
    display: flex;
    gap: 10px;
}

.reply-form textarea {
    flex: 1;
    padding: 12px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    resize: none;
    font-family: 'Tajawal', sans-serif;
}

.reply-form button {
    background: var(--primary);
    color: white;
    border: none;
    padding: 0 20px;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
}

.status-select {
    padding: 5px 10px;
    border: 1px solid #e0e0e0;
    border-radius: 5px;
}

@media (max-width: 768px) {
    .support-container {
        flex-direction: column;
    }
    
    .tickets-sidebar {
        width: 100%;
        height: 200px;
    }
    
    .message {
        max-width: 90%;
    }
}
</style>

<div class="main-content">
    <div class="top-bar">
        <i class="bi bi-headset text-primary fs-4 me-2"></i>
        <span><strong>الدعم الفني</strong></span>
    </div>

    <div class="support-container">
        <!-- Tickets List -->
        <div class="tickets-sidebar">
            <div style="padding: 15px; background: #f8f9fa; border-bottom: 1px solid #e0e0e0;">
                <h5 style="margin: 0;"><i class="bi bi-list"></i> التذاكر</h5>
            </div>
            
            <div id="ticketsList">
                <?php while($t = $tickets->fetch_assoc()): 
                    $priority_class = 'priority-' . $t['priority'];
                    $priority_text = ['low' => 'منخفضة', 'medium' => 'متوسطة', 'high' => 'عالية'][$t['priority']];
                    $is_active = isset($_GET['ticket']) && $_GET['ticket'] == $t['id'];
                ?>
                <div class="ticket-item <?= $t['unread'] > 0 ? 'unread' : '' ?> <?= $is_active ? 'active' : '' ?>" 
                     onclick="window.location.href='?ticket=<?= $t['id'] ?>'">
                    
                    <div class="ticket-header">
                        <span class="ticket-id">#<?= $t['id'] ?></span>
                        <span class="ticket-priority <?= $priority_class ?>"><?= $priority_text ?></span>
                    </div>
                    
                    <div style="font-weight: 600; margin-bottom: 5px;">
                        <?= htmlspecialchars($t['subject']) ?>
                        <?php if ($t['unread'] > 0): ?>
                            <span class="unread-badge"><?= $t['unread'] ?></span>
                        <?php endif; ?>
                    </div>
                    
                    <div style="display: flex; justify-content: space-between; font-size: 0.75rem; color: #666;">
                        <span><?= $t['customer_name'] ?></span>
                        <span><?= $t['order_id'] ? 'طلب #'.$t['order_id'] : 'بدون طلب' ?></span>
                    </div>
                    
                    <div style="font-size: 0.7rem; color: #999; margin-top: 5px;">
                        <?= date('Y-m-d H:i', strtotime($t['created_at'])) ?>
                    </div>
                </div>
                <?php endwhile; ?>
            </div>
        </div>

        <!-- Chat Area -->
        <div class="chat-area">
            <?php if ($selected_ticket): ?>
                <div class="chat-header">
                    <div>
                        <h5 style="margin: 0;">تذكرة #<?= $selected_ticket['id'] ?> - <?= htmlspecialchars($selected_ticket['subject']) ?></h5>
                        <small class="text-muted">
                            <?= $selected_ticket['customer_name'] ?> | 
                            <?= $selected_ticket['customer_phone'] ?> |
                            <?= $selected_ticket['order_id'] ? 'طلب #'.$selected_ticket['order_id'] : '' ?>
                        </small>
                    </div>
                    
                    <select class="status-select" onchange="updateStatus(<?= $selected_ticket['id'] ?>, this.value)">
                        <option value="open" <?= $selected_ticket['status'] == 'open' ? 'selected' : '' ?>>مفتوحة</option>
                        <option value="in_progress" <?= $selected_ticket['status'] == 'in_progress' ? 'selected' : '' ?>>قيد المعالجة</option>
                        <option value="closed" <?= $selected_ticket['status'] == 'closed' ? 'selected' : '' ?>>مغلقة</option>
                    </select>
                </div>

                <div class="messages-container" id="messagesContainer">
                    <?php 
                    $messages->data_seek(0);
                    while($msg = $messages->fetch_assoc()): 
                    ?>
                    <div class="message <?= $msg['sender'] ?>">
                        <div class="message-bubble">
                            <?= nl2br(htmlspecialchars($msg['message'])) ?>
                            
                            <?php if ($msg['attachment']): ?>
                                <div class="message-attachment" onclick="window.open('/uploads/support/<?= $msg['attachment'] ?>', '_blank')">
                                    <img src="/uploads/support/<?= $msg['attachment'] ?>" alt="Attachment">
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="message-time"><?= $msg['time'] ?></div>
                    </div>
                    <?php endwhile; ?>
                </div>

                <?php if ($selected_ticket['status'] != 'closed'): ?>
                <div class="reply-box">
                    <form method="POST" class="reply-form">
                        <input type="hidden" name="ticket_id" value="<?= $selected_ticket['id'] ?>">
                        <textarea name="message" rows="2" placeholder="اكتب ردك هنا..." required></textarea>
                        <button type="submit" name="reply">إرسال</button>
                    </form>
                </div>
                <?php endif; ?>

                <script>
                document.getElementById('messagesContainer').scrollTop = 
                    document.getElementById('messagesContainer').scrollHeight;

                function updateStatus(ticketId, status) {
                    fetch('support_update.php', {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: 'ticket_id=' + ticketId + '&status=' + status
                    });
                }

                // Auto refresh
                setInterval(function() {
                    if (document.visibilityState === 'visible') {
                        location.reload();
                    }
                }, 3000);
                </script>

            <?php else: ?>
                <div style="display: flex; align-items: center; justify-content: center; height: 100%; color: #999;">
                    <i class="bi bi-chat-dots" style="font-size: 3rem; margin-left: 10px;"></i>
                    <span>اختر تذكرة لعرض المحادثة</span>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>