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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'FINANCE_MANAGER', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];

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

// Filters
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$status = isset($_GET['status']) ? $_GET['status'] : '';
$smart_filter = isset($_GET['smart_filter']) ? $_GET['smart_filter'] : '';

// Build query
$where_clauses = [];
$params = [];
$types = '';

if (!empty($search)) {
    $where_clauses[] = "(provider_name LIKE ? OR provider_code LIKE ? OR contact_person LIKE ? OR email LIKE ?)";
    $search_param = "%{$search}%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
    $types .= 'ssss';
}

if ($status !== '') {
    $where_clauses[] = "is_active = ?";
    $params[] = (int)$status;
    $types .= 'i';
}

if ($smart_filter !== '') {
    $where_clauses[] = "smart_enabled = ?";
    $params[] = (int)$smart_filter;
    $types .= 'i';
}

$where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

// Count total records
$count_sql = "SELECT COUNT(*) as total FROM insurance_providers {$where_sql}";

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

$total_pages = ceil($total_records / $records_per_page);

// Fetch providers
$providers_sql = "SELECT 
                    provider_id, provider_name, provider_code, contact_person,
                    phone, email, address, coverage_percentage, copay_percentage,
                    claim_processing_days, is_active, smart_enabled, created_at,
                    (SELECT COUNT(*) FROM patients WHERE insurance_provider_id = insurance_providers.provider_id) as patient_count
                FROM insurance_providers
                {$where_sql}
                ORDER BY provider_name ASC
                LIMIT ? OFFSET ?";

$params[] = $records_per_page;
$params[] = $offset;
$types .= 'ii';

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

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_providers,
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_providers,
                SUM(CASE WHEN smart_enabled = 1 THEN 1 ELSE 0 END) as smart_providers,
                AVG(coverage_percentage) as avg_coverage
              FROM insurance_providers";
$stats = $conn->query($stats_sql)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Insurance Providers')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .stats-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.3s;
        }
        
        .stats-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stats-icon {
            width: 48px;
            height: 48px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .stats-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .stats-label {
            color: #64748b;
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .filter-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
        }
        
        .custom-table {
            width: 100%;
            margin: 0;
        }
        
        .custom-table thead th {
            background: #f8fafc;
            border-bottom: 2px solid #e2e8f0;
            color: #475569;
            font-weight: 600;
            font-size: 0.875rem;
            text-transform: uppercase;
            padding: 1rem;
        }
        
        .custom-table tbody td {
            padding: 1rem;
            vertical-align: middle;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .custom-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .provider-logo {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: white;
            font-size: 0.875rem;
        }
        
        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-weight: 500;
            font-size: 0.75rem;
            text-transform: uppercase;
        }
        
        .badge-active {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-inactive {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .badge-smart {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .action-btn {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            text-decoration: none;
        }
        
        .btn-view {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .btn-view:hover {
            background: #bfdbfe;
            color: #1e40af;
        }
        
        .btn-edit {
            background: #fef3c7;
            color: #92400e;
        }
        
        .btn-edit:hover {
            background: #fde68a;
            color: #92400e;
        }
        
        .btn-toggle {
            background: #e0e7ff;
            color: #3730a3;
        }
        
        .btn-toggle:hover {
            background: #c7d2fe;
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem;
            color: #64748b;
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #cbd5e1;
            margin-bottom: 1rem;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Insurance Providers</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Insurance Providers</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="stats-icon" style="background: #dbeafe;">
                                        <i class="ri-shield-check-line" style="color: #1e40af;"></i>
                                    </div>
                                    <div class="ms-3 flex-grow-1">
                                        <div class="stats-value"><?php echo number_format($stats['total_providers']); ?></div>
                                        <div class="stats-label">Total Providers</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="stats-icon" style="background: #d1fae5;">
                                        <i class="ri-check-double-line" style="color: #065f46;"></i>
                                    </div>
                                    <div class="ms-3 flex-grow-1">
                                        <div class="stats-value"><?php echo number_format($stats['active_providers']); ?></div>
                                        <div class="stats-label">Active Providers</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="stats-icon" style="background: #e0e7ff;">
                                        <i class="ri-flashlight-line" style="color: #3730a3;"></i>
                                    </div>
                                    <div class="ms-3 flex-grow-1">
                                        <div class="stats-value"><?php echo number_format($stats['smart_providers']); ?></div>
                                        <div class="stats-label">SMART Enabled</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="stats-icon" style="background: #fef3c7;">
                                        <i class="ri-percent-line" style="color: #92400e;"></i>
                                    </div>
                                    <div class="ms-3 flex-grow-1">
                                        <div class="stats-value"><?php echo number_format($stats['avg_coverage'], 1); ?>%</div>
                                        <div class="stats-label">Avg Coverage</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="filter-card">
                        <form method="GET" id="filterForm">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Search</label>
                                    <input type="text" class="form-control" name="search" 
                                           value="<?php echo htmlspecialchars($search); ?>" 
                                           placeholder="Provider name, code, contact, email...">
                                </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="1" <?php echo $status === '1' ? 'selected' : ''; ?>>Active</option>
                                        <option value="0" <?php echo $status === '0' ? 'selected' : ''; ?>>Inactive</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">SMART Status</label>
                                    <select class="form-select" name="smart_filter">
                                        <option value="">All Providers</option>
                                        <option value="1" <?php echo $smart_filter === '1' ? 'selected' : ''; ?>>SMART Enabled</option>
                                        <option value="0" <?php echo $smart_filter === '0' ? 'selected' : ''; ?>>Non-SMART</option>
                                    </select>
                                </div>
                                <div class="col-md-4 d-flex align-items-end gap-2">
                                    <button type="submit" class="btn btn-primary flex-grow-1">
                                        <i class="ri-search-line me-1"></i> Search
                                    </button>
                                    <a href="list_insurance_providers.php" class="btn btn-secondary">
                                        <i class="ri-refresh-line"></i>
                                    </a>
                                    <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])): ?>
                                    <a href="add_insurance_provider.php" class="btn btn-success">
                                        <i class="ri-add-line me-1"></i> Add Provider
                                    </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Providers Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h5 class="mb-0">
                                <i class="ri-shield-check-line me-2"></i>
                                Insurance Providers
                                <?php if ($total_records > 0): ?>
                                    <span class="text-muted" style="font-size: 0.875rem; font-weight: 400;">
                                        (<?php echo number_format($total_records); ?> providers)
                                    </span>
                                <?php endif; ?>
                            </h5>
                        </div>
                        
                        <div class="table-responsive">
                            <?php if ($providers_result->num_rows > 0): ?>
                            <table class="custom-table">
                                <thead>
                                    <tr>
                                        <th>Provider</th>
                                        <th>Code</th>
                                        <th>Contact</th>
                                        <th>Coverage</th>
                                        <th>Copay</th>
                                        <th>Processing</th>
                                        <th>Patients</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($provider = $providers_result->fetch_assoc()): 
                                        $initials = strtoupper(substr($provider['provider_name'], 0, 2));
                                        $colors = ['#3b82f6', '#ef4444', '#10b981', '#f59e0b', '#8b5cf6', '#ec4899'];
                                        $color = $colors[ord($initials[0]) % count($colors)];
                                    ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="provider-logo" style="background: <?php echo $color; ?>;">
                                                    <?php echo $initials; ?>
                                                </div>
                                                <div class="ms-3">
                                                    <div style="font-weight: 600; color: #1e293b;">
                                                        <?php echo htmlspecialchars($provider['provider_name']); ?>
                                                    </div>
                                                    <?php if ($provider['smart_enabled']): ?>
                                                    <span class="badge badge-smart mt-1">
                                                        <i class="ri-flashlight-line me-1"></i>SMART
                                                    </span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span style="font-family: monospace; font-weight: 600; color: #3b82f6;">
                                                <?php echo htmlspecialchars($provider['provider_code']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div style="font-size: 0.875rem;">
                                                <?php if ($provider['contact_person']): ?>
                                                <div style="font-weight: 600;"><?php echo htmlspecialchars($provider['contact_person']); ?></div>
                                                <?php endif; ?>
                                                <?php if ($provider['phone']): ?>
                                                <div class="text-muted"><i class="ri-phone-line me-1"></i><?php echo htmlspecialchars($provider['phone']); ?></div>
                                                <?php endif; ?>
                                                <?php if ($provider['email']): ?>
                                                <div class="text-muted"><i class="ri-mail-line me-1"></i><?php echo htmlspecialchars($provider['email']); ?></div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600; color: #10b981;">
                                                <?php echo number_format($provider['coverage_percentage'], 1); ?>%
                                            </span>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600; color: #f59e0b;">
                                                <?php echo number_format($provider['copay_percentage'], 1); ?>%
                                            </span>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600;">
                                                <?php echo $provider['claim_processing_days']; ?> days
                                            </span>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600; color: #3b82f6;">
                                                <?php echo number_format($provider['patient_count']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge <?php echo $provider['is_active'] ? 'badge-active' : 'badge-inactive'; ?>">
                                                <?php echo $provider['is_active'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="d-flex gap-1">
                                                <a href="view_insurance_provider.php?id=<?php echo $provider['provider_id']; ?>" 
                                                   class="action-btn btn-view" title="View Details">
                                                    <i class="ri-eye-line"></i>
                                                </a>
                                                <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])): ?>
                                                <a href="edit_insurance_provider.php?id=<?php echo $provider['provider_id']; ?>" 
                                                   class="action-btn btn-edit" title="Edit">
                                                    <i class="ri-edit-line"></i>
                                                </a>
                                                <button onclick="toggleStatus(<?php echo $provider['provider_id']; ?>, <?php echo $provider['is_active']; ?>)" 
                                                        class="action-btn btn-toggle" title="Toggle Status">
                                                    <i class="ri-toggle-line"></i>
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                            <?php else: ?>
                            <div class="empty-state">
                                <i class="ri-shield-check-line"></i>
                                <h5>No Insurance Providers Found</h5>
                                <p class="text-muted">
                                    <?php if (!empty($search) || $status !== '' || $smart_filter !== ''): ?>
                                        No providers match your search criteria.
                                    <?php else: ?>
                                        No insurance providers have been added yet.
                                    <?php endif; ?>
                                </p>
                                <?php if (in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])): ?>
                                <a href="add_insurance_provider.php" class="btn btn-primary mt-3">
                                    <i class="ri-add-line me-1"></i> Add First Provider
                                </a>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($total_pages > 1): ?>
                        <div style="padding: 1.5rem; border-top: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center;">
                            <div style="color: #64748b; font-size: 0.875rem;">
                                Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $records_per_page, $total_records); ?> of <?php echo number_format($total_records); ?>
                            </div>
                            <div style="display: flex; gap: 0.5rem;">
                                <?php if ($page > 1): ?>
                                <a href="?page=<?php echo $page - 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo $status !== '' ? '&status=' . $status : ''; ?><?php echo $smart_filter !== '' ? '&smart_filter=' . $smart_filter : ''; ?>" 
                                   class="btn btn-sm btn-secondary">
                                    <i class="ri-arrow-left-s-line"></i> Previous
                                </a>
                                <?php endif; ?>
                                
                                <?php if ($page < $total_pages): ?>
                                <a href="?page=<?php echo $page + 1; ?><?php echo !empty($search) ? '&search=' . urlencode($search) : ''; ?><?php echo $status !== '' ? '&status=' . $status : ''; ?><?php echo $smart_filter !== '' ? '&smart_filter=' . $smart_filter : ''; ?>" 
                                   class="btn btn-sm btn-secondary">
                                    Next <i class="ri-arrow-right-s-line"></i>
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    function toggleStatus(providerId, currentStatus) {
        const newStatus = currentStatus ? 0 : 1;
        const statusText = newStatus ? 'activate' : 'deactivate';
        
        Swal.fire({
            title: 'Confirm Action',
            text: `Are you sure you want to ${statusText} this insurance provider?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: `Yes, ${statusText} it!`
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('ajax/toggle_provider_status.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        provider_id: providerId,
                        status: newStatus
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: 'Provider status updated successfully',
                            timer: 1500
                        }).then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error', data.message || 'Failed to update status', 'error');
                    }
                })
                .catch(error => {
                    Swal.fire('Error', 'An error occurred', 'error');
                });
            }
        });
    }
    </script>

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