<?php
// doctor_payment_batches.php - Manage Doctor Payment Batches
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Get filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : 'all';
$doctor_filter = isset($_GET['doctor']) ? intval($_GET['doctor']) : 0;
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// 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[] = "dpb.status = ?";
    $params[] = $status_filter;
    $types .= 's';
}

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

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

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

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

// Get statistics
$stats_sql = "SELECT 
    COUNT(*) as total_batches,
    SUM(dpb.gross_amount) as total_gross,
    SUM(dpb.total_tax_withheld) as total_tax,
    SUM(dpb.net_payable) as total_net,
    SUM(CASE WHEN dpb.status IN ('DRAFT', 'PENDING_APPROVAL') THEN dpb.net_payable ELSE 0 END) as pending_amount,
    SUM(CASE WHEN dpb.status = 'PAID' THEN dpb.net_payable ELSE 0 END) as paid_amount
FROM doctor_payment_batches dpb
$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
$count_sql = "SELECT COUNT(*) as total FROM doctor_payment_batches dpb $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 batches
$batches_sql = "SELECT 
    dpb.*,
    u.full_name as doctor_name,
    d.specialization,
    d.medical_license,
    approved_user.full_name as approved_by_name,
    processed_user.full_name as processed_by_name
FROM doctor_payment_batches dpb
JOIN doctors d ON dpb.doctor_id = d.doctor_id
JOIN users u ON d.user_id = u.user_id
LEFT JOIN users approved_user ON dpb.approved_by = approved_user.user_id
LEFT JOIN users processed_user ON dpb.processed_by = processed_user.user_id
$where_sql
ORDER BY dpb.created_at DESC
LIMIT ? OFFSET ?";

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

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

// Get doctors for filter
$doctors_sql = "SELECT d.doctor_id, u.full_name 
                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' => 'Doctor Payment Batches')); ?>
    <?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, #3b82f6 0%, #2563eb 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 #3b82f6;
            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;
        }
        
        .batch-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            border: 1px solid #e2e8f0;
            transition: all 0.2s;
        }
        
        .batch-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            border-color: #3b82f6;
        }
        
        .batch-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .batch-number {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
        }
        
        .batch-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;
        }
        
        .amounts-box {
            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 #3b82f6;
            margin-top: 0.5rem;
            padding-top: 1rem;
            font-weight: 700;
            color: #3b82f6;
        }
        
        .badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .badge-draft { background: #e0e7ff; color: #4338ca; }
        .badge-pending-approval { background: #fef3c7; color: #92400e; }
        .badge-approved { background: #d1fae5; color: #065f46; }
        .badge-processing { background: #dbeafe; color: #1e40af; }
        .badge-paid { background: #d1fae5; color: #047857; }
        .badge-failed { background: #fee2e2; color: #991b1b; }
        .badge-cancelled { background: #f1f5f9; color: #475569; }
        
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            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">
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h3 class="mb-2"><i class="ri-group-line me-2"></i>Doctor Payment Batches</h3>
                                <p class="mb-0 opacity-75">Manage batch payments to doctors</p>
                            </div>
                            <div class="col-auto">
                                <a href="create_payment_batch.php" class="btn btn-success">
                                    <i class="ri-add-line me-1"></i>Create Batch
                                </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_batches']); ?></div>
                                <div class="stat-label">Total Batches</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #10b981;">
                                <div class="stat-value">KES <?php echo number_format($stats['total_gross'] ?? 0, 0); ?></div>
                                <div class="stat-label">Total Gross Amount</div>
                            </div>
                        </div>
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card" style="border-left-color: #f59e0b;">
                                <div class="stat-value">KES <?php echo number_format($stats['pending_amount'] ?? 0, 0); ?></div>
                                <div class="stat-label">Pending Payment</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['paid_amount'] ?? 0, 0); ?></div>
                                <div class="stat-label">Total Paid</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Filters -->
                    <div class="filter-card">
                        <form method="GET" action="">
                            <div class="row g-3">
                                <div class="col-md-3">
                                    <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="PROCESSING" <?php echo $status_filter === 'PROCESSING' ? 'selected' : ''; ?>>Processing</option>
                                        <option value="PAID" <?php echo $status_filter === 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                        <option value="FAILED" <?php echo $status_filter === 'FAILED' ? 'selected' : ''; ?>>Failed</option>
                                    </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 class="col-md-2">
                                    <label class="form-label">Period From</label>
                                    <input type="text" class="form-control datepicker" name="date_from" 
                                           value="<?php echo htmlspecialchars($date_from); ?>">
                                </div>
                                <div class="col-md-2">
                                    <label class="form-label">Period To</label>
                                    <input type="text" class="form-control datepicker" name="date_to" 
                                           value="<?php echo htmlspecialchars($date_to); ?>">
                                </div>
                                <div class="col-md-2 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>Filter
                                    </button>
                                    <a href="doctor_payment_batches.php" class="btn btn-secondary">
                                        <i class="ri-refresh-line"></i>
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                    
                    <!-- Batches List -->
                    <?php if ($batches->num_rows > 0): ?>
                        <?php while ($batch = $batches->fetch_assoc()): ?>
                            <div class="batch-card">
                                <div class="batch-header">
                                    <div>
                                        <div class="batch-number">
                                            <i class="ri-hashtag"></i><?php echo htmlspecialchars($batch['batch_number']); ?>
                                        </div>
                                        <div class="text-muted small mt-1">
                                            <?php echo htmlspecialchars($batch['doctor_name']); ?>
                                            <?php if ($batch['specialization']): ?>
                                                - <?php echo htmlspecialchars($batch['specialization']); ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="text-end">
                                        <span class="badge badge-<?php echo strtolower(str_replace('_', '-', $batch['status'])); ?>">
                                            <?php echo str_replace('_', ' ', $batch['status']); ?>
                                        </span>
                                    </div>
                                </div>
                                
                                <div class="batch-info">
                                    <div class="info-item">
                                        <div class="info-label">Payment Period</div>
                                        <div class="info-value">
                                            <?php echo date('d M', strtotime($batch['payment_period_start'])); ?> - 
                                            <?php echo date('d M Y', strtotime($batch['payment_period_end'])); ?>
                                        </div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Total Allocations</div>
                                        <div class="info-value"><?php echo number_format($batch['total_allocations']); ?> items</div>
                                    </div>
                                    <div class="info-item">
                                        <div class="info-label">Payment Method</div>
                                        <div class="info-value"><?php echo str_replace('_', ' ', $batch['payment_method']); ?></div>
                                    </div>
                                    <?php if ($batch['payment_date']): ?>
                                    <div class="info-item">
                                        <div class="info-label">Payment Date</div>
                                        <div class="info-value"><?php echo date('d M Y', strtotime($batch['payment_date'])); ?></div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="amounts-box">
                                    <div class="amount-row">
                                        <span>Gross Amount:</span>
                                        <strong>KES <?php echo number_format($batch['gross_amount'], 2); ?></strong>
                                    </div>
                                    <?php if ($batch['total_tax_withheld'] > 0): ?>
                                    <div class="amount-row">
                                        <span>Less: Tax Withheld:</span>
                                        <span class="text-danger">KES <?php echo number_format($batch['total_tax_withheld'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if ($batch['total_deductions'] > 0): ?>
                                    <div class="amount-row">
                                        <span>Less: Deductions:</span>
                                        <span class="text-danger">KES <?php echo number_format($batch['total_deductions'], 2); ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <div class="amount-row total">
                                        <span>Net Payable:</span>
                                        <strong>KES <?php echo number_format($batch['net_payable'], 2); ?></strong>
                                    </div>
                                </div>
                                
                                <div class="mt-3 d-flex justify-content-between align-items-center">
                                    <div class="text-muted small">
                                        Created: <?php echo date('d M Y', strtotime($batch['created_at'])); ?>
                                        <?php if ($batch['approved_at']): ?>
                                            | Approved: <?php echo date('d M Y', strtotime($batch['approved_at'])); ?>
                                        <?php endif; ?>
                                    </div>
                                    <div class="d-flex gap-2">
                                        <a href="view_payment_batch.php?id=<?php echo $batch['batch_id']; ?>" 
                                           class="btn btn-sm btn-primary">
                                            <i class="ri-eye-line me-1"></i>View
                                        </a>
                                        <?php if ($batch['status'] === 'APPROVED'): ?>
                                        <a href="process_doctor_payment.php?id=<?php echo $batch['batch_id']; ?>" 
                                           class="btn btn-sm btn-success">
                                            <i class="ri-check-double-line me-1"></i>Process Payment
                                        </a>
                                        <?php endif; ?>
                                        <button onclick="printBatch(<?php echo $batch['batch_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; ?>&doctor=<?php echo $doctor_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                                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; ?>&doctor=<?php echo $doctor_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                                <?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; ?>&doctor=<?php echo $doctor_filter; ?>&date_from=<?php echo $date_from; ?>&date_to=<?php echo $date_to; ?>">
                                                Next
                                            </a>
                                        </li>
                                        <?php endif; ?>
                                    </ul>
                                </nav>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                    <?php else: ?>
                        <div class="batch-card">
                            <div class="empty-state">
                                <i class="ri-group-line"></i>
                                <h5>No Payment Batches Found</h5>
                                <p>Create your first payment batch to group doctor allocations</p>
                                <a href="create_payment_batch.php" class="btn btn-success mt-2">
                                    <i class="ri-add-line me-1"></i>Create Batch
                                </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>
        document.addEventListener('DOMContentLoaded', function() {
            flatpickr('.datepicker', {
                dateFormat: 'Y-m-d',
                allowInput: true
            });
        });
        
        function printBatch(batchId) {
            window.open('print_payment_batch.php?id=' + batchId, '_blank');
        }
    </script>
</body>
</html>