<?php
session_start();
require_once 'db.php';
require_once 'mail_config.php';

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

if (!isset($_GET['id'])) {
    header('Location: dashboard.php');
    exit;
}

$db = new Database();
$conn = $db->connect();
$ticket_id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);

$stmt = $conn->prepare("
    SELECT 
        t.*,
        u.username,
        u.email,
        CASE t.status
            WHEN 'open' THEN 'bg-yellow-400/10 text-yellow-400'
            WHEN 'in_progress' THEN 'bg-blue-400/10 text-blue-400'
            WHEN 'resolved' THEN 'bg-green-400/10 text-green-400'
            ELSE 'bg-gray-400/10 text-gray-400'
        END as status_class,
        CASE t.priority
            WHEN 'high' THEN 'text-red-400'
            WHEN 'medium' THEN 'text-yellow-400'
            ELSE 'text-green-400'
        END as priority_class
    FROM support_tickets t
    JOIN utilisateurs u ON t.user_id = u.id
    WHERE t.id = ? AND (t.user_id = ? OR ? IN (SELECT id FROM utilisateurs WHERE role = 1))
");

$stmt->execute([$ticket_id, $_SESSION['user_id'], $_SESSION['user_id']]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$ticket) {
    $_SESSION['error'] = "Ticket not found or access denied";
    header('Location: dashboard.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['response'])) {
    $response = trim(filter_input(INPUT_POST, 'response', FILTER_SANITIZE_STRING));
    
    try {
        $conn->beginTransaction();
        
        $stmt = $conn->prepare("
            INSERT INTO ticket_responses (ticket_id, user_id, response, is_staff)
            VALUES (?, ?, ?, 0)
        ");
        $stmt->execute([$ticket_id, $_SESSION['user_id'], $response]);
        
        if ($ticket['status'] === 'closed') {
            $stmt = $conn->prepare("
                UPDATE support_tickets 
                SET status = 'open', updated_at = CURRENT_TIMESTAMP 
                WHERE id = ?
            ");
            $stmt->execute([$ticket_id]);
        }
        
        $stmt = $conn->prepare("
            INSERT INTO ticket_notifications (ticket_id, user_id, message)
            SELECT ?, id, ? FROM utilisateurs WHERE role = 1
        ");
        $notification_message = "New client response on ticket #$ticket_id";
        $stmt->execute([$ticket_id, $notification_message]);
        
        $emailBody = "
            <div style='font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;'>
                <h2>New Client Response - Ticket #{$ticket_id}</h2>
                <p><strong>Client:</strong> {$ticket['username']}</p>
                <p><strong>Response:</strong></p>
                <div style='background: #f5f5f5; padding: 15px; border-radius: 5px;'>
                    " . nl2br(htmlspecialchars($response)) . "
                </div>
                <p>Please review and respond to this ticket at your earliest convenience.</p>
            </div>
        ";
        
        sendTicketEmail('support@imators.com', "New Response - Ticket #$ticket_id", $emailBody);
        
        $conn->commit();
        $_SESSION['success'] = "Your response has been submitted successfully.";
        
    } catch (PDOException $e) {
        $conn->rollBack();
        $_SESSION['error'] = "There was an error submitting your response.";
        error_log("Ticket response error: " . $e->getMessage());
    }
    
    header("Location: view_ticket.php?id=" . $ticket_id);
    exit;
}

$stmt = $conn->prepare("
    SELECT 
        r.*,
        u.username,
        u.role
    FROM ticket_responses r
    JOIN utilisateurs u ON r.user_id = u.id
    WHERE r.ticket_id = ?
    ORDER BY r.created_at ASC
");
$stmt->execute([$ticket_id]);
$responses = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $conn->prepare("
    UPDATE ticket_notifications 
    SET is_read = TRUE 
    WHERE ticket_id = ? AND user_id = ? AND is_read = FALSE
");
$stmt->execute([$ticket_id, $_SESSION['user_id']]);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ticket #<?php echo $ticket_id; ?> - Support</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #000000, #1a1a1a);
            min-height: 100vh;
        }
        
        .glass-effect {
            backdrop-filter: blur(12px);
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .message-bubble {
            position: relative;
            margin-bottom: 1.5rem;
        }
        
        .hover-scale {
            transition: transform 0.2s ease;
        }
        
        .hover-scale:hover {
            transform: translateY(-2px);
        }
    </style>
</head>
<body class="text-white bg-black">
    <nav class="bg-black border-b border-white/10 sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16 items-center">
                <div class="flex items-center space-x-4">
                    <a href="dashboard.php" class="text-gray-300 hover:text-white">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                        </svg>
                    </a>
                    <h1 class="text-xl font-semibold">Ticket #<?php echo $ticket_id; ?></h1>
                </div>
                <div class="flex items-center space-x-4">
                    <span class="px-3 py-1 rounded-full <?php echo $ticket['status_class']; ?>">
                        <?php echo ucfirst($ticket['status']); ?>
                    </span>
                </div>
            </div>
        </div>
    </nav>

    <main class="max-w-4xl mx-auto px-4 py-8">
        <?php if (isset($_SESSION['success'])): ?>
            <div class="mb-6 p-4 bg-green-500/10 border border-green-500/20 rounded-lg">
                <p class="text-green-400"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></p>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="mb-6 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
                <p class="text-red-400"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></p>
            </div>
        <?php endif; ?>

        <div class="glass-effect rounded-lg p-6 mb-6">
            <div class="mb-6">
                <h2 class="text-xl font-semibold mb-4"><?php echo htmlspecialchars($ticket['subject']); ?></h2>
                <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                    <div>
                        <span class="text-gray-400 text-sm">Created</span>
                        <p><?php echo date('m/d/Y H:i', strtotime($ticket['created_at'])); ?></p>
                    </div>
                    <div>
                        <span class="text-gray-400 text-sm">Last Updated</span>
                        <p><?php echo date('m/d/Y H:i', strtotime($ticket['updated_at'])); ?></p>
                    </div>
                    <div>
                        <span class="text-gray-400 text-sm">Priority</span>
                        <p class="<?php echo $ticket['priority_class']; ?>"><?php echo ucfirst($ticket['priority']); ?></p>
                    </div>
                    <div>
                        <span class="text-gray-400 text-sm">Status</span>
                        <p class="<?php echo $ticket['status_class']; ?>"><?php echo ucfirst($ticket['status']); ?></p>
                    </div>
                </div>
            </div>

            <div class="border-t border-white/10 pt-6">
                <h3 class="text-lg font-medium mb-4">Description</h3>
                <div class="prose prose-invert max-w-none">
                    <?php echo nl2br(htmlspecialchars($ticket['description'])); ?>
                </div>
            </div>
        </div>

        <div class="glass-effect rounded-lg p-6 mb-6">
            <h3 class="text-lg font-medium mb-6">Conversation</h3>
            <div class="space-y-6">
                <?php foreach ($responses as $response): ?>
                    <div class="message-bubble <?php echo $response['is_staff'] ? 'ml-12' : 'mr-12'; ?>">
                        <div class="p-4 rounded-lg <?php echo $response['is_staff'] ? 'bg-indigo-500/10' : 'bg-white/5'; ?>">
                            <div class="flex justify-between items-start mb-3">
                                <div class="flex items-center space-x-2">
                                    <?php if ($response['is_staff']): ?>
                                        <span class="px-2 py-1 bg-indigo-500/20 text-indigo-400 rounded text-sm">Support Team</span>
                                    <?php else: ?>
                                        <span class="text-gray-300"><?php echo htmlspecialchars($response['username']); ?></span>
                                    <?php endif; ?>
                                </div>
                                <span class="text-xs text-gray-500">
                                    <?php echo date('m/d/Y H:i', strtotime($response['created_at'])); ?>
                                </span>
                            </div>
                            <div class="prose prose-invert max-w-none">
                                <?php echo nl2br(htmlspecialchars($response['response'])); ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if ($ticket['status'] !== 'closed'): ?>
            <div class="glass-effect rounded-lg p-6">
                <form method="POST" id="replyForm" class="space-y-4">
                    <div>
                        <label for="response" class="block text-sm font-medium mb-2">Your Response</label>
                        <textarea
                            id="response"
                            name="response"
                            rows="4"
                            required
                            class="w-full px-4 py-3 bg-black/50 border border-white/10 rounded-lg focus:border-white/30 focus:ring focus:ring-white/10 resize-none"
                            placeholder="Type your message..."
                        ></textarea>
                    </div>
                    <div class="flex justify-end">
                        <button
                            type="submit"
                            id="submitButton"
                            class="px-6 py-3 bg-white text-black rounded-lg font-medium hover:bg-gray-100 hover-scale"
                        >
                            Send Response
                        </button>
                    </div>
                </form>
            </div>
        <?php else: ?>
            <div class="glass-effect rounded-lg p-6 text-center">
                <p class="text-gray-400 mb-4">This ticket is closed. Need more help?</p>
                <a
                    href="create_ticket.php"
                    class="inline-block px-6 py-3 bg-white text-black rounded-lg font-medium hover:bg-gray-100 hover-scale"
                >
                    Create New Ticket
                </a>
            </div>
        <?php endif; ?>
    </main>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('replyForm');
        const textarea = document.getElementById('response');
        const submitButton = document.getElementById('submitButton');

        if (form) {
            textarea.addEventListener('input', function() {
                this.style.height = 'auto';
                this.style.height = (this.scrollHeight) + 'px';
            });

            form.addEventListener('submit', function(e) {
                submitButton.disabled = true;
                submitButton.innerHTML = `
                    <svg class="animate-spin -ml-1 mr-3 h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    Sending...
                `;
            });
        }

        const conversationContainer = document.querySelector('.space-y-6');
        if (conversationContainer) {
            conversationContainer.scrollTop = conversationContainer.scrollHeight;
        }
    });
    </script>
</body>
</html>