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

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

// Only admin roles can manage ICD-10 codes
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'MEDICAL_RECORDS'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Handle Delete
if (isset($_GET['delete'])) {
    $icd10_id = (int)$_GET['delete'];
    $delete_sql = "DELETE FROM icd10_codes WHERE icd10_id = ?";
    $stmt = $conn->prepare($delete_sql);
    $stmt->bind_param('i', $icd10_id);
    if ($stmt->execute()) {
        $_SESSION['success_message'] = 'ICD-10 code deleted successfully';
    } else {
        $_SESSION['error_message'] = 'Error deleting ICD-10 code';
    }
    header('Location: manage_icd10_codes.php');
    exit();
}

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_codes,
                SUM(CASE WHEN is_ent_related = 1 THEN 1 ELSE 0 END) as ent_codes,
                SUM(CASE WHEN commonly_used = 1 THEN 1 ELSE 0 END) as common_codes,
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_codes
              FROM icd10_codes";
$stats = $conn->query($stats_sql)->fetch_assoc();

// Fetch ICD-10 codes with pagination and search
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$category_filter = isset($_GET['category']) ? $_GET['category'] : '';
$ent_filter = isset($_GET['ent_only']) ? 1 : 0;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

$where_clauses = ['1=1'];
$params = [];
$types = '';

if (!empty($search)) {
    $where_clauses[] = "(code LIKE ? OR short_description LIKE ? OR full_description LIKE ?)";
    $search_param = "%{$search}%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
    $types .= 'sss';
}

if (!empty($category_filter)) {
    $where_clauses[] = "category = ?";
    $params[] = $category_filter;
    $types .= 's';
}

if ($ent_filter) {
    $where_clauses[] = "is_ent_related = 1";
}

$where_sql = implode(' AND ', $where_clauses);

// Count total
$count_sql = "SELECT COUNT(*) as total FROM icd10_codes WHERE $where_sql";
$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 / $per_page);

// Fetch codes
$sql = "SELECT * FROM icd10_codes WHERE $where_sql ORDER BY commonly_used DESC, code ASC LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;
$types .= 'ii';

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$codes_result = $stmt->get_result();

// Get categories for filter
$categories_sql = "SELECT DISTINCT category FROM icd10_codes WHERE category IS NOT NULL ORDER BY category";
$categories_result = $conn->query($categories_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Manage ICD-10 Codes')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #3b82f6;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --info: #06b6d4;
        }

        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border-left: 4px solid var(--primary);
            transition: transform 0.2s;
        }

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

        .stats-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary);
        }

        .stats-label {
            color: #6b7280;
            font-size: 0.875rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

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

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

        .table-card-header {
            padding: 1.5rem;
            border-bottom: 2px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .code-badge {
            display: inline-block;
            background: linear-gradient(135deg, var(--primary), #2563eb);
            color: white;
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 600;
            font-family: monospace;
            font-size: 0.875rem;
        }

        .category-badge {
            display: inline-block;
            background: #f3f4f6;
            color: #374151;
            padding: 0.25rem 0.625rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
        }

        .ent-badge {
            background: #dcfce7;
            color: #166534;
            padding: 0.25rem 0.625rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .common-badge {
            background: #fef3c7;
            color: #92400e;
            padding: 0.25rem 0.625rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
        }

        .table-hover tbody tr:hover {
            background: #f9fafb;
        }

        .action-btn {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            transition: all 0.2s;
        }

        .btn-edit {
            background: #dbeafe;
            color: #1e40af;
            border: none;
        }

        .btn-edit:hover {
            background: #bfdbfe;
        }

        .btn-delete {
            background: #fee2e2;
            color: #991b1b;
            border: none;
        }

        .btn-delete:hover {
            background: #fecaca;
        }

        .pagination {
            margin-top: 1.5rem;
        }

        .page-link {
            border-radius: 6px;
            margin: 0 0.25rem;
        }

        .import-section {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 1.5rem;
            border-left: 4px solid var(--info);
        }
    </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="row mb-4">
                        <div class="col-12">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h4 class="mb-1">
                                        <i class="ri-file-list-3-line me-2"></i>
                                        ICD-10 Code Management
                                    </h4>
                                    <p class="text-muted mb-0">Manage diagnosis codes for insurance claims and medical records</p>
                                </div>
                                <div class="d-flex gap-2">
                                    <a href="import_icd10_codes.php" class="btn btn-info">
                                        <i class="ri-upload-2-line me-1"></i> Import Codes
                                    </a>
                                    <a href="add_icd10_code.php" class="btn btn-primary">
                                        <i class="ri-add-line me-1"></i> Add Code
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['success_message'])): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <i class="ri-checkbox-circle-line me-2"></i>
                        <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="ri-error-warning-line me-2"></i>
                        <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo number_format($stats['total_codes']); ?></div>
                                <div class="stats-label">Total Codes</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card" style="border-color: var(--success);">
                                <div class="stats-number" style="color: var(--success);">
                                    <?php echo number_format($stats['ent_codes']); ?>
                                </div>
                                <div class="stats-label">ENT Specific</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card" style="border-color: var(--warning);">
                                <div class="stats-number" style="color: var(--warning);">
                                    <?php echo number_format($stats['common_codes']); ?>
                                </div>
                                <div class="stats-label">Commonly Used</div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="stats-card" style="border-color: var(--info);">
                                <div class="stats-number" style="color: var(--info);">
                                    <?php echo number_format($stats['active_codes']); ?>
                                </div>
                                <div class="stats-label">Active</div>
                            </div>
                        </div>
                    </div>

                    <!-- Search and Filter Section -->
                    <div class="search-section">
                        <form method="GET" class="row g-3">
                            <div class="col-md-5">
                                <label class="form-label">Search Codes</label>
                                <input type="text" class="form-control" name="search" 
                                       value="<?php echo htmlspecialchars($search); ?>"
                                       placeholder="Search by code, description...">
                            </div>
                            <div class="col-md-3">
                                <label class="form-label">Category</label>
                                <select class="form-select" name="category">
                                    <option value="">All Categories</option>
                                    <?php while ($cat = $categories_result->fetch_assoc()): ?>
                                    <option value="<?php echo $cat['category']; ?>" 
                                            <?php echo $category_filter == $cat['category'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($cat['category']); ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="ent_only" 
                                           <?php echo $ent_filter ? 'checked' : ''; ?>>
                                    <label class="form-check-label">ENT Only</label>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">&nbsp;</label>
                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary w-100">
                                        <i class="ri-search-line"></i> Search
                                    </button>
                                    <a href="manage_icd10_codes.php" class="btn btn-secondary">
                                        <i class="ri-refresh-line"></i>
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- ICD-10 Codes Table -->
                    <div class="table-card">
                        <div class="table-card-header">
                            <h5 class="mb-0">ICD-10 Codes (<?php echo number_format($total_records); ?>)</h5>
                            <span class="text-muted">Page <?php echo $page; ?> of <?php echo $total_pages; ?></span>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead style="background: #f9fafb;">
                                    <tr>
                                        <th style="width: 10%;">Code</th>
                                        <th style="width: 35%;">Description</th>
                                        <th style="width: 15%;">Category</th>
                                        <th style="width: 10%;" class="text-center">Tags</th>
                                        <th style="width: 10%;" class="text-center">Status</th>
                                        <th style="width: 20%;" class="text-center">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($codes_result->num_rows > 0): ?>
                                        <?php while ($code = $codes_result->fetch_assoc()): ?>
                                        <tr>
                                            <td>
                                                <span class="code-badge"><?php echo htmlspecialchars($code['code']); ?></span>
                                            </td>
                                            <td>
                                                <div class="fw-semibold"><?php echo htmlspecialchars($code['short_description']); ?></div>
                                                <?php if (!empty($code['full_description'])): ?>
                                                <small class="text-muted"><?php echo substr(htmlspecialchars($code['full_description']), 0, 80); ?>...</small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($code['category']): ?>
                                                <span class="category-badge"><?php echo htmlspecialchars($code['category']); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($code['is_ent_related']): ?>
                                                <span class="ent-badge">ENT</span>
                                                <?php endif; ?>
                                                <?php if ($code['commonly_used']): ?>
                                                <span class="common-badge">Common</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <?php if ($code['is_active']): ?>
                                                <span class="badge bg-success">Active</span>
                                                <?php else: ?>
                                                <span class="badge bg-secondary">Inactive</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-center">
                                                <div class="d-flex gap-1 justify-content-center">
                                                    <a href="edit_icd10_code.php?id=<?php echo $code['icd10_id']; ?>" 
                                                       class="action-btn btn-edit" title="Edit">
                                                        <i class="ri-edit-line"></i>
                                                    </a>
                                                    <button onclick="deleteCode(<?php echo $code['icd10_id']; ?>)" 
                                                            class="action-btn btn-delete" title="Delete">
                                                        <i class="ri-delete-bin-line"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="6" class="text-center py-5">
                                                <i class="ri-inbox-line" style="font-size: 3rem; opacity: 0.3;"></i>
                                                <div class="mt-2 text-muted">No ICD-10 codes found</div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <div class="px-4 pb-4">
                            <nav>
                                <ul class="pagination justify-content-center mb-0">
                                    <?php if ($page > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?><?php echo $ent_filter ? '&ent_only=1' : ''; ?>">
                                            <i class="ri-arrow-left-s-line"></i>
                                        </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; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?><?php echo $ent_filter ? '&ent_only=1' : ''; ?>">
                                            <?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; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?><?php echo $ent_filter ? '&ent_only=1' : ''; ?>">
                                            <i class="ri-arrow-right-s-line"></i>
                                        </a>
                                    </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        </div>
                        <?php endif; ?>
                    </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    function deleteCode(id) {
        Swal.fire({
            title: 'Delete ICD-10 Code?',
            text: 'This action cannot be undone. Are you sure?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#6b7280',
            confirmButtonText: 'Yes, delete it',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'manage_icd10_codes.php?delete=' + id;
            }
        });
    }
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>