<?php
/**
 * Admin Support - Live Chat with Users
 */
require_once '../config/config.php';
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/Auth.php';

if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// Handle reply
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reply'])) {
    $ticketId = (int)$_POST['ticket_id'];
    $message = trim($_POST['message'] ?? '');
    
    if (!empty($message) && $ticketId > 0) {
        dbInsert('support_messages', [
            'ticket_id' => $ticketId,
            'user_id' => $_SESSION['admin_id'] ?? 0,
            'message' => $message,
            'is_admin' => 1,
            'created_at' => date('Y-m-d H:i:s')
        ]);
        dbQuery("UPDATE support_tickets SET updated_at = NOW(), status = 'pending' WHERE id = :id", ['id' => $ticketId]);
        header("Location: support.php?ticket=$ticketId&replied=1");
        exit;
    }
}

// Get selected ticket
$selectedTicket = null;
$messages = [];
if (isset($_GET['ticket'])) {
    $ticketId = (int)$_GET['ticket'];
    $selectedTicket = dbFetch(
        "SELECT t.*, CONCAT(u.first_name, ' ', u.last_name) as user_name, u.email as user_email
         FROM support_tickets t 
         JOIN users u ON t.user_id = u.id 
         WHERE t.id = :id",
        ['id' => $ticketId]
    );
    
    if ($selectedTicket) {
        $messages = dbFetchAll(
            "SELECT m.*, CONCAT(u.first_name, ' ', u.last_name) as sender_name 
             FROM support_messages m 
             LEFT JOIN users u ON m.user_id = u.id 
             WHERE m.ticket_id = :tid 
             ORDER BY m.created_at ASC",
            ['tid' => $ticketId]
        );
    }
}

// Get all tickets
$tickets = dbFetchAll(
    "SELECT t.*, CONCAT(u.first_name, ' ', u.last_name) as user_name,
            (SELECT COUNT(*) FROM support_messages WHERE ticket_id = t.id AND is_admin = 0) as user_msgs,
            (SELECT message FROM support_messages WHERE ticket_id = t.id ORDER BY created_at DESC LIMIT 1) as last_message
     FROM support_tickets t 
     JOIN users u ON t.user_id = u.id 
     ORDER BY t.updated_at DESC 
     LIMIT 50"
);

include 'includes/header.php';
?>

<div class="container-fluid py-4">
    <div class="row">
        <!-- Ticket List -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-headset me-2"></i>Live Support</h5>
                </div>
                <div class="list-group list-group-flush" style="max-height:600px;overflow-y:auto">
                    <?php if (empty($tickets)): ?>
                    <div class="list-group-item text-muted text-center py-4">No support tickets</div>
                    <?php else: ?>
                    <?php foreach ($tickets as $t): ?>
                    <a href="?ticket=<?= $t['id'] ?>" class="list-group-item list-group-item-action <?= ($selectedTicket && $selectedTicket['id'] == $t['id']) ? 'active' : '' ?>">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong><?= htmlspecialchars($t['user_name']) ?></strong>
                                <small class="d-block text-muted"><?= htmlspecialchars(substr($t['last_message'] ?? 'No messages', 0, 40)) ?>...</small>
                            </div>
                            <div class="text-end">
                                <span class="badge bg-<?= $t['status'] === 'open' ? 'success' : ($t['status'] === 'pending' ? 'warning' : 'secondary') ?>"><?= ucfirst($t['status']) ?></span>
                                <small class="d-block"><?= date('H:i', strtotime($t['updated_at'])) ?></small>
                            </div>
                        </div>
                    </a>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Chat -->
        <div class="col-md-8">
            <?php if ($selectedTicket): ?>
            <div class="card">
                <div class="card-header bg-light">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="mb-0"><?= htmlspecialchars($selectedTicket['user_name']) ?></h5>
                            <small class="text-muted"><?= htmlspecialchars($selectedTicket['user_email']) ?></small>
                        </div>
                        <span class="badge bg-<?= $selectedTicket['status'] === 'open' ? 'success' : 'warning' ?> fs-6"><?= ucfirst($selectedTicket['status']) ?></span>
                    </div>
                </div>
                <div class="card-body" style="height:400px;overflow-y:auto;background:#f8f9fa" id="chatBox">
                    <?php foreach ($messages as $m): ?>
                    <div class="mb-3 <?= $m['is_admin'] ? 'text-end' : '' ?>">
                        <div class="d-inline-block p-3 rounded-3 <?= $m['is_admin'] ? 'bg-primary text-white' : 'bg-white border' ?>" style="max-width:70%">
                            <div><?= nl2br(htmlspecialchars($m['message'])) ?></div>
                            <small class="<?= $m['is_admin'] ? 'text-white-50' : 'text-muted' ?>"><?= date('M d, H:i', strtotime($m['created_at'])) ?></small>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <div class="card-footer">
                    <form method="POST" class="d-flex gap-2">
                        <input type="hidden" name="ticket_id" value="<?= $selectedTicket['id'] ?>">
                        <input type="text" name="message" class="form-control" placeholder="Type your reply..." required autofocus>
                        <button type="submit" name="reply" class="btn btn-primary"><i class="fas fa-paper-plane"></i></button>
                    </form>
                </div>
            </div>
            <?php else: ?>
            <div class="card">
                <div class="card-body text-center py-5 text-muted">
                    <i class="fas fa-comments fa-4x mb-3"></i>
                    <p>Select a ticket to view conversation</p>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Auto scroll to bottom
const chatBox = document.getElementById('chatBox');
if (chatBox) chatBox.scrollTop = chatBox.scrollHeight;

// Auto refresh
setInterval(() => {
    if (<?= $selectedTicket ? 'true' : 'false' ?>) {
        location.reload();
    }
}, 10000);
</script>

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