<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

include '../include/config.php';

$doctor_id = $_SESSION['doctor_id'];
$doctor_name = $_SESSION['doctor_name'];
$discussion_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($discussion_id == 0) {
    header("Location: doctor_engagement.php");
    exit();
}

// Create forum tables if not exists
$conn->query("CREATE TABLE IF NOT EXISTS forum_discussions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    doctor_id INT NOT NULL,
    title VARCHAR(255),
    content TEXT,
    views INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$conn->query("CREATE TABLE IF NOT EXISTS forum_replies (
    id INT AUTO_INCREMENT PRIMARY KEY,
    discussion_id INT NOT NULL,
    doctor_id INT NOT NULL,
    content TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Get discussion details
$discussion = $conn->query("
    SELECT fd.*, d.doctor_name, d.specialization
    FROM forum_discussions fd
    JOIN doctors d ON fd.doctor_id = d.doctor_id
    WHERE fd.id = '$discussion_id'
")->fetch_assoc();

if (!$discussion) {
    header("Location: doctor_engagement.php?error=Discussion not found");
    exit();
}

// Update view count
$conn->query("UPDATE forum_discussions SET views = views + 1 WHERE id = '$discussion_id'");

// Handle reply submission
$success_msg = '';
$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['post_reply'])) {
    $content = $conn->real_escape_string($_POST['content']);
    
    if (empty(trim($content))) {
        $error_msg = "Reply content cannot be empty.";
    } else {
        $insert = $conn->query("INSERT INTO forum_replies (discussion_id, doctor_id, content, created_at) 
                                VALUES ('$discussion_id', '$doctor_id', '$content', NOW())");
        if ($insert) {
            $success_msg = "Reply posted successfully!";
            // Log engagement
            $conn->query("INSERT INTO doctor_engagement_feed (doctor_id, activity_type, activity_data) 
                          VALUES ('$doctor_id', 'discussion_replied', 'Replied to discussion: " . $conn->real_escape_string($discussion['title']) . "')");
        } else {
            $error_msg = "Error posting reply: " . $conn->error;
        }
    }
}

// Get replies
$replies = $conn->query("
    SELECT fr.*, d.doctor_name, d.specialization
    FROM forum_replies fr
    JOIN doctors d ON fr.doctor_id = d.doctor_id
    WHERE fr.discussion_id = '$discussion_id'
    ORDER BY fr.created_at ASC
");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($discussion['title']) ?> | UHD Discussion</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        :root {
            --uhd-green: #0a3d2f;
            --uhd-gold: #d4a017;
            --uhd-dark: #064e3b;
        }
        body { background: #f0f2f5; font-family: 'Segoe UI', sans-serif; }
        
        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100%;
            background: linear-gradient(135deg, #0a3d2f, #064e3b);
            color: white;
            z-index: 1000;
            overflow-y: auto;
            transition: 0.3s;
        }
        .sidebar-header {
            padding: 25px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.2);
        }
        .sidebar-header h4 { font-size: 1.2rem; margin: 10px 0 5px; }
        .sidebar-header p { font-size: 0.75rem; opacity: 0.8; }
        .sidebar-menu a {
            display: block;
            padding: 12px 20px;
            color: white;
            text-decoration: none;
            transition: 0.2s;
        }
        .sidebar-menu a:hover, .sidebar-menu a.active {
            background: rgba(255,255,255,0.15);
            border-left: 4px solid var(--uhd-gold);
        }
        .sidebar-menu i { width: 28px; margin-right: 10px; }
        
        .main-content {
            margin-left: 280px;
            padding: 25px;
            transition: 0.3s;
        }
        
        .discussion-container {
            max-width: 1000px;
            margin: 0 auto;
        }
        .discussion-card {
            background: white;
            border-radius: 24px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }
        .reply-card {
            background: #f8f9fa;
            border-radius: 20px;
            padding: 20px;
            margin-bottom: 18px;
            border-left: 4px solid var(--uhd-gold);
            transition: 0.2s;
        }
        .reply-card:hover {
            background: #fff8e7;
            transform: translateX(3px);
        }
        .reply-form textarea {
            border-radius: 16px;
            border: 1px solid #e0e0e0;
            padding: 15px;
            transition: 0.2s;
        }
        .reply-form textarea:focus {
            border-color: var(--uhd-gold);
            outline: none;
            box-shadow: 0 0 0 3px rgba(212,160,23,0.1);
        }
        .btn-gold {
            background: var(--uhd-gold);
            color: white;
            border-radius: 30px;
            padding: 10px 25px;
            font-weight: 500;
            border: none;
        }
        .btn-gold:hover {
            background: #b8860b;
            color: white;
        }
        .btn-outline-gold {
            background: transparent;
            border: 1px solid var(--uhd-gold);
            color: var(--uhd-gold);
            border-radius: 30px;
            padding: 8px 20px;
        }
        .btn-outline-gold:hover {
            background: var(--uhd-gold);
            color: white;
        }
        .menu-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1100;
            background: var(--uhd-green);
            color: white;
            border: none;
            padding: 8px 14px;
            border-radius: 8px;
        }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); width: 260px; }
            .sidebar.active { transform: translateX(0); }
            .main-content { margin-left: 0; }
            .menu-toggle { display: block; }
            .discussion-card { padding: 20px; }
        }
    </style>
</head>
<body>

<button class="menu-toggle" onclick="document.getElementById('sidebar').classList.toggle('active')">
    <i class="fas fa-bars"></i> Menu
</button>

<div class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <i class="fas fa-comments fa-3x mb-2" style="color: var(--uhd-gold);"></i>
        <h4>Dr. <?= htmlspecialchars($doctor_name) ?></h4>
        <p>UHD Discussion Forum</p>
    </div>
    <div class="sidebar-menu">
        <a href="dashboard.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
        <a href="my_patients.php"><i class="fas fa-users"></i> My Patients</a>
        <a href="consultations.php"><i class="fas fa-video"></i> Video Consult</a>
        <a href="appointments.php"><i class="fas fa-calendar-alt"></i> Appointments</a>
        <a href="doctor_engagement.php" class="active"><i class="fas fa-handshake"></i> Engagement Hub</a>
        <a href="cme_sessions.php"><i class="fas fa-graduation-cap"></i> CME Sessions</a>
        <a href="ai_assistant.php"><i class="fas fa-robot"></i> AI Assistant</a>
        <a href="doctor_payments.php"><i class="fas fa-money-bill-wave"></i> Payments</a>
        <a href="referral.php"><i class="fas fa-share-alt"></i> Refer & Earn</a>
        <a href="profile.php"><i class="fas fa-user-edit"></i> Profile</a>
        <a href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
    </div>
</div>

<div class="main-content">
    <div class="discussion-container">
        <!-- Alerts -->
        <?php if ($success_msg): ?>
            <div class="alert alert-success alert-dismissible fade show"><?= $success_msg ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>
        <?php if ($error_msg): ?>
            <div class="alert alert-danger alert-dismissible fade show"><?= $error_msg ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>
        <?php endif; ?>

        <!-- Discussion Card -->
        <div class="discussion-card">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <h3 class="mb-0" style="color: var(--uhd-green);">
                    <i class="fas fa-comment-dots me-2" style="color: var(--uhd-gold);"></i>
                    <?= htmlspecialchars($discussion['title']) ?>
                </h3>
                <span class="badge bg-secondary px-3 py-2">
                    <i class="fas fa-eye me-1"></i> <?= $discussion['views'] ?> views
                </span>
            </div>
            
            <div class="mb-3 pb-2 border-bottom">
                <i class="fas fa-user-md me-1" style="color: var(--uhd-gold);"></i>
                <strong>Dr. <?= htmlspecialchars($discussion['doctor_name']) ?></strong>
                <small class="text-muted">(<?= htmlspecialchars($discussion['specialization']) ?>)</small>
                <span class="mx-2">•</span>
                <i class="fas fa-calendar-alt me-1 text-muted"></i>
                <small class="text-muted"><?= date('l, F j, Y \a\t h:i A', strtotime($discussion['created_at'])) ?></small>
            </div>
            
            <div class="content" style="line-height: 1.8; font-size: 1rem;">
                <?= nl2br(htmlspecialchars($discussion['content'])) ?>
            </div>
        </div>

        <!-- Replies Section -->
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h5><i class="fas fa-reply-all me-2" style="color: var(--uhd-gold);"></i> Replies (<?= $replies->num_rows ?>)</h5>
        </div>

        <?php if ($replies && $replies->num_rows > 0): ?>
            <?php while ($reply = $replies->fetch_assoc()): ?>
                <div class="reply-card">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div>
                            <i class="fas fa-user-circle me-1" style="color: var(--uhd-gold);"></i>
                            <strong>Dr. <?= htmlspecialchars($reply['doctor_name']) ?></strong>
                            <small class="text-muted">(<?= htmlspecialchars($reply['specialization']) ?>)</small>
                        </div>
                        <small class="text-muted">
                            <i class="fas fa-clock me-1"></i> <?= date('M d, Y h:i A', strtotime($reply['created_at'])) ?>
                        </small>
                    </div>
                    <div class="mt-2">
                        <?= nl2br(htmlspecialchars($reply['content'])) ?>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="alert alert-light text-center py-4">
                <i class="fas fa-comment-slash fa-2x mb-2 text-muted"></i>
                <p class="mb-0">No replies yet. Be the first to respond!</p>
            </div>
        <?php endif; ?>

        <!-- Reply Form -->
        <div class="discussion-card">
            <h6 class="mb-3"><i class="fas fa-edit me-2" style="color: var(--uhd-gold);"></i> Post a Reply</h6>
            <form method="POST" class="reply-form">
                <textarea name="content" class="form-control" rows="4" placeholder="Write your reply here... Share your insights, ask clarifying questions, or provide feedback..." required></textarea>
                <div class="mt-3 d-flex gap-2">
                    <button type="submit" name="post_reply" class="btn btn-gold">
                        <i class="fas fa-paper-plane me-2"></i> Post Reply
                    </button>
                    <a href="doctor_engagement.php" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i> Back to Engagement Hub
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>