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

$page_title = "All Invoices";

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

// Filters
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, trim($_GET['search'])) : '';
$status_filter = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';
$bill_to_filter = isset($_GET['bill_to']) ? mysqli_real_escape_string($conn, $_GET['bill_to']) : '';
$date_from = isset($_GET['date_from']) ? mysqli_real_escape_string($conn, $_GET['date_from']) : '';
$date_to = isset($_GET['date_to']) ? mysqli_real_escape_string($conn, $_GET['date_to']) : '';

// Build WHERE conditions
$where_conditions = ["1=1"];

if ($search) {
    $where_conditions[] = "(i.invoice_number LIKE '%$search%' OR u.full_name LIKE '%$search%' OR pat.patient_unique_id LIKE '%$search%')";
}

if ($status_filter) {
    $where_conditions[] = "i.status = '$status_filter'";
}

if ($bill_to_filter) {
    $where_conditions[] = "i.bill_to = '$bill_to_filter'";
}

if ($date_from) {
    $where_conditions[] = "i.invoice_date >= '$date_from'";
}

if ($date_to) {
    $where_conditions[] = "i.invoice_date <= '$date_to'";
}

$where_clause = implode(" AND ", $where_conditions);

// Get total count
$count_query = "SELECT COUNT(*) as total 
FROM invoices i
INNER JOIN patients pat ON i.patient_id = pat.patient_id
INNER JOIN users u ON pat.user_id = u.user_id
WHERE $where_clause";

$count_result = mysqli_query($conn, $count_query);
$total_records = mysqli_fetch_assoc($count_result)['total'];
$total_pages = ceil($total_records / $records_per_page);

// Get invoices
$invoices_query = "SELECT 
    i.invoice_id,
    i.invoice_number,
    i.invoice_date,
    i.due_date,
    i.total_amount,
    i.amount_paid,
    i.balance,
    i.status,
    i.bill_to,
    u.full_name as patient_name,
    pat.patient_number,
    u.phone_primary as mobileno,
    ip.provider_name as insurance_provider,
    i.insurance_claim_number,
    DATEDIFF(CURDATE(), i.due_date) as days_overdue
FROM invoices i
INNER JOIN patients pat ON i.patient_id = pat.patient_id
INNER JOIN users u ON pat.user_id = u.user_id
LEFT JOIN insurance_providers ip ON i.insurance_provider_id = ip.provider_id
WHERE $where_clause
ORDER BY i.invoice_date DESC, i.invoice_id DESC
LIMIT $records_per_page OFFSET $offset";

$invoices_result = mysqli_query($conn, $invoices_query);
$invoices = [];
while ($row = mysqli_fetch_assoc($invoices_result)) {
    $invoices[] = $row;
}

// Get summary statistics
$stats_query = "SELECT 
    COUNT(*) as total_invoices,
    COALESCE(SUM(total_amount), 0) as total_billed,
    COALESCE(SUM(amount_paid), 0) as total_paid,
    COALESCE(SUM(balance), 0) as total_outstanding,
    COUNT(CASE WHEN i.status = 'DRAFT' THEN 1 END) as draft_count,
    COUNT(CASE WHEN i.status = 'SENT' THEN 1 END) as sent_count,
    COUNT(CASE WHEN i.status = 'PARTIAL_PAYMENT' THEN 1 END) as partial_count,
    COUNT(CASE WHEN i.status = 'PAID' THEN 1 END) as paid_count,
    COUNT(CASE WHEN i.status = 'OVERDUE' THEN 1 END) as overdue_count
FROM invoices i
INNER JOIN patients pat ON i.patient_id = pat.patient_id
INNER JOIN users u ON pat.user_id = u.user_id
WHERE $where_clause";

$stats_result = mysqli_query($conn, $stats_query);
$stats = mysqli_fetch_assoc($stats_result);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.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;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-mini {
            text-align: center;
            padding: 1rem;
            border-radius: 8px;
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            margin-bottom: 1rem;
        }
        
        .stat-mini-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
        }
        
        .stat-mini-label {
            font-size: 0.75rem;
            color: #64748b;
            margin-top: 0.25rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            display: inline-block;
        }
        
        .status-badge.draft { background: #f1f5f9; color: #475569; }
        .status-badge.sent { background: #dbeafe; color: #1e40af; }
        .status-badge.partial_payment { background: #fef3c7; color: #92400e; }
        .status-badge.paid { background: #dcfce7; color: #166534; }
        .status-badge.insurance_pending { background: #f3e8ff; color: #6b21a8; }
        .status-badge.overdue { background: #fee2e2; color: #991b1b; }
        .status-badge.cancelled { background: #f1f5f9; color: #64748b; }
        
        .bill-to-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.7rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .bill-to-badge.patient { background: #e0f2fe; color: #075985; }
        .bill-to-badge.insurance { background: #ede9fe; color: #5b21b6; }
        .bill-to-badge.corporate { background: #fef9c3; color: #854d0e; }
        
        .filter-section {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .invoice-table {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .invoice-table th {
            background: #f8fafc;
            font-weight: 600;
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #475569;
            padding: 1rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .invoice-table td {
            padding: 1rem;
            vertical-align: middle;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .invoice-table tr:hover {
            background: #f8fafc;
        }
        
        .amount-cell {
            text-align: right;
            font-weight: 600;
        }
        
        .amount-paid { color: #059669; }
        .amount-balance { color: #dc2626; }
        
        .overdue-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            background: #fee2e2;
            color: #991b1b;
            border-radius: 4px;
            font-size: 0.7rem;
            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">Invoice Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item">Financial Management</li>
                                        <li class="breadcrumb-item active">All Invoices</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-file-list-3-line me-2"></i>All Invoices</h4>
                                <p class="mb-0">Manage patient invoices and billing</p>
                            </div>
                            <div>
                                <a href="create_invoice.php" class="btn btn-light btn-lg">
                                    <i class="ri-add-line me-2"></i>Create Invoice
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="row">
                        <div class="col-xl-2 col-md-4 col-6">
                            <div class="stat-mini">
                                <div class="stat-mini-value"><?php echo number_format($stats['total_invoices']); ?></div>
                                <div class="stat-mini-label">Total Invoices</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6">
                            <div class="stat-mini">
                                <div class="stat-mini-value text-success"><?php echo $stats['paid_count']; ?></div>
                                <div class="stat-mini-label">Paid</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6">
                            <div class="stat-mini">
                                <div class="stat-mini-value text-warning"><?php echo $stats['partial_count']; ?></div>
                                <div class="stat-mini-label">Partial</div>
                            </div>
                        </div>
                        <div class="col-xl-2 col-md-4 col-6">
                            <div class="stat-mini">
                                <div class="stat-mini-value text-danger"><?php echo $stats['overdue_count']; ?></div>
                                <div class="stat-mini-label">Overdue</div>
                            </div>
                        </div>
                        <div class="col-xl-4 col-md-8 col-12">
                            <div class="stat-mini" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none;">
                                <div class="stat-mini-value">KES <?php echo number_format($stats['total_outstanding'], 2); ?></div>
                                <div class="stat-mini-label" style="color: rgba(255,255,255,0.9);">Total Outstanding</div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="d-flex flex-wrap gap-2">
                                <a href="create_invoice.php" class="btn btn-primary">
                                    <i class="ri-add-circle-line me-1"></i> Create Invoice
                                </a>
                                <button type="button" class="btn btn-success" onclick="exportInvoices()">
                                    <i class="ri-file-excel-line me-1"></i> Export to Excel
                                </button>
                                <button type="button" class="btn btn-outline-primary" onclick="sendBulkReminders()">
                                    <i class="ri-mail-send-line me-1"></i> Send Reminders
                                </button>
                                <button type="button" class="btn btn-outline-danger" onclick="clearFilters()">
                                    <i class="ri-filter-off-line me-1"></i> Clear Filters
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="filter-section">
                        <form method="GET" id="filterForm" 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="Invoice #, Patient name, ID...">
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Status</label>
                                <select class="form-select" name="status">
                                    <option value="">All Status</option>
                                    <option value="DRAFT" <?php echo $status_filter == 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                    <option value="SENT" <?php echo $status_filter == 'SENT' ? 'selected' : ''; ?>>Sent</option>
                                    <option value="PARTIAL_PAYMENT" <?php echo $status_filter == 'PARTIAL_PAYMENT' ? 'selected' : ''; ?>>Partial Payment</option>
                                    <option value="PAID" <?php echo $status_filter == 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                    <option value="INSURANCE_PENDING" <?php echo $status_filter == 'INSURANCE_PENDING' ? 'selected' : ''; ?>>Insurance Pending</option>
                                    <option value="OVERDUE" <?php echo $status_filter == 'OVERDUE' ? 'selected' : ''; ?>>Overdue</option>
                                    <option value="CANCELLED" <?php echo $status_filter == 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label class="form-label">Bill To</label>
                                <select class="form-select" name="bill_to">
                                    <option value="">All</option>
                                    <option value="PATIENT" <?php echo $bill_to_filter == 'PATIENT' ? 'selected' : ''; ?>>Patient</option>
                                    <option value="INSURANCE" <?php echo $bill_to_filter == 'INSURANCE' ? 'selected' : ''; ?>>Insurance</option>
                                    <option value="CORPORATE" <?php echo $bill_to_filter == 'CORPORATE' ? 'selected' : ''; ?>>Corporate</option>
                                </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 $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 $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>

                    <!-- Invoices Table -->
                    <div class="invoice-table">
                        <div class="table-responsive">
                            <table class="table mb-0">
                                <thead>
                                    <tr>
                                        <th>
                                            <input type="checkbox" id="selectAll" class="form-check-input">
                                        </th>
                                        <th>Invoice #</th>
                                        <th>Patient</th>
                                        <th>Date</th>
                                        <th>Bill To</th>
                                        <th class="text-end">Amount</th>
                                        <th class="text-end">Paid</th>
                                        <th class="text-end">Balance</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (!empty($invoices)): ?>
                                        <?php foreach ($invoices as $invoice): ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" class="form-check-input invoice-check" 
                                                       value="<?php echo $invoice['invoice_id']; ?>">
                                            </td>
                                            <td>
                                                <strong><?php echo $invoice['invoice_number']; ?></strong>
                                                <?php if ($invoice['days_overdue'] > 0 && $invoice['balance'] > 0): ?>
                                                    <br><span class="overdue-badge"><?php echo $invoice['days_overdue']; ?> days overdue</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <div style="font-weight: 600;"><?php echo htmlspecialchars($invoice['patient_name']); ?></div>
                                                <div style="font-size: 0.75rem; color: #64748b;">
                                                    <?php echo $invoice['patient_unique_id']; ?>
                                                </div>
                                            </td>
                                            <td>
                                                <div><?php echo date('M d, Y', strtotime($invoice['invoice_date'])); ?></div>
                                                <?php if ($invoice['due_date']): ?>
                                                    <div style="font-size: 0.75rem; color: #64748b;">
                                                        Due: <?php echo date('M d', strtotime($invoice['due_date'])); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="bill-to-badge <?php echo strtolower($invoice['bill_to']); ?>">
                                                    <?php echo $invoice['bill_to']; ?>
                                                </span>
                                                <?php if ($invoice['bill_to'] == 'INSURANCE' && $invoice['insurance_provider']): ?>
                                                    <div style="font-size: 0.7rem; color: #64748b; margin-top: 0.25rem;">
                                                        <?php echo htmlspecialchars($invoice['insurance_provider']); ?>
                                                    </div>
                                                <?php endif; ?>
                                            </td>
                                            <td class="amount-cell">
                                                KES <?php echo number_format($invoice['total_amount'], 2); ?>
                                            </td>
                                            <td class="amount-cell amount-paid">
                                                KES <?php echo number_format($invoice['amount_paid'], 2); ?>
                                            </td>
                                            <td class="amount-cell amount-balance">
                                                KES <?php echo number_format($invoice['balance'], 2); ?>
                                            </td>
                                            <td>
                                                <span class="status-badge <?php echo strtolower(str_replace('_', '', $invoice['status'])); ?>">
                                                    <?php echo str_replace('_', ' ', $invoice['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <a href="view_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" 
                                                       class="btn btn-outline-primary" title="View">
                                                        <i class="ri-eye-line"></i>
                                                    </a>
                                                    <a href="edit_invoice.php?id=<?php echo $invoice['invoice_id']; ?>" 
                                                       class="btn btn-outline-secondary" title="Edit">
                                                        <i class="ri-pencil-line"></i>
                                                    </a>
                                                    <button type="button" class="btn btn-outline-success" 
                                                            onclick="recordPayment(<?php echo $invoice['invoice_id']; ?>)" 
                                                            title="Record Payment">
                                                        <i class="ri-money-dollar-circle-line"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-outline-info" 
                                                            onclick="printInvoice(<?php echo $invoice['invoice_id']; ?>)" 
                                                            title="Print">
                                                        <i class="ri-printer-line"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="10" class="text-center py-5">
                                                <i class="ri-file-list-3-line" style="font-size: 3rem; color: #cbd5e1;"></i>
                                                <p class="text-muted mt-3">No invoices found</p>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <?php if ($total_pages > 1): ?>
                        <div class="d-flex justify-content-between align-items-center p-3 border-top">
                            <div class="text-muted">
                                Showing <?php echo $offset + 1; ?> to <?php echo min($offset + $records_per_page, $total_records); ?> of <?php echo $total_records; ?> invoices
                            </div>
                            <nav>
                                <ul class="pagination mb-0">
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?page=<?php echo $page - 1; ?>&<?php echo http_build_query(array_diff_key($_GET, ['page' => ''])); ?>">
                                                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; ?>&<?php echo http_build_query(array_diff_key($_GET, ['page' => ''])); ?>">
                                                <?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; ?>&<?php echo http_build_query(array_diff_key($_GET, ['page' => ''])); ?>">
                                                Next
                                            </a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        </div>
                        <?php endif; ?>
                    </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        // Select All functionality
        document.getElementById('selectAll').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('.invoice-check');
            checkboxes.forEach(checkbox => checkbox.checked = this.checked);
        });

        function recordPayment(invoiceId) {
            window.location.href = 'record_payment.php?invoice_id=' + invoiceId;
        }

        function printInvoice(invoiceId) {
            window.open('print_invoice.php?id=' + invoiceId, '_blank');
        }

        function exportInvoices() {
            const queryString = window.location.search;
            window.location.href = 'actions/export_invoices.php' + queryString;
        }

        function sendBulkReminders() {
            const selectedInvoices = Array.from(document.querySelectorAll('.invoice-check:checked'))
                .map(cb => cb.value);
            
            if (selectedInvoices.length === 0) {
                Swal.fire('Please select invoices', 'Select at least one invoice to send reminders', 'warning');
                return;
            }

            Swal.fire({
                title: 'Send Payment Reminders',
                text: `Send payment reminders for ${selectedInvoices.length} selected invoice(s)?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Send',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#667eea'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Send reminders via AJAX
                    $.ajax({
                        url: 'actions/send_invoice_reminders.php',
                        method: 'POST',
                        data: JSON.stringify({invoice_ids: selectedInvoices}),
                        contentType: 'application/json',
                        dataType: 'json',
                        success: function(data) {
                            if (data.success) {
                                Swal.fire('Success', data.message, 'success');
                            } else {
                                Swal.fire('Error', data.message, 'error');
                            }
                        },
                        error: function() {
                            Swal.fire('Error', 'Failed to send reminders', 'error');
                        }
                    });
                }
            });
        }

        function clearFilters() {
            window.location.href = 'list_invoices.php';
        }
    </script>
</body>
</html>
<?php mysqli_close($conn); ?>