<?php
// list_payment_allocations.php - Payment Allocation Listing
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Check if user has permission to view page
// Add your permission check here based on user role

// Get filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$provider_filter = isset($_GET['provider']) ? intval($_GET['provider']) : 0;
$doctor_filter = isset($_GET['doctor']) ? intval($_GET['doctor']) : 0;
$allocation_type_filter = isset($_GET['allocation_type']) ? $_GET['allocation_type'] : 'all';
$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']) : '';

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

// Build WHERE clause
$where_conditions = [];
$params = [];
$types = '';

if ($status_filter !== 'all') {
    $where_conditions[] = "pa.allocation_status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

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

if ($doctor_filter > 0) {
    $where_conditions[] = "pa.doctor_id = ?";
    $params[] = $doctor_filter;
    $types .= 'i';
}

if ($allocation_type_filter !== 'all') {
    $where_conditions[] = "pa.allocation_type = ?";
    $params[] = $allocation_type_filter;
    $types .= 's';
}

if (!empty($date_from)) {
    $where_conditions[] = "pa.service_date >= ?";
    $params[] = $date_from;
    $types .= 's';
}

if (!empty($date_to)) {
    $where_conditions[] = "pa.service_date <= ?";
    $params[] = $date_to;
    $types .= 's';
}

if (!empty($search)) {
    $where_conditions[] = "(pa.allocation_number LIKE ? OR pa.patient_reference LIKE ? OR pa.service_description LIKE ? OR bp.payment_number LIKE ?)";
    $search_term = "%{$search}%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
    $types .= 'ssss';
}

$where_sql = count($where_conditions) > 0 ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get statistics
$stats_sql = "SELECT 
    COUNT(*) as total_allocations,
    SUM(CASE WHEN pa.allocation_status = 'DRAFT' THEN 1 ELSE 0 END) as draft_count,
    SUM(CASE WHEN pa.allocation_status = 'PENDING_APPROVAL' THEN 1 ELSE 0 END) as pending_count,
    SUM(CASE WHEN pa.allocation_status = 'APPROVED' THEN 1 ELSE 0 END) as approved_count,
    SUM(CASE WHEN pa.allocation_status = 'PAID' THEN 1 ELSE 0 END) as paid_count,
    SUM(pa.total_service_cost) as total_service_value,
    SUM(pa.doctor_allocation) as total_doctor_allocation,
    SUM(pa.facility_allocation) as total_facility_allocation
FROM payment_allocations pa
JOIN bulk_payments bp ON pa.bulk_payment_id = bp.bulk_payment_id
JOIN external_service_providers esp ON pa.provider_id = esp.provider_id
LEFT JOIN doctors d ON pa.doctor_id = d.doctor_id
LEFT JOIN users u ON d.user_id = u.user_id
$where_sql";

if (count($params) > 0) {
    $stmt = $conn->prepare($stats_sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $stats = $stmt->get_result()->fetch_assoc();
} else {
    $stats = $conn->query($stats_sql)->fetch_assoc();
}

// Get total records for pagination
$count_sql = "SELECT COUNT(*) as total 
FROM payment_allocations pa
JOIN bulk_payments bp ON pa.bulk_payment_id = bp.bulk_payment_id
JOIN external_service_providers esp ON pa.provider_id = esp.provider_id
LEFT JOIN doctors d ON pa.doctor_id = d.doctor_id
LEFT JOIN users u ON d.user_id = u.user_id
$where_sql";

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

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

// Get allocations
$allocations_sql = "SELECT 
    pa.allocation_id,
    pa.allocation_number,
    pa.service_date,
    pa.patient_reference,
    pa.service_description,
    pa.service_category,
    pa.total_service_cost,
    pa.allocation_type,
    pa.doctor_allocation,
    pa.facility_allocation,
    pa.tax_withheld,
    pa.net_doctor_payment,
    pa.doctor_payment_status,
    pa.allocation_status,
    pa.verification_status,
    bp.payment_number as bulk_payment_number,
    bp.payment_date as bulk_payment_date,
    esp.provider_name,
    esp.provider_code,
    u.full_name as doctor_name,
    d.specialization,
    pa.created_at
FROM payment_allocations pa
JOIN bulk_payments bp ON pa.bulk_payment_id = bp.bulk_payment_id
JOIN external_service_providers esp ON pa.provider_id = esp.provider_id
LEFT JOIN doctors d ON pa.doctor_id = d.doctor_id
LEFT JOIN users u ON d.user_id = u.user_id
$where_sql
ORDER BY pa.service_date DESC, pa.created_at DESC
LIMIT ? OFFSET ?";

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

$stmt = $conn->prepare($allocations_sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$allocations = $stmt->get_result();

// Get providers for filter dropdown
$providers_sql = "SELECT provider_id, provider_name, provider_code 
                  FROM external_service_providers 
                  WHERE is_active = 1 
                  ORDER BY provider_name";
$providers = $conn->query($providers_sql);

// Get active doctors for filter dropdown
$doctors_sql = "SELECT d.doctor_id, u.full_name, d.specialization 
                FROM doctors d 
                JOIN users u ON d.user_id = u.user_id 
                WHERE d.is_active = 1 
                ORDER BY u.full_name";
$doctors = $conn->query($doctors_sql);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Payment Allocations')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            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-left: 4px solid #667eea;
            transition: transform 0.2s;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .stat-value {
            font-size: 1.75rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .filter-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .allocation-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            border: 1px solid #e2e8f0;
            transition: all 0.2s;
        }
        
        .allocation-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            border-color: #667eea;
        }
        
        .allocation-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .allocation-number {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
        }
        
        .allocation-info {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 1rem;
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
        }
        
        .info-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 0.25rem;
        }
        
        .info-value {
            font-size: 0.95rem;
            color: #1e293b;
            font-weight: 500;
        }
        
        .allocation-amounts {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
        }
        
        .amount-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
        }
        
        .amount-row.total {
            border-top: 2px solid #e2e8f0;
            padding-top: 1rem;
            margin-top: 0.5rem;
            font-weight: 600;
        }
        
        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .badge-draft { background: #e0e7ff; color: #4338ca; }
        .badge-pending { background: #fef3c7; color: #92400e; }
        .badge-approved { background: #d1fae5; color: #065f46; }
        .badge-paid { background: #d1fae5; color: #047857; }
        .badge-rejected { background: #fee2e2; color: #991b1b; }
        .badge-cancelled { background: #f1f5f9; color: #475569; }
        
        .badge-doctor-only { background: #dbeafe; color: #1e40af; }
        .badge-facility-only { background: #fce7f3; color: #9f1239; }
        .badge-both { background: #e0e7ff; color: #5b21b6; }
        
        .badge-unverified { background: #fef3c7; color: #92400e; }
        .badge-verified { background: #d1fae5; color: #065f46; }
        .badge-disputed { background: #fee2e2; color: #991b1b; }
        
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: #64748b;
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #cbd5e1;
            margin-bottom: 1rem;
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        
        .btn-sm {
            padding: 0.375rem 0.75rem;
            font-size: 0.875rem;
        }
    </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">
                        <div class="row align-items-center">
                            <div class="col">
                                <h3 class="mb-2"><i class="ri-money-dollar-circle-line me-2"></i>Payment Allocations</h3>
                                <p class="mb-0 opacity-75">Manage allocations from bulk payments to doctors and facility</p>
                            </div>
                            <div class="col-auto">
                                <a href="list_bulk_payments.php" class="btn btn-light me-2">
                                    <i class="ri-file-list-3-line me-1"></i>Bulk Payments
                                </a>
                                <a href="create_payment_allocation.php" class="btn btn-success">
                                    <i class="ri-add-line me-1"></i>New Allocation
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-value"><?php echo number_format($stats['total_allocations']); ?></div>
                                <div class="stat-label">Total Allocations</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #fbbf24;">
                                <div class="stat-value"><?php echo number_format($stats['pending_count']); ?></div>
                                <div class="stat-label">Pending Approval</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #10b981;">
                                <div class="stat-value"><?php echo number_format($stats['approved_count']); ?></div>
                                <div class="stat-label">Approved</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #059669;">
                                <div class="stat-value">KES <?php echo number_format($stats['total_service_value'], 2); ?></div>
                                <div class="stat-label">Total Service Value</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Additional Stats Row -->
                    <div class="row mb-4">
                        <div class="col-xl-4 col-md-6">
                            <div class="stat-card" style="border-left-color: #3b82f6;">
                                <div class="stat-value">KES <?php echo number_format($stats['total_doctor_allocation'], 2); ?></div>
                                <div class="stat-label">Total Doctor Allocations</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6">
                            <div class="stat-card" style="border-left-color: #ec4899;">
                                <div class="stat-value">KES <?php echo number_format($stats['total_facility_allocation'], 2); ?></div>
                                <div class="stat-label">Total Facility Allocations</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-6">
                            <div class="stat-card" style="border-left-color: #8b5cf6;">
                                <div class="stat-value"><?php echo number_format($stats['paid_count']); ?></div>
                                <div class="stat-label">Paid Allocations</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Filters -->
                    <div class="filter-card">
                        <form method="GET" action="" id="filterForm">
                            <div class="row g-3">
                                <div class="col-md-3">
                                    <label class="form-label">Search</label>
                                    <input type="text" class="form-control" name="search" 
                                           placeholder="Allocation #, Patient Ref..." 
                                           value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Status</label>
                                    <select class="form-select" name="status">
                                        <option value="all" <?php echo $status_filter === 'all' ? 'selected' : ''; ?>>All Status</option>
                                        <option value="DRAFT" <?php echo $status_filter === 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                        <option value="PENDING_APPROVAL" <?php echo $status_filter === 'PENDING_APPROVAL' ? 'selected' : ''; ?>>Pending Approval</option>
                                        <option value="APPROVED" <?php echo $status_filter === 'APPROVED' ? 'selected' : ''; ?>>Approved</option>
                                        <option value="PAID" <?php echo $status_filter === 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                        <option value="REJECTED" <?php echo $status_filter === 'REJECTED' ? 'selected' : ''; ?>>Rejected</option>
                                        <option value="CANCELLED" <?php echo $status_filter === 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Allocation Type</label>
                                    <select class="form-select" name="allocation_type">
                                        <option value="all" <?php echo $allocation_type_filter === 'all' ? 'selected' : ''; ?>>All Types</option>
                                        <option value="DOCTOR_ONLY" <?php echo $allocation_type_filter === 'DOCTOR_ONLY' ? 'selected' : ''; ?>>Doctor Only</option>
                                        <option value="FACILITY_ONLY" <?php echo $allocation_type_filter === 'FACILITY_ONLY' ? 'selected' : ''; ?>>Facility Only</option>
                                        <option value="DOCTOR_AND_FACILITY" <?php echo $allocation_type_filter === 'DOCTOR_AND_FACILITY' ? 'selected' : ''; ?>>Doctor & Facility</option>
                                    </select>
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Provider</label>
                                    <select class="form-select" name="provider">
                                        <option value="0">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-3">
                                    <label class="form-label">Doctor</label>
                                    <select class="form-select" name="doctor">
                                        <option value="0">All Doctors</option>
                                        <?php while ($doctor = $doctors->fetch_assoc()): ?>
                                            <option value="<?php echo $doctor['doctor_id']; ?>" 
                                                    <?php echo $doctor_filter == $doctor['doctor_id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($doctor['full_name']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row g-3 mt-2">
                                <div class="col-md-2">
                                    <label class="form-label">Date From</label>
                                    <input type="text" class="form-control datepicker" name="date_from" 
                                           placeholder="Select date" value="<?php echo htmlspecialchars($date_from); ?>">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Date To</label>
                                    <input type="text" class="form-control datepicker" name="date_to" 
                                           placeholder="Select date" value="<?php echo htmlspecialchars($date_to); ?>">
                                </div>
                                <div class="col-md-8 d-flex align-items-end justify-content-end gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="ri-search-line me-1"></i>Filter
                                    </button>
                                    <a href="list_payment_allocations.php" class="btn btn-secondary">
                                        <i class="ri-refresh-line me-1"></i>Reset
                                    </a>
                                    <button type="button" class="btn btn-success" onclick="exportAllocations()">
                                        <i class="ri-file-excel-line me-1"></i>Export
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Allocations List -->
                    <?php if ($allocations->num_rows > 0): ?>
                        <?php while ($allocation = $allocations->fetch_assoc()): ?>
                            <div class="allocation-card">
                                <div class="allocation-header">
                                    <div>
                                        <div class="allocation-number">
                                            <i class="ri-hashtag"></i><?php echo htmlspecialchars($allocation['allocation_number']); ?>
                                        </div>
                                        <div class="text-muted small mt-1">
                                            Bulk Payment: <?php echo htmlspecialchars($allocation['bulk_payment_number']); ?>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <span class="badge badge-<?php 
                                            echo strtolower(str_replace('_', '-', $allocation['allocation_status'])); 
                                        ?>">
                                            <?php echo str_replace('_', ' ', $allocation['allocation_status']); ?>
                                        </span>
                                        <div class="mt-2">
                                            <span class="badge badge-<?php 
                                                echo $allocation['allocation_type'] === 'DOCTOR_ONLY' ? 'doctor-only' : 
                                                    ($allocation['allocation_type'] === 'FACILITY_ONLY' ? 'facility-only' : 'both'); 
                                            ?>">
                                                <?php echo str_replace('_', ' ', $allocation['allocation_type']); ?>
                                            </span>
                                        </div>
                                        <?php if ($allocation['verification_status']): ?>
                                        <div class="mt-2">
                                            <span class="badge badge-<?php echo strtolower($allocation['verification_status']); ?>">
                                                <?php echo ucfirst($allocation['verification_status']); ?>
                                            </span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <div class="allocation-info">
                                    <div class="info-item">
                                        <div class="info-label">Provider</div>
                                        <div class="info-value">
                                            <?php echo htmlspecialchars($allocation['provider_name']); ?>
                                            <span class="text-muted small">(<?php echo htmlspecialchars($allocation['provider_code']); ?>)</span>
                                        </div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Service Date</div>
                                        <div class="info-value"><?php echo date('d M Y', strtotime($allocation['service_date'])); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Patient Reference</div>
                                        <div class="info-value"><?php echo htmlspecialchars($allocation['patient_reference'] ?: 'N/A'); ?></div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Service Category</div>
                                        <div class="info-value"><?php echo ucfirst(strtolower($allocation['service_category'])); ?></div>
                                    </div>
                                    <?php if ($allocation['doctor_name']): ?>
                                    <div class="info-item">
                                        <div class="info-label">Doctor</div>
                                        <div class="info-value">
                                            <?php echo htmlspecialchars($allocation['doctor_name']); ?>
                                            <?php if ($allocation['specialization']): ?>
                                                <div class="text-muted small"><?php echo htmlspecialchars($allocation['specialization']); ?></div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="mt-2">
                                    <div class="info-label">Service Description</div>
                                    <div class="info-value"><?php echo htmlspecialchars($allocation['service_description']); ?></div>
                                </div>
                                
                                <div class="allocation-amounts">
                                    <div class="amount-row">
                                        <span>Total Service Cost:</span>
                                        <strong>KES <?php echo number_format($allocation['total_service_cost'], 2); ?></strong>
                                    </div>
                                    <?php if ($allocation['doctor_allocation'] > 0): ?>
                                    <div class="amount-row">
                                        <span>Doctor Allocation:</span>
                                        <span class="text-primary">KES <?php echo number_format($allocation['doctor_allocation'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($allocation['facility_allocation'] > 0): ?>
                                    <div class="amount-row">
                                        <span>Facility Allocation:</span>
                                        <span class="text-info">KES <?php echo number_format($allocation['facility_allocation'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($allocation['tax_withheld'] > 0): ?>
                                    <div class="amount-row">
                                        <span>Tax Withheld:</span>
                                        <span class="text-danger">KES <?php echo number_format($allocation['tax_withheld'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($allocation['doctor_allocation'] > 0): ?>
                                    <div class="amount-row total">
                                        <span>Net Doctor Payment:</span>
                                        <strong class="text-success">KES <?php echo number_format($allocation['net_doctor_payment'], 2); ?></strong>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($allocation['doctor_payment_status'] && $allocation['doctor_allocation'] > 0): ?>
                                    <div class="amount-row">
                                        <span>Doctor Payment Status:</span>
                                        <span class="badge badge-<?php echo strtolower($allocation['doctor_payment_status']); ?>">
                                            <?php echo str_replace('_', ' ', $allocation['doctor_payment_status']); ?>
                                        </span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="mt-3 d-flex justify-content-between align-items-center">
                                    <div class="text-muted small">
                                        <i class="ri-calendar-line me-1"></i>
                                        Created: <?php echo date('d M Y H:i', strtotime($allocation['created_at'])); ?>
                                    </div>
                                    <div class="action-buttons">
                                        <a href="view_payment_allocation.php?id=<?php echo $allocation['allocation_id']; ?>" 
                                           class="btn btn-sm btn-primary">
                                            <i class="ri-eye-line me-1"></i>View
                                        </a>
                                        <?php if ($allocation['allocation_status'] === 'DRAFT'): ?>
                                        <a href="edit_payment_allocation.php?id=<?php echo $allocation['allocation_id']; ?>" 
                                           class="btn btn-sm btn-info">
                                            <i class="ri-edit-line me-1"></i>Edit
                                        </a>
                                        <?php endif; ?>
                                        <?php if ($allocation['allocation_status'] === 'DRAFT'): ?>
                                        <button onclick="submitForApproval(<?php echo $allocation['allocation_id']; ?>)" 
                                                class="btn btn-sm btn-success">
                                            <i class="ri-check-line me-1"></i>Submit for Approval
                                        </button>
                                        <?php endif; ?>
                                        <?php if ($allocation['allocation_status'] === 'PENDING_APPROVAL'): ?>
                                        <button onclick="approveAllocation(<?php echo $allocation['allocation_id']; ?>)" 
                                                class="btn btn-sm btn-success">
                                            <i class="ri-check-double-line me-1"></i>Approve
                                        </button>
                                        <button onclick="rejectAllocation(<?php echo $allocation['allocation_id']; ?>)" 
                                                class="btn btn-sm btn-danger">
                                            <i class="ri-close-line me-1"></i>Reject
                                        </button>
                                        <?php endif; ?>
                                        <button onclick="printAllocation(<?php echo $allocation['allocation_id']; ?>)" 
                                                class="btn btn-sm btn-secondary">
                                            <i class="ri-printer-line me-1"></i>Print
                                        </button>
                                    </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                        
                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <div class="row mt-4">
                            <div class="col-12">
                                <nav>
                                    <ul class="pagination 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; ?>&doctor=<?php echo $doctor_filter; ?>&allocation_type=<?php echo $allocation_type_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; ?>&doctor=<?php echo $doctor_filter; ?>&allocation_type=<?php echo $allocation_type_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; ?>&doctor=<?php echo $doctor_filter; ?>&allocation_type=<?php echo $allocation_type_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">
                                    Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $records_per_page, $total_records); ?> of <?php echo number_format($total_records); ?> allocations
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                    <?php else: ?>
                        <div class="allocation-card">
                            <div class="empty-state">
                                <i class="ri-file-list-3-line"></i>
                                <h5>No Allocations Found</h5>
                                <p>No payment allocations match your current filters.</p>
                                <a href="list_payment_allocations.php" class="btn btn-primary mt-2">
                                    <i class="ri-refresh-line me-1"></i>Reset Filters
                                </a>
                            </div>
                        </div>
                    <?php endif; ?>
                    
                </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 src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <script>
        // Initialize Flatpickr for date inputs
        document.addEventListener('DOMContentLoaded', function() {
            flatpickr('.datepicker', {
                dateFormat: 'Y-m-d',
                allowInput: true
            });
        });
        
        // Submit for approval
        function submitForApproval(allocationId) {
            Swal.fire({
                title: 'Submit for Approval?',
                text: 'This allocation will be sent for approval. You won\'t be able to edit it afterwards.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#059669',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, submit it',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Send AJAX request
                    fetch('actions/submit_allocation_approval.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'allocation_id=' + allocationId
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Submitted!',
                                text: data.message,
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Error', data.message, 'error');
                        }
                    })
                    .catch(error => {
                        Swal.fire('Error', 'An error occurred. Please try again.', 'error');
                    });
                }
            });
        }
        
        // Approve allocation
        function approveAllocation(allocationId) {
            Swal.fire({
                title: 'Approve Allocation?',
                text: 'This will approve the payment allocation.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#059669',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, approve it',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('actions/approve_allocation.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'allocation_id=' + allocationId
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Approved!',
                                text: data.message,
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Error', data.message, 'error');
                        }
                    })
                    .catch(error => {
                        Swal.fire('Error', 'An error occurred. Please try again.', 'error');
                    });
                }
            });
        }
        
        // Reject allocation
        function rejectAllocation(allocationId) {
            Swal.fire({
                title: 'Reject Allocation?',
                html: '<textarea id="rejection-reason" class="swal2-textarea" placeholder="Enter reason for rejection..." style="width: 100%; height: 100px;"></textarea>',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, reject it',
                cancelButtonText: 'Cancel',
                preConfirm: () => {
                    const reason = document.getElementById('rejection-reason').value;
                    if (!reason) {
                        Swal.showValidationMessage('Please enter a reason for rejection');
                    }
                    return { reason: reason };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    fetch('actions/reject_allocation.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'allocation_id=' + allocationId + '&reason=' + encodeURIComponent(result.value.reason)
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Rejected!',
                                text: data.message,
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Error', data.message, 'error');
                        }
                    })
                    .catch(error => {
                        Swal.fire('Error', 'An error occurred. Please try again.', 'error');
                    });
                }
            });
        }
        
        // Print allocation
        function printAllocation(allocationId) {
            window.open('print_allocation.php?id=' + allocationId, '_blank');
        }
        
        // Export allocations
        function exportAllocations() {
            const form = document.getElementById('filterForm');
            const formData = new FormData(form);
            const params = new URLSearchParams(formData).toString();
            window.location.href = 'export_allocations.php?' + params;
        }
    </script>
</body>
</html>