<?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'];

// Get filter from URL
$filter = isset($_GET['filter']) ? $_GET['filter'] : 'all';

// Build query based on filter
$status_condition = '';
if ($filter == 'pending') {
    $status_condition = "AND c.status = 'scheduled'";
} elseif ($filter == 'ongoing') {
    $status_condition = "AND c.status = 'ongoing'";
} elseif ($filter == 'completed') {
    $status_condition = "AND c.status = 'completed'";
} else {
    $status_condition = "";
}

// Get consultations based on filter
$consultations = $conn->query("
    SELECT c.*, CONCAT(p.first_name, ' ', p.last_name) as patient_name, p.patient_id, p.email, p.phone
    FROM consultations c
    JOIN patients p ON c.patient_id = p.patient_id
    WHERE c.doctor_id = '$doctor_id' $status_condition
    ORDER BY FIELD(c.status, 'ongoing', 'scheduled', 'completed', 'cancelled'), c.scheduled_time DESC
");

// Get counts for filter badges
$pending_count = $conn->query("SELECT COUNT(*) as cnt FROM consultations WHERE doctor_id = '$doctor_id' AND status = 'scheduled'")->fetch_assoc()['cnt'] ?? 0;
$ongoing_count = $conn->query("SELECT COUNT(*) as cnt FROM consultations WHERE doctor_id = '$doctor_id' AND status = 'ongoing'")->fetch_assoc()['cnt'] ?? 0;
$completed_count = $conn->query("SELECT COUNT(*) as cnt FROM consultations WHERE doctor_id = '$doctor_id' AND status = 'completed'")->fetch_assoc()['cnt'] ?? 0;
$cancelled_count = $conn->query("SELECT COUNT(*) as cnt FROM consultations WHERE doctor_id = '$doctor_id' AND status = 'cancelled'")->fetch_assoc()['cnt'] ?? 0;

$page_title = 'Consultations | UHD';
include '../include/header.php';
?>

<style>
    .consultation-card {
        background: white;
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 15px;
        border-left: 5px solid;
        box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        transition: all 0.2s;
    }
    .consultation-card:hover {
        transform: translateX(5px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    .consultation-scheduled { border-left-color: #ffc107; background: #fffbf0; }
    .consultation-ongoing { border-left-color: #dc3545; background: #fff5f5; animation: pulse 1.5s infinite; }
    .consultation-completed { border-left-color: #28a745; background: #f0fff4; }
    .consultation-cancelled { border-left-color: #6c757d; background: #f8f9fa; }
    
    @keyframes pulse {
        0% { box-shadow: 0 0 0 0 rgba(220,53,69,0.2); }
        70% { box-shadow: 0 0 0 8px rgba(220,53,69,0); }
        100% { box-shadow: 0 0 0 0 rgba(220,53,69,0); }
    }
    
    .filter-btn {
        padding: 8px 20px;
        border-radius: 30px;
        background: #f0f0f0;
        color: #333;
        text-decoration: none;
        transition: 0.2s;
        display: inline-block;
    }
    .filter-btn.active {
        background: #d4a017;
        color: white;
    }
    .filter-btn:hover:not(.active) {
        background: #e0e0e0;
    }
    .badge-count {
        background: #dc3545;
        color: white;
        border-radius: 20px;
        padding: 2px 8px;
        font-size: 0.7rem;
        margin-left: 5px;
    }
    .btn-sm-action {
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 0.75rem;
    }
</style>

<div class="container mt-4">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fas fa-video me-2" style="color: #d4a017;"></i> My Consultations</h2>
        <a href="schedule_consultation.php" class="btn btn-success rounded-pill">
            <i class="fas fa-plus"></i> Schedule Consultation
        </a>
    </div>

    <!-- Filter Buttons -->
    <div class="mb-4">
        <a href="consultations.php?filter=all" class="filter-btn <?= $filter == 'all' ? 'active' : '' ?> me-2">
            All <span class="badge bg-secondary text-white ms-1"><?= $pending_count + $ongoing_count + $completed_count + $cancelled_count ?></span>
        </a>
        <a href="consultations.php?filter=pending" class="filter-btn <?= $filter == 'pending' ? 'active' : '' ?> me-2">
            Pending <span class="badge-count"><?= $pending_count ?></span>
        </a>
        <a href="consultations.php?filter=ongoing" class="filter-btn <?= $filter == 'ongoing' ? 'active' : '' ?> me-2">
            Ongoing <span class="badge-count"><?= $ongoing_count ?></span>
        </a>
        <a href="consultations.php?filter=completed" class="filter-btn <?= $filter == 'completed' ? 'active' : '' ?> me-2">
            Completed <span class="badge bg-success text-white ms-1"><?= $completed_count ?></span>
        </a>
        <a href="consultations.php?filter=cancelled" class="filter-btn <?= $filter == 'cancelled' ? 'active' : '' ?>">
            Cancelled <span class="badge bg-secondary text-white ms-1"><?= $cancelled_count ?></span>
        </a>
    </div>

    <!-- Back to Dashboard -->
    <div class="mb-3">
        <a href="dashboard.php" class="btn btn-secondary btn-sm rounded-pill">
            <i class="fas fa-arrow-left"></i> Back to Dashboard
        </a>
    </div>

    <!-- Consultations List -->
    <?php if ($consultations && $consultations->num_rows > 0): ?>
        <?php while ($c = $consultations->fetch_assoc()): 
            $status_class = '';
            $status_text = '';
            if ($c['status'] == 'scheduled') {
                $status_class = 'consultation-scheduled';
                $status_text = 'Pending';
            } elseif ($c['status'] == 'ongoing') {
                $status_class = 'consultation-ongoing';
                $status_text = 'Ongoing';
            } elseif ($c['status'] == 'completed') {
                $status_class = 'consultation-completed';
                $status_text = 'Completed';
            } else {
                $status_class = 'consultation-cancelled';
                $status_text = 'Cancelled';
            }
        ?>
            <div class="consultation-card <?= $status_class ?>">
                <div class="row align-items-center">
                    <div class="col-md-3">
                        <strong><i class="fas fa-user me-2"></i><?= htmlspecialchars($c['patient_name']) ?></strong>
                        <br>
                        <small class="text-muted">ID: <?= htmlspecialchars($c['patient_id']) ?></small>
                    </div>
                    <div class="col-md-3">
                        <i class="fas fa-calendar-alt me-1 text-muted"></i> <?= date('M d, Y', strtotime($c['scheduled_time'])) ?>
                        <br>
                        <i class="fas fa-clock me-1 text-muted"></i> <?= date('h:i A', strtotime($c['scheduled_time'])) ?>
                    </div>
                    <div class="col-md-3">
                        <span class="badge bg-<?= $c['status'] == 'ongoing' ? 'danger' : ($c['status'] == 'scheduled' ? 'warning' : ($c['status'] == 'completed' ? 'success' : 'secondary')) ?>">
                            <?= $status_text ?>
                        </span>
                        <?php if ($c['reason']): ?>
                            <br><small class="text-muted"><?= htmlspecialchars(substr($c['reason'], 0, 40)) ?>...</small>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 text-end">
                        <?php if ($c['status'] == 'scheduled'): ?>
                            <form method="POST" action="dashboard.php" class="d-inline">
                                <input type="hidden" name="consult_id" value="<?= $c['id'] ?>">
                                <button type="submit" name="start_consultation" class="btn btn-danger btn-sm-action">
                                    <i class="fas fa-video"></i> Start
                                </button>
                            </form>
                            <form method="POST" action="dashboard.php" class="d-inline" onsubmit="return confirm('Cancel this consultation?')">
                                <input type="hidden" name="consult_id" value="<?= $c['id'] ?>">
                                <button type="submit" name="cancel_consultation" class="btn btn-secondary btn-sm-action">
                                    <i class="fas fa-times"></i>
                                </button>
                            </form>
                        <?php elseif ($c['status'] == 'ongoing' && $c['meeting_link']): ?>
                            <a href="<?= $c['meeting_link'] ?>" target="_blank" class="btn btn-danger btn-sm-action">
                                <i class="fas fa-video"></i> Join
                            </a>
                            <button class="btn btn-outline-secondary btn-sm-action" onclick="copyLink('<?= htmlspecialchars($c['meeting_link']) ?>')">
                                <i class="fas fa-copy"></i>
                            </button>
                            <button class="btn btn-success btn-sm-action" data-bs-toggle="modal" data-bs-target="#completeModal<?= $c['id'] ?>">
                                <i class="fas fa-check"></i> Complete
                            </button>
                        <?php elseif ($c['status'] == 'completed'): ?>
                            <a href="consultation_details.php?id=<?= $c['id'] ?>" class="btn btn-info btn-sm-action">
                                <i class="fas fa-eye"></i> Details
                            </a>
                        <?php endif; ?>
                        
                        <a href="consultation_details.php?id=<?= $c['id'] ?>" class="btn btn-outline-info btn-sm-action">
                            <i class="fas fa-info-circle"></i>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Complete Modal -->
            <?php if ($c['status'] == 'ongoing'): ?>
            <div class="modal fade" id="completeModal<?= $c['id'] ?>" tabindex="-1">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header bg-success text-white">
                            <h5 class="modal-title"><i class="fas fa-notes-medical me-2"></i> Complete Consultation</h5>
                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                        </div>
                        <form method="POST" action="dashboard.php">
                            <div class="modal-body">
                                <p><strong>Patient:</strong> <?= htmlspecialchars($c['patient_name']) ?></p>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Consultation Notes</label>
                                    <textarea name="notes" class="form-control" rows="3" placeholder="Diagnosis, observations, recommendations..." required></textarea>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Prescription</label>
                                    <textarea name="prescription" class="form-control" rows="2" placeholder="Medication, dosage, duration..."></textarea>
                                </div>
                                <input type="hidden" name="consult_id" value="<?= $c['id'] ?>">
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                <button type="submit" name="complete_consultation" class="btn btn-success">Save & Complete</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        <?php endwhile; ?>
    <?php else: ?>
        <div class="alert alert-info text-center py-5">
            <i class="fas fa-inbox fa-3x mb-3"></i>
            <h5>No consultations found</h5>
            <p class="mb-0">Schedule your first consultation to get started.</p>
            <a href="schedule_consultation.php" class="btn btn-success mt-3 rounded-pill">
                <i class="fas fa-plus"></i> Schedule Consultation
            </a>
        </div>
    <?php endif; ?>
</div>

<script>
function copyLink(link) {
    navigator.clipboard.writeText(link);
    alert('Meeting link copied to clipboard!');
}
</script>

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