<?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'];
$specialization = $_SESSION['doctor_specialization'] ?? 'General Medicine';

// ========== CREATE ENGAGEMENT TABLES IF NOT EXISTS ==========
$conn->query("CREATE TABLE IF NOT EXISTS doctor_collaborations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    doctor_id INT NOT NULL,
    invited_doctor_id INT NOT NULL,
    topic VARCHAR(255),
    description TEXT,
    status ENUM('pending','accepted','declined') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)");

$conn->query("CREATE TABLE IF NOT EXISTS cme_sessions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255),
    description TEXT,
    scheduled_date DATE,
    scheduled_time TIME,
    credits INT DEFAULT 0,
    status ENUM('upcoming','ongoing','completed') DEFAULT 'upcoming',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$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,
    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 ENGAGEMENT STATS ==========
$collab_count = 0;
$collab_check = $conn->query("SELECT COUNT(*) as cnt FROM doctor_collaborations WHERE doctor_id = '$doctor_id' OR invited_doctor_id = '$doctor_id'");
if ($collab_check && $collab_check->num_rows) {
    $collab_count = $collab_check->fetch_assoc()['cnt'];
}

$cme_count = 0;
$cme_check = $conn->query("SELECT COUNT(*) as cnt FROM cme_sessions WHERE status = 'upcoming'");
if ($cme_check && $cme_check->num_rows) {
    $cme_count = $cme_check->fetch_assoc()['cnt'];
}

$discussion_count = 0;
$discussion_check = $conn->query("SELECT COUNT(*) as cnt FROM forum_discussions WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)");
if ($discussion_check && $discussion_check->num_rows) {
    $discussion_count = $discussion_check->fetch_assoc()['cnt'];
}

// ========== GET ALL DOCTORS FOR COLLABORATION ==========
// FIXED: Using 'name' instead of 'doctor_name'
$all_doctors = $conn->query("SELECT doctor_id, name, specialization FROM doctors WHERE doctor_id != '$doctor_id' AND status = 'active'");

// ========== GET EXISTING COLLABORATIONS ==========
// FIXED: Using 'name' instead of 'doctor_name'
$my_collaborations = $conn->query("
    SELECT dc.*, 
           CASE 
               WHEN dc.doctor_id = '$doctor_id' THEN d2.name 
               ELSE d1.name 
           END as other_doctor_name,
           CASE 
               WHEN dc.doctor_id = '$doctor_id' THEN d2.specialization 
               ELSE d1.specialization 
           END as other_specialization
    FROM doctor_collaborations dc
    LEFT JOIN doctors d1 ON dc.doctor_id = d1.doctor_id
    LEFT JOIN doctors d2 ON dc.invited_doctor_id = d2.doctor_id
    WHERE dc.doctor_id = '$doctor_id' OR dc.invited_doctor_id = '$doctor_id'
    ORDER BY dc.created_at DESC
");

// ========== GET FORUM DISCUSSIONS ==========
// FIXED: Using 'name' instead of 'doctor_name'
$discussions = $conn->query("
    SELECT fd.*, d.name as doctor_name, d.specialization,
           (SELECT COUNT(*) FROM forum_replies WHERE discussion_id = fd.id) as reply_count
    FROM forum_discussions fd
    JOIN doctors d ON fd.doctor_id = d.doctor_id
    ORDER BY fd.created_at DESC LIMIT 10
");

// ========== GET CME SESSIONS ==========
$cme_sessions = $conn->query("SELECT * FROM cme_sessions WHERE status = 'upcoming' ORDER BY scheduled_date ASC LIMIT 5");

// ========== GET LEADERBOARD ==========
// FIXED: Using 'name' instead of 'doctor_name'
$leaderboard = $conn->query("
    SELECT d.name as doctor_name, d.specialization,
        (SELECT COUNT(*) FROM doctor_collaborations WHERE (doctor_id = d.doctor_id OR invited_doctor_id = d.doctor_id) AND status = 'accepted') as collabs,
        (SELECT COUNT(*) FROM forum_discussions WHERE doctor_id = d.doctor_id) as discussions,
        ((SELECT COUNT(*) FROM doctor_collaborations WHERE (doctor_id = d.doctor_id OR invited_doctor_id = d.doctor_id) AND status = 'accepted') * 10 +
         (SELECT COUNT(*) FROM forum_discussions WHERE doctor_id = d.doctor_id) * 5) as points
    FROM doctors d
    WHERE d.status = 'active'
    ORDER BY points DESC
    LIMIT 5
");

// ========== HANDLE POST ACTIONS ==========
$success_msg = '';
$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['invite_collaboration'])) {
        $invited_doctor_id = (int)$_POST['invited_doctor_id'];
        $collab_topic = $conn->real_escape_string($_POST['collab_topic']);
        $collab_description = $conn->real_escape_string($_POST['collab_description']);
        
        $insert = $conn->query("INSERT INTO doctor_collaborations (doctor_id, invited_doctor_id, topic, description, status) 
                                VALUES ('$doctor_id', '$invited_doctor_id', '$collab_topic', '$collab_description', 'pending')");
        if ($insert) {
            $success_msg = "Collaboration invitation sent successfully!";
        } else {
            $error_msg = "Error sending invitation: " . $conn->error;
        }
    }
    
    if (isset($_POST['accept_collaboration'])) {
        $collab_id = (int)$_POST['collab_id'];
        $conn->query("UPDATE doctor_collaborations SET status = 'accepted', updated_at = NOW() WHERE id = '$collab_id'");
        $success_msg = "Collaboration accepted!";
    }
    
    if (isset($_POST['decline_collaboration'])) {
        $collab_id = (int)$_POST['collab_id'];
        $conn->query("UPDATE doctor_collaborations SET status = 'declined', updated_at = NOW() WHERE id = '$collab_id'");
        $success_msg = "Collaboration declined.";
    }
    
    if (isset($_POST['post_discussion'])) {
        $title = $conn->real_escape_string($_POST['title']);
        $content = $conn->real_escape_string($_POST['content']);
        $insert = $conn->query("INSERT INTO forum_discussions (doctor_id, title, content) VALUES ('$doctor_id', '$title', '$content')");
        if ($insert) {
            $success_msg = "Discussion posted successfully!";
        } else {
            $error_msg = "Error posting discussion: " . $conn->error;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Doctor Engagement Hub | UHD</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; }
        
        .engagement-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
            margin-bottom: 25px;
            overflow: hidden;
        }
        .engagement-header {
            background: linear-gradient(135deg, var(--uhd-green), var(--uhd-dark));
            padding: 18px 24px;
            color: white;
        }
        .engagement-header h5 { margin: 0; font-weight: 600; }
        .stat-engagement {
            background: white;
            border-radius: 20px;
            padding: 20px;
            text-align: center;
            border: 1px solid #e0e0e0;
        }
        .stat-engagement h3 {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--uhd-gold);
            margin: 10px 0;
        }
        .collab-list-item {
            background: #f8f9fa;
            border-left: 4px solid var(--uhd-gold);
            margin-bottom: 12px;
            padding: 15px;
            border-radius: 12px;
        }
        .btn-gold {
            background: var(--uhd-gold);
            color: white;
            border-radius: 30px;
            padding: 8px 20px;
            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: 6px 16px;
        }
        .btn-outline-gold:hover { background: var(--uhd-gold); color: white; }
        .discussion-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 15px;
            cursor: pointer;
        }
        .discussion-card:hover { background: #fff8e7; border-left: 4px solid var(--uhd-gold); }
        .badge-cme { background: var(--uhd-gold); color: white; padding: 5px 12px; border-radius: 20px; font-size: 0.7rem; }
        .leaderboard-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 0;
            border-bottom: 1px solid #e0e0e0;
        }
        .rank-icon {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        .rank-1 { background: linear-gradient(135deg, #ffd700, #ffb800); color: #1a1a2e; }
        .rank-2 { background: linear-gradient(135deg, #c0c0c0, #a8a8a8); color: #1a1a2e; }
        .rank-3 { background: linear-gradient(135deg, #cd7f32, #b87333); color: white; }
        .rank-other { background: #e0e0e0; color: #666; }
    </style>
</head>
<body>
<div class="container py-4">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="text-success"><i class="fas fa-handshake me-2" style="color: var(--uhd-gold);"></i> Doctor Engagement Hub</h2>
        <button class="btn btn-gold" data-bs-toggle="modal" data-bs-target="#collaborateModal"><i class="fas fa-plus"></i> Start Collaboration</button>
    </div>

    <!-- Alerts -->
    <?php if ($success_msg): ?>
        <div class="alert alert-success"><?= $success_msg ?></div>
    <?php endif; ?>
    <?php if ($error_msg): ?>
        <div class="alert alert-danger"><?= $error_msg ?></div>
    <?php endif; ?>

    <!-- Stats Row -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-6"><div class="stat-engagement"><i class="fas fa-project-diagram fa-2x" style="color: var(--uhd-gold);"></i><h3><?= $collab_count ?></h3><p>Collaborations</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-engagement"><i class="fas fa-graduation-cap fa-2x" style="color: var(--uhd-gold);"></i><h3><?= $cme_count ?></h3><p>Upcoming CMEs</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-engagement"><i class="fas fa-comments fa-2x" style="color: var(--uhd-gold);"></i><h3><?= $discussion_count ?></h3><p>Discussions</p></div></div>
        <div class="col-md-3 col-6"><div class="stat-engagement"><i class="fas fa-trophy fa-2x" style="color: var(--uhd-gold);"></i><h3>Active</h3><p>Members</p></div></div>
    </div>

    <!-- My Collaborations -->
    <div class="engagement-card">
        <div class="engagement-header"><h5><i class="fas fa-users me-2"></i> My Collaborations</h5></div>
        <div class="p-3">
            <?php if ($my_collaborations && $my_collaborations->num_rows > 0): ?>
                <?php while ($collab = $my_collaborations->fetch_assoc()): ?>
                    <div class="collab-list-item">
                        <div class="d-flex justify-content-between">
                            <div><h6><?= htmlspecialchars($collab['topic'] ?? 'No Topic') ?></h6><small class="text-muted">Dr. <?= htmlspecialchars($collab['other_doctor_name'] ?? 'Unknown') ?></small></div>
                            <span class="badge bg-<?= $collab['status'] == 'accepted' ? 'success' : 'warning' ?>"><?= ucfirst($collab['status']) ?></span>
                        </div>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p class="text-muted text-center py-3">No collaborations yet.</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Forum Discussions -->
    <div class="engagement-card">
        <div class="engagement-header"><h5><i class="fas fa-comments me-2"></i> Recent Discussions</h5></div>
        <div class="p-3">
            <?php if ($discussions && $discussions->num_rows > 0): ?>
                <?php while ($disc = $discussions->fetch_assoc()): ?>
                    <div class="discussion-card" onclick="location.href='discussion_detail.php?id=<?= $disc['id'] ?>'">
                        <h6><?= htmlspecialchars($disc['title']) ?></h6>
                        <small class="text-muted">Dr. <?= htmlspecialchars($disc['doctor_name']) ?> • <?= date('M d', strtotime($disc['created_at'])) ?> • <?= $disc['reply_count'] ?> replies</small>
                    </div>
                <?php endwhile; ?>
            <?php else: ?>
                <p class="text-muted text-center py-3">No discussions yet.</p>
            <?php endif; ?>
            <button class="btn btn-outline-gold w-100 mt-2" data-bs-toggle="modal" data-bs-target="#discussionModal">Post a Discussion</button>
        </div>
    </div>

    <!-- Leaderboard -->
    <div class="engagement-card">
        <div class="engagement-header"><h5><i class="fas fa-chart-line me-2"></i> Leaderboard</h5></div>
        <div class="p-3">
            <?php $rank = 1; if ($leaderboard && $leaderboard->num_rows > 0): while ($doc = $leaderboard->fetch_assoc()): ?>
                <div class="leaderboard-item">
                    <div class="rank-icon <?= $rank == 1 ? 'rank-1' : ($rank == 2 ? 'rank-2' : ($rank == 3 ? 'rank-3' : 'rank-other')) ?>"><?= $rank ?></div>
                    <div><strong>Dr. <?= htmlspecialchars($doc['doctor_name']) ?></strong><br><small><?= htmlspecialchars($doc['specialization']) ?></small></div>
                    <div class="ms-auto text-gold fw-bold"><?= $doc['points'] ?? 0 ?> pts</div>
                </div>
            <?php $rank++; endwhile; endif; ?>
        </div>
    </div>
</div>

<!-- Collaborate Modal -->
<div class="modal fade" id="collaborateModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content">
        <div class="modal-header bg-success text-white"><h5>Start Collaboration</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <form method="POST"><div class="modal-body">
            <select name="invited_doctor_id" class="form-select mb-2" required>
                <option value="">Select Doctor</option>
                <?php if ($all_doctors && $all_doctors->num_rows > 0): while($doc = $all_doctors->fetch_assoc()): ?>
                    <option value="<?= $doc['doctor_id'] ?>">Dr. <?= htmlspecialchars($doc['name']) ?> (<?= htmlspecialchars($doc['specialization']) ?>)</option>
                <?php endwhile; endif; ?>
            </select>
            <input type="text" name="collab_topic" class="form-control mb-2" placeholder="Topic" required>
            <textarea name="collab_description" class="form-control" rows="3" placeholder="Description" required></textarea>
        </div><div class="modal-footer"><button type="submit" name="invite_collaboration" class="btn btn-gold">Send Invitation</button></div></form>
    </div></div>
</div>

<!-- Discussion Modal -->
<div class="modal fade" id="discussionModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content">
        <div class="modal-header bg-info text-white"><h5>Post Discussion</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <form method="POST"><div class="modal-body">
            <input type="text" name="title" class="form-control mb-2" placeholder="Title" required>
            <textarea name="content" class="form-control" rows="3" placeholder="Content" required></textarea>
        </div><div class="modal-footer"><button type="submit" name="post_discussion" class="btn btn-gold">Post</button></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>