<?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', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'RECEPTIONIST'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

// Get filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$provider_filter = isset($_GET['provider']) ? (int)$_GET['provider'] : 0;
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

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

if ($status_filter) {
    $where_clauses[] = "pa.auth_status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

if ($provider_filter) {
    $where_clauses[] = "pa.provider_id = ?";
    $params[] = $provider_filter;
    $types .= 'i';
}

if ($date_from) {
    $where_clauses[] = "pa.request_date >= ?";
    $params[] = $date_from;
    $types .= 's';
}

if ($date_to) {
    $where_clauses[] = "pa.request_date <= ?";
    $params[] = $date_to;
    $types .= 's';
}

if ($search) {
    $where_clauses[] = "(pa.preauth_number LIKE ? OR u.full_name LIKE ? OR p.patient_number LIKE ?)";
    $search_term = "%{$search}%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $types .= 'sss';
}

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

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

// Count total records
$count_sql = "SELECT COUNT(*) as total
              FROM insurance_pre_authorizations pa
              INNER JOIN patients p ON pa.patient_id = p.patient_id
              INNER JOIN users u ON p.user_id = u.user_id
              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 / $records_per_page);

// Fetch pre-authorizations
$preauth_sql = "SELECT 
                    pa.*,
                    p.patient_number,
                    u.full_name as patient_name,
                    ip.provider_name,
                    doc.full_name as doctor_name,
                    DATEDIFF(pa.valid_until, CURDATE()) as days_until_expiry
                FROM insurance_pre_authorizations pa
                INNER JOIN patients p ON pa.patient_id = p.patient_id
                INNER JOIN users u ON p.user_id = u.user_id
                LEFT JOIN insurance_providers ip ON pa.provider_id = ip.provider_id
                LEFT JOIN users doc ON pa.requested_by = doc.user_id
                WHERE {$where_sql}
                ORDER BY pa.created_at DESC
                LIMIT ? OFFSET ?";

$stmt = $conn->prepare($preauth_sql);
$params[] = $records_per_page;
$params[] = $offset;
$types .= 'ii';
$stmt->bind_param($types, ...$params);
$stmt->execute();
$preauths = $stmt->get_result();

// Fetch insurance providers for filter
$providers_sql = "SELECT provider_id, provider_name FROM insurance_providers WHERE is_active = 1 ORDER BY provider_name";
$providers = $conn->query($providers_sql);

// Get statistics
$stats_sql = "SELECT 
                COUNT(*) as total_count,
                SUM(CASE WHEN auth_status = 'DRAFT' THEN 1 ELSE 0 END) as draft_count,
                SUM(CASE WHEN auth_status = 'SUBMITTED' THEN 1 ELSE 0 END) as submitted_count,
                SUM(CASE WHEN auth_status = 'PENDING' THEN 1 ELSE 0 END) as pending_count,
                SUM(CASE WHEN auth_status = 'APPROVED' THEN 1 ELSE 0 END) as approved_count,
                SUM(CASE WHEN auth_status = 'REJECTED' THEN 1 ELSE 0 END) as rejected_count,
                SUM(requested_amount) as total_requested,
                SUM(approved_amount) as total_approved
              FROM insurance_pre_authorizations";
$stats = $conn->query($stats_sql)->fetch_assoc();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pre-Authorizations')); ?>
    <?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: 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: #1e293b;
        }
        
        .stats-label {
            color: #64748b;
            font-size: 0.875rem;
            margin-top: 0.5rem;
        }
        
        .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;
        }
        
        .status-badge {
            display: inline-block;
            padding: 0.35rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .status-draft { background: #e0e7ff; color: #3730a3; }
        .status-submitted { background: #dbeafe; color: #1e40af; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-under_review { background: #fed7aa; color: #9a3412; }
        .status-approved { background: #d1fae5; color: #065f46; }
        .status-partially_approved { background: #a7f3d0; color: #064e3b; }
        .status-rejected { background: #fee2e2; color: #991b1b; }
        .status-expired { background: #f3f4f6; color: #4b5563; }
        .status-cancelled { background: #e5e7eb; color: #374151; }
        
        .urgency-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.7rem;
            font-weight: 600;
        }
        
        .urgency-routine { background: #e0f2fe; color: #075985; }
        .urgency-urgent { background: #fed7aa; color: #9a3412; }
        .urgency-emergency { background: #fee2e2; color: #991b1b; }
        
        .expiry-warning {
            color: #dc2626;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .expiry-soon {
            color: #f59e0b;
            font-size: 0.75rem;
            font-weight: 600;
        }
    </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 Title -->
                    <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">Pre-Authorizations</h4>
                                <div class="page-title-right">
                                    <a href="create_preauthorization.php" class="btn btn-primary">
                                        <i class="ri-add-line me-1"></i> New Pre-Authorization
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-2 col-md-4">
                            <div class="stats-card">
                                <div class="stats-number"><?php echo number_format($stats['total_count']); ?></div>
                                <div class="stats-label">Total Requests</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4">
                            <div class="stats-card">
                                <div class="stats-number text-warning"><?php echo number_format($stats['pending_count']); ?></div>
                                <div class="stats-label">Pending</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4">
                            <div class="stats-card">
                                <div class="stats-number text-success"><?php echo number_format($stats['approved_count']); ?></div>
                                <div class="stats-label">Approved</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4">
                            <div class="stats-card">
                                <div class="stats-number text-danger"><?php echo number_format($stats['rejected_count']); ?></div>
                                <div class="stats-label">Rejected</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-8">
                            <div class="stats-card">
                                <div class="stats-number text-primary">KES <?php echo number_format($stats['total_requested'], 0); ?></div>
                                <div class="stats-label">Total Amount Requested</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="filter-card">
                        <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="Pre-Auth #, Patient...">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="">All Statuses</option>
                                    <option value="DRAFT" <?php echo $status_filter === 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                    <option value="SUBMITTED" <?php echo $status_filter === 'SUBMITTED' ? 'selected' : ''; ?>>Submitted</option>
                                    <option value="PENDING" <?php echo $status_filter === 'PENDING' ? 'selected' : ''; ?>>Pending</option>
                                    <option value="UNDER_REVIEW" <?php echo $status_filter === 'UNDER_REVIEW' ? 'selected' : ''; ?>>Under Review</option>
                                    <option value="APPROVED" <?php echo $status_filter === 'APPROVED' ? 'selected' : ''; ?>>Approved</option>
                                    <option value="REJECTED" <?php echo $status_filter === 'REJECTED' ? 'selected' : ''; ?>>Rejected</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Insurance Provider</label>
                                <select class="form-select" name="provider">
                                    <option value="">All Providers</option>
                                    <?php while ($provider = $providers->fetch_assoc()): ?>
                                        <option value="<?php echo $provider['provider_id']; ?>" <?php echo $provider_filter == $provider['provider_id'] ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($provider['provider_name']); ?>
                                        </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Date From</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">Date To</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>

                    <!-- Pre-Authorizations Table -->
                    <div class="table-card">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Pre-Auth #</th>
                                        <th>Date</th>
                                        <th>Patient</th>
                                        <th>Insurance Provider</th>
                                        <th>Service Type</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Urgency</th>
                                        <th>Expiry</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($preauths->num_rows > 0): ?>
                                        <?php while ($preauth = $preauths->fetch_assoc()): ?>
                                        <tr>
                                            <td>
                                                <strong><?php echo htmlspecialchars($preauth['preauth_number']); ?></strong>
                                            </td>
                                            <td><?php echo date('d M Y', strtotime($preauth['request_date'])); ?></td>
                                            <td>
                                                <div><?php echo htmlspecialchars($preauth['patient_name']); ?></div>
                                                <small class="text-muted"><?php echo htmlspecialchars($preauth['patient_number']); ?></small>
                                            </td>
                                            <td><?php echo htmlspecialchars($preauth['provider_name']); ?></td>
                                            <td><?php echo ucfirst(str_replace('_', ' ', strtolower($preauth['service_type']))); ?></td>
                                            <td>
                                                <strong>KES <?php echo number_format($preauth['requested_amount'], 0); ?></strong>
                                                <?php if ($preauth['approved_amount']): ?>
                                                <br><small class="text-success">Approved: KES <?php echo number_format($preauth['approved_amount'], 0); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="status-badge status-<?php echo strtolower($preauth['auth_status']); ?>">
                                                    <?php echo str_replace('_', ' ', $preauth['auth_status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <span class="urgency-badge urgency-<?php echo strtolower($preauth['urgency_level']); ?>">
                                                    <?php echo $preauth['urgency_level']; ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($preauth['valid_until']): ?>
                                                    <?php 
                                                    $days = $preauth['days_until_expiry'];
                                                    if ($days < 0): ?>
                                                        <span class="expiry-warning">Expired</span>
                                                    <?php elseif ($days <= 7): ?>
                                                        <span class="expiry-soon"><?php echo $days; ?> days</span>
                                                    <?php else: ?>
                                                        <?php echo date('d M Y', strtotime($preauth['valid_until'])); ?>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span class="text-muted">Not set</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <a href="view_preauthorization.php?id=<?php echo $preauth['preauth_id']; ?>" class="btn btn-info" title="View Details">
                                                        <i class="ri-eye-line"></i>
                                                    </a>
                                                    <a href="letter_of_undertaking.php?id=<?php echo $preauth['preauth_id']; ?>" class="btn btn-primary" title="Generate Letter" target="_blank">
                                                        <i class="ri-file-text-line"></i>
                                                    </a>
                                                    <?php if ($preauth['auth_status'] === 'DRAFT'): ?>
                                                    <a href="create_preauthorization.php?edit=<?php echo $preauth['preauth_id']; ?>" class="btn btn-warning" title="Edit">
                                                        <i class="ri-edit-line"></i>
                                                    </a>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="10" class="text-center py-4">
                                                <i class="ri-file-list-line" style="font-size: 3rem; opacity: 0.3;"></i>
                                                <p class="text-muted mt-2">No pre-authorizations found</p>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <div class="p-3 border-top">
                            <nav>
                                <ul class="pagination pagination-sm mb-0 justify-content-center">
                                    <?php if ($page > 1): ?>
                                    <li class="page-item">
                                        <a class="page-link" href="?page=<?php echo ($page - 1); ?>&status=<?php echo $status_filter; ?>&provider=<?php echo $provider_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
                                            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; ?>&status=<?php echo $status_filter; ?>&provider=<?php echo $provider_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
                                            <?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); ?>&status=<?php echo $status_filter; ?>&provider=<?php echo $provider_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>&search=<?php echo urlencode($search); ?>">
                                            Next
                                        </a>
                                    </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                            <div class="text-center text-muted mt-2">
                                <small>Showing <?php echo min($offset + 1, $total_records); ?> to <?php echo min($offset + $records_per_page, $total_records); ?> of <?php echo $total_records; ?> entries</small>
                            </div>
                        </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>
</body>
</html>