<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'];

// Fetch filters
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$type_filter = isset($_GET['type']) ? $_GET['type'] : '';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$records_per_page = 15;
$offset = ($page - 1) * $records_per_page;

// Build query based on role
$where_conditions = ["1=1"];
$params = [];
$types = "";

// Role-based filtering
if ($role_code === 'ENT_CONSULTANT' || $role_code === 'ENT_SPECIALIST') {
    $where_conditions[] = "c.doctor_id = ?";
    $params[] = $user_id;
    $types .= "i";
}

// Status filter
if (!empty($status_filter)) {
    $where_conditions[] = "c.status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

// Type filter
if (!empty($type_filter)) {
    $where_conditions[] = "c.consultation_type = ?";
    $params[] = $type_filter;
    $types .= "s";
}

// Date range filter
if (!empty($date_from)) {
    $where_conditions[] = "DATE(c.started_at) >= ?";
    $params[] = $date_from;
    $types .= "s";
}
if (!empty($date_to)) {
    $where_conditions[] = "DATE(c.started_at) <= ?";
    $params[] = $date_to;
    $types .= "s";
}

// Search filter
if (!empty($search)) {
    $where_conditions[] = "(p.patient_number LIKE ? OR p.full_name LIKE ? OR c.consultation_number LIKE ? OR c.chief_complaint LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $types .= "ssss";
}

$where_clause = implode(" AND ", $where_conditions);

// Count total records
$count_sql = "SELECT COUNT(*) as total 
              FROM consultations c
              INNER JOIN patients p ON c.patient_id = p.patient_id
              INNER JOIN users d ON c.doctor_id = d.user_id
              WHERE $where_clause";

$count_stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $count_stmt->bind_param($types, ...$params);
}
$count_stmt->execute();
$total_records = $count_stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_records / $records_per_page);

// Fetch consultations
$sql = "SELECT 
            c.*,
            p.patient_number,
            d.full_name as patient_name,
            d.phone_primary as patient_phone,
            d.date_of_birth,
            d.full_name as doctor_name,
            v.visit_number,
            v.registration_type
        FROM consultations c
        INNER JOIN patients p ON c.patient_id = p.patient_id
        INNER JOIN users d ON c.doctor_id = d.user_id
        LEFT JOIN patient_visits v ON c.visit_id = v.visit_id
        WHERE $where_clause
        ORDER BY c.started_at DESC
        LIMIT ? OFFSET ?";

$stmt = $conn->prepare($sql);
$params[] = $records_per_page;
$params[] = $offset;
$types .= "ii";
$stmt->bind_param($types, ...$params);
$stmt->execute();
$consultations = $stmt->get_result();

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_consultations,
                SUM(CASE WHEN status = 'IN_PROGRESS' THEN 1 ELSE 0 END) as in_progress,
                SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed,
                SUM(CASE WHEN DATE(started_at) = CURDATE() THEN 1 ELSE 0 END) as today_consultations,
                SUM(consultation_fee) as total_revenue
              FROM consultations c
              WHERE " . (($role_code === 'ENT_CONSULTANT' || $role_code === 'ENT_SPECIALIST') ? "c.doctor_id = $user_id" : "1=1");
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'All Consultations')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #3b82f6;
            --primary-dark: #2563eb;
            --success-color: #10b981;
            --danger-color: #ef4444;
            --warning-color: #f59e0b;
            --info-color: #06b6d4;
            --gray-50: #f9fafb;
            --gray-100: #f3f4f6;
            --gray-200: #e5e7eb;
            --gray-600: #4b5563;
            --gray-700: #374151;
            --gray-900: #111827;
        }

        body {
            background: var(--gray-50);
            font-family: 'Inter', system-ui, sans-serif;
        }

        .page-header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            border-radius: 16px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .page-header h1 {
            color: white;
            font-size: 1.875rem;
            font-weight: 700;
            margin: 0 0 0.5rem 0;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .page-header p {
            color: rgba(255, 255, 255, 0.9);
            margin: 0;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid var(--gray-200);
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin-bottom: 1rem;
        }

        .stat-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: var(--gray-900);
            margin-bottom: 0.25rem;
        }

        .stat-label {
            font-size: 0.875rem;
            color: var(--gray-600);
            font-weight: 500;
        }

        .filters-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid var(--gray-200);
        }

        .table-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
            border: 1px solid var(--gray-200);
            overflow: hidden;
        }

        .table {
            margin: 0;
        }

        .table thead {
            background: var(--gray-50);
        }

        .table thead th {
            font-weight: 600;
            color: var(--gray-700);
            border-bottom: 2px solid var(--gray-200);
            padding: 1rem;
            font-size: 0.875rem;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .table tbody td {
            padding: 1rem;
            vertical-align: middle;
            color: var(--gray-700);
        }

        .table tbody tr {
            border-bottom: 1px solid var(--gray-200);
            transition: background 0.2s ease;
        }

        .table tbody tr:hover {
            background: var(--gray-50);
        }

        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.025em;
        }

        .badge-primary { background: #dbeafe; color: #1e40af; }
        .badge-success { background: #d1fae5; color: #065f46; }
        .badge-warning { background: #fef3c7; color: #92400e; }
        .badge-danger { background: #fee2e2; color: #991b1b; }
        .badge-info { background: #cffafe; color: #164e63; }

        .btn-action {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 500;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.375rem;
        }

        .btn-primary {
            background: var(--primary-color);
            color: white;
        }

        .btn-primary:hover {
            background: var(--primary-dark);
        }

        .btn-success {
            background: var(--success-color);
            color: white;
        }

        .btn-info {
            background: var(--info-color);
            color: white;
        }

        .patient-info {
            display: flex;
            flex-direction: column;
            gap: 0.25rem;
        }

        .patient-name {
            font-weight: 600;
            color: var(--gray-900);
        }

        .patient-details {
            font-size: 0.8125rem;
            color: var(--gray-600);
        }

        .pagination {
            margin: 1.5rem 0;
            justify-content: center;
        }

        .page-link {
            color: var(--primary-color);
            border: 1px solid var(--gray-200);
            padding: 0.5rem 0.75rem;
        }

        .page-link:hover {
            background: var(--primary-color);
            color: white;
            border-color: var(--primary-color);
        }

        .page-item.active .page-link {
            background: var(--primary-color);
            border-color: var(--primary-color);
        }

        @media (max-width: 768px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }

            .table-container {
                overflow-x: auto;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1>
                            <i class="ri-stethoscope-line"></i>
                            Consultations Management
                        </h1>
                        <p>View and manage all patient consultations</p>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #dbeafe; color: #1e40af;">
                                <i class="ri-file-list-3-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['total_consultations']); ?></div>
                            <div class="stat-label">Total Consultations</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #fef3c7; color: #92400e;">
                                <i class="ri-time-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['in_progress']); ?></div>
                            <div class="stat-label">In Progress</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #d1fae5; color: #065f46;">
                                <i class="ri-checkbox-circle-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['completed']); ?></div>
                            <div class="stat-label">Completed</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #e0e7ff; color: #3730a3;">
                                <i class="ri-calendar-check-line"></i>
                            </div>
                            <div class="stat-value"><?php echo number_format($stats['today_consultations']); ?></div>
                            <div class="stat-label">Today's Consultations</div>
                        </div>
                        <div class="stat-card">
                            <div class="stat-icon" style="background: #d1fae5; color: #065f46;">
                                <i class="ri-money-dollar-circle-line"></i>
                            </div>
                            <div class="stat-value">KES <?php echo number_format($stats['total_revenue'], 2); ?></div>
                            <div class="stat-label">Total Revenue</div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="filters-section">
                        <form method="GET" action="" class="row g-3">
                            <div class="col-md-3">
                                <label class="form-label">Search</label>
                                <input type="text" class="form-control" name="search" 
                                       value="<?php echo htmlspecialchars($search); ?>" 
                                       placeholder="Patient name, number, complaint...">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="">All Status</option>
                                    <option value="IN_PROGRESS" <?php echo $status_filter === 'IN_PROGRESS' ? 'selected' : ''; ?>>In Progress</option>
                                    <option value="COMPLETED" <?php echo $status_filter === 'COMPLETED' ? 'selected' : ''; ?>>Completed</option>
                                    <option value="CANCELLED" <?php echo $status_filter === 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Type</label>
                                <select class="form-select" name="type">
                                    <option value="">All Types</option>
                                    <option value="INITIAL" <?php echo $type_filter === 'INITIAL' ? 'selected' : ''; ?>>Initial</option>
                                    <option value="FOLLOW_UP" <?php echo $type_filter === 'FOLLOW_UP' ? 'selected' : ''; ?>>Follow-up</option>
                                    <option value="SECOND_OPINION" <?php echo $type_filter === 'SECOND_OPINION' ? 'selected' : ''; ?>>Second Opinion</option>
                                    <option value="EMERGENCY" <?php echo $type_filter === 'EMERGENCY' ? 'selected' : ''; ?>>Emergency</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">From Date</label>
                                <input type="date" class="form-control" name="date_from" 
                                       value="<?php echo htmlspecialchars($date_from); ?>">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">To Date</label>
                                <input type="date" class="form-control" name="date_to" 
                                       value="<?php echo htmlspecialchars($date_to); ?>">
                            </div>
                            <div class="col-md-1 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="ri-search-line"></i>
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- Consultations Table -->
                    <div class="table-container">
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Consultation #</th>
                                        <th>Patient</th>
                                        <th>Doctor</th>
                                        <th>Type</th>
                                        <th>Chief Complaint</th>
                                        <th>Date & Time</th>
                                        <th>Fee (KES)</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($consultations->num_rows > 0): ?>
                                        <?php while ($row = $consultations->fetch_assoc()): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($row['consultation_number']); ?></strong>
                                                    <?php if (!empty($row['visit_number'])): ?>
                                                        <br><small class="text-muted"><?php echo htmlspecialchars($row['visit_number']); ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <div class="patient-info">
                                                        <span class="patient-name"><?php echo htmlspecialchars($row['patient_name']); ?></span>
                                                        <span class="patient-details"><?php echo htmlspecialchars($row['patient_number']); ?></span>
                                                        <span class="patient-details"><?php echo htmlspecialchars($row['patient_phone']); ?></span>
                                                    </div>
                                                </td>
                                                <td><?php echo htmlspecialchars($row['doctor_name']); ?></td>
                                                <td>
                                                    <?php
                                                    $type_badges = [
                                                        'INITIAL' => 'badge-primary',
                                                        'FOLLOW_UP' => 'badge-info',
                                                        'SECOND_OPINION' => 'badge-warning',
                                                        'EMERGENCY' => 'badge-danger'
                                                    ];
                                                    $badge_class = $type_badges[$row['consultation_type']] ?? 'badge-secondary';
                                                    ?>
                                                    <span class="badge <?php echo $badge_class; ?>">
                                                        <?php echo str_replace('_', ' ', $row['consultation_type']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php 
                                                    $complaint = htmlspecialchars($row['chief_complaint']);
                                                    echo strlen($complaint) > 50 ? substr($complaint, 0, 50) . '...' : $complaint;
                                                    ?>
                                                </td>
                                                <td>
                                                    <?php echo date('d M Y', strtotime($row['started_at'])); ?><br>
                                                    <small class="text-muted"><?php echo date('h:i A', strtotime($row['started_at'])); ?></small>
                                                </td>
                                                <td><?php echo number_format($row['consultation_fee'], 2); ?></td>
                                                <td>
                                                    <?php
                                                    $status_badges = [
                                                        'IN_PROGRESS' => 'badge-warning',
                                                        'COMPLETED' => 'badge-success',
                                                        'CANCELLED' => 'badge-danger'
                                                    ];
                                                    $status_class = $status_badges[$row['status']] ?? 'badge-secondary';
                                                    ?>
                                                    <span class="badge <?php echo $status_class; ?>">
                                                        <?php echo str_replace('_', ' ', $row['status']); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="d-flex gap-2">
                                                        <a href="view_consultation.php?id=<?php echo $row['consultation_id']; ?>" 
                                                           class="btn btn-sm btn-info" title="View Details">
                                                            <i class="ri-eye-line"></i>
                                                        </a>
                                                        <?php if ($row['status'] === 'IN_PROGRESS'): ?>
                                                            <a href="new_consultation.php?id=<?php echo $row['consultation_id']; ?>" 
                                                               class="btn btn-sm btn-primary" title="Continue">
                                                                <i class="ri-edit-line"></i>
                                                            </a>
                                                        <?php endif; ?>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="9" class="text-center py-4">
                                                <i class="ri-inbox-line" style="font-size: 3rem; color: var(--gray-300);"></i>
                                                <p class="text-muted mt-2">No consultations found</p>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                            <nav>
                                <ul class="pagination">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                Previous
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                                        <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                            <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                <?php echo $i; ?>
                                            </a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if ($page < $total_pages): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page + 1; ?>&<?php echo http_build_query(array_filter($_GET, function($k) { return $k !== 'page'; }, ARRAY_FILTER_USE_KEY)); ?>">
                                                Next
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        <?php endif; ?>
                    </div>

                </div>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <?php if (isset($_SESSION['success_message'])): ?>
    <script>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $_SESSION['success_message']; ?>',
            confirmButtonColor: '#3b82f6'
        });
    </script>
    <?php unset($_SESSION['success_message']); endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
    <script>
        Swal.fire({
            icon: 'error',
            title: 'Error!',
            text: '<?php echo $_SESSION['error_message']; ?>',
            confirmButtonColor: '#ef4444'
        });
    </script>
    <?php unset($_SESSION['error_message']); endif; ?>
</body>
</html>