<?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'];
$collab_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Create collaboration table 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
)");

// Get collaboration details
$collab = $conn->query("
    SELECT dc.*, 
           d1.doctor_name as requester_name,
           d1.specialization as requester_spec,
           d2.doctor_name as invitee_name,
           d2.specialization as invitee_spec
    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.id = '$collab_id'
")->fetch_assoc();

if (!$collab) {
    header("Location: doctor_engagement.php");
    exit();
}

// Handle collaboration actions
$success_msg = '';
$error_msg = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['accept_collaboration'])) {
        $update = $conn->query("UPDATE doctor_collaborations SET status = 'accepted', updated_at = NOW() WHERE id = '$collab_id'");
        if ($update) {
            $success_msg = "Collaboration accepted! You can now collaborate with Dr. " . htmlspecialchars($collab['requester_name']);
            $collab['status'] = 'accepted';
        } else {
            $error_msg = "Error accepting collaboration.";
        }
    }
    
    if (isset($_POST['decline_collaboration'])) {
        $update = $conn->query("UPDATE doctor_collaborations SET status = 'declined', updated_at = NOW() WHERE id = '$collab_id'");
        if ($update) {
            $success_msg = "Collaboration declined.";
            $collab['status'] = 'declined';
        } else {
            $error_msg = "Error declining collaboration.";
        }
    }
    
    if (isset($_POST['send_message'])) {
        $message = $conn->real_escape_string($_POST['message']);
        $receiver_id = ($collab['doctor_id'] == $doctor_id) ? $collab['invited_doctor_id'] : $collab['doctor_id'];
        $conn->query("INSERT INTO doctor_doctor_chat (sender_id, receiver_id, message, is_read) VALUES ('$doctor_id', '$receiver_id', '$message', 0)");
        $success_msg = "Message sent!";
    }
}

// Get chat messages for this collaboration
$other_doctor_id = ($collab['doctor_id'] == $doctor_id) ? $collab['invited_doctor_id'] : $collab['doctor_id'];
$messages = $conn->query("
    SELECT * FROM doctor_doctor_chat 
    WHERE (sender_id = '$doctor_id' AND receiver_id = '$other_doctor_id') 
       OR (sender_id = '$other_doctor_id' AND receiver_id = '$doctor_id')
    ORDER BY 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($collab['topic']) ?> | UHD Collaboration</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;
        }
        
        .detail-card {
            background: white;
            border-radius: 24px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            margin-bottom: 25px;
        }
        .detail-header {
            background: linear-gradient(135deg, var(--uhd-green), var(--uhd-dark));
            padding: 20px 25px;
            color: white;
        }
        .info-row {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 15px 0;
            border-bottom: 1px solid #e0e0e0;
        }
        .info-icon {
            width: 40px;
            height: 40px;
            background: #f8f9fa;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--uhd-gold);
        }
        .chat-message {
            background: #f8f9fa;
            border-radius: 18px;
            padding: 12px 18px;
            margin-bottom: 12px;
            max-width: 80%;
        }
        .chat-message.sent {
            background: var(--uhd-green);
            color: white;
            margin-left: auto;
        }
        .btn-gold {
            background: var(--uhd-gold);
            color: white;
            border-radius: 30px;
            padding: 8px 20px;
            font-weight: 500;
            border: none;
        }
        .btn-gold:hover {
            background: #b8860b;
            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; }
            .chat-message { max-width: 95%; }
        }
    </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-handshake fa-3x mb-2" style="color: var(--uhd-gold);"></i>
        <h4>Dr. <?= htmlspecialchars($doctor_name) ?></h4>
        <p>UHD Collaboration Hub</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="container-fluid">
        <!-- 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; ?>

        <!-- Collaboration Detail Card -->
        <div class="detail-card">
            <div class="detail-header">
                <h4 class="mb-0"><i class="fas fa-handshake me-2"></i> <?= htmlspecialchars($collab['topic']) ?></h4>
            </div>
            <div class="p-4">
                <div class="info-row">
                    <div class="info-icon"><i class="fas fa-user-md fa-lg"></i></div>
                    <div>
                        <strong>Initiated by:</strong> Dr. <?= htmlspecialchars($collab['requester_name']) ?>
                        <span class="text-muted">(<?= htmlspecialchars($collab['requester_spec']) ?>)</span>
                    </div>
                </div>
                
                <div class="info-row">
                    <div class="info-icon"><i class="fas fa-user-friends fa-lg"></i></div>
                    <div>
                        <strong>Collaborating with:</strong> Dr. <?= htmlspecialchars($collab['invitee_name']) ?>
                        <span class="text-muted">(<?= htmlspecialchars($collab['invitee_spec']) ?>)</span>
                    </div>
                </div>
                
                <div class="info-row">
                    <div class="info-icon"><i class="fas fa-tag fa-lg"></i></div>
                    <div>
                        <strong>Status:</strong> 
                        <span class="badge bg-<?= $collab['status'] == 'accepted' ? 'success' : ($collab['status'] == 'pending' ? 'warning' : 'secondary') ?> px-3 py-2">
                            <i class="fas fa-<?= $collab['status'] == 'accepted' ? 'check-circle' : ($collab['status'] == 'pending' ? 'hourglass-half' : 'times-circle') ?> me-1"></i>
                            <?= ucfirst($collab['status']) ?>
                        </span>
                    </div>
                </div>
                
                <div class="info-row">
                    <div class="info-icon"><i class="fas fa-calendar-alt fa-lg"></i></div>
                    <div>
                        <strong>Created:</strong> <?= date('l, F j, Y \a\t h:i A', strtotime($collab['created_at'])) ?>
                    </div>
                </div>
                
                <div class="mt-4 mb-4">
                    <h6 class="fw-bold"><i class="fas fa-align-left me-2" style="color: var(--uhd-gold);"></i> Description</h6>
                    <div class="p-3 bg-light rounded">
                        <?= nl2br(htmlspecialchars($collab['description'])) ?>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <?php if ($collab['status'] == 'pending' && $collab['invited_doctor_id'] == $doctor_id): ?>
                    <div class="d-flex gap-3 mb-4">
                        <form method="POST">
                            <button type="submit" name="accept_collaboration" class="btn btn-success px-4 py-2">
                                <i class="fas fa-check-circle me-2"></i> Accept Collaboration
                            </button>
                        </form>
                        <form method="POST">
                            <button type="submit" name="decline_collaboration" class="btn btn-danger px-4 py-2">
                                <i class="fas fa-times-circle me-2"></i> Decline
                            </button>
                        </form>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Chat Section (if accepted) -->
        <?php if ($collab['status'] == 'accepted'): ?>
        <div class="detail-card">
            <div class="detail-header">
                <h5 class="mb-0"><i class="fas fa-comments me-2"></i> Collaboration Chat</h5>
            </div>
            <div class="p-4">
                <div class="chat-container mb-4" style="max-height: 400px; overflow-y: auto;">
                    <?php if ($messages && $messages->num_rows > 0): ?>
                        <?php while ($msg = $messages->fetch_assoc()): ?>
                            <div class="chat-message <?= $msg['sender_id'] == $doctor_id ? 'sent' : 'received' ?>">
                                <small class="d-block fw-bold mb-1">
                                    <?= $msg['sender_id'] == $doctor_id ? 'You' : 'Dr. ' . ($msg['sender_id'] == $collab['doctor_id'] ? $collab['requester_name'] : $collab['invitee_name']) ?>
                                </small>
                                <?= nl2br(htmlspecialchars($msg['message'])) ?>
                                <small class="d-block mt-1 opacity-50" style="font-size: 0.65rem;">
                                    <?= date('h:i A', strtotime($msg['created_at'])) ?>
                                </small>
                            </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <p class="text-muted text-center py-4">No messages yet. Start the conversation!</p>
                    <?php endif; ?>
                </div>
                
                <form method="POST">
                    <div class="input-group">
                        <textarea name="message" class="form-control" rows="2" placeholder="Type your message..." required></textarea>
                        <button type="submit" name="send_message" class="btn btn-gold">
                            <i class="fas fa-paper-plane"></i> Send
                        </button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Back Button -->
        <div class="mt-3">
            <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>
    </div>
</div>

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