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

$page_title = "Pending Invoices";

// Fetch pending invoices - Using EXACT schema
$query = "SELECT i.*, 
          p.patient_number, 
          u.full_name as patient_name,
          u.phone_primary,
          ip.provider_name,
          DATEDIFF(CURDATE(), i.due_date) as days_overdue,
          creator.full_name as created_by_name,
          ei.submission_status as etims_status,
          ei.etims_invoice_number
          FROM invoices i
          JOIN patients p ON i.patient_id = p.patient_id
          JOIN users u ON p.user_id = u.user_id
          LEFT JOIN insurance_providers ip ON i.insurance_provider_id = ip.provider_id
          LEFT JOIN users creator ON i.created_by = creator.user_id
          LEFT JOIN etims_invoices ei ON i.invoice_id = ei.invoice_id
          WHERE i.status IN ('SENT', 'PARTIAL_PAYMENT', 'INSURANCE_PENDING') 
          AND i.balance > 0
          ORDER BY i.due_date ASC, i.created_at DESC";

$result = mysqli_query($conn, $query);

// Calculate summary statistics
$summary_query = "SELECT 
                  COUNT(*) as total_pending,
                  SUM(balance) as total_balance,
                  SUM(CASE WHEN due_date < CURDATE() THEN balance ELSE 0 END) as overdue_balance,
                  SUM(CASE WHEN bill_to = 'INSURANCE' THEN balance ELSE 0 END) as insurance_pending,
                  COUNT(CASE WHEN due_date < CURDATE() THEN 1 END) as overdue_count
                  FROM invoices 
                  WHERE status IN ('SENT', 'PARTIAL_PAYMENT', 'INSURANCE_PENDING') 
                  AND balance > 0";
$summary_result = mysqli_query($conn, $summary_query);
$summary = mysqli_fetch_assoc($summary_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">
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: transform 0.2s;
            margin-bottom: 1.5rem;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.15);
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-bottom: 1rem;
        }
        
        .stat-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
        }
        
        .chart-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .quick-action-btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }
        
        .quick-action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .badge-overdue {
            background: #fecaca;
            color: #991b1b;
        }
    </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"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="financial_dashboard.php">Financial</a></li>
                                        <li class="breadcrumb-item active">Pending 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-hourglass-line me-2"></i>Pending Invoices</h4>
                                <p class="mb-0">Track unpaid invoices and outstanding balances</p>
                            </div>
                            <a href="create_invoice.php" class="btn btn-light">
                                <i class="ri-add-line me-1"></i> Create Invoice
                            </a>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white;">
                                    <i class="ri-file-list-3-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($summary['total_pending'] ?? 0); ?></div>
                                <div class="stat-label">Total Pending Invoices</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white;">
                                    <i class="ri-money-dollar-circle-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['total_balance'] ?? 0, 2); ?></div>
                                <div class="stat-label">Total Outstanding Balance</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #dc2626 0%, #991b1b 100%); color: white;">
                                    <i class="ri-alarm-warning-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['overdue_balance'] ?? 0, 2); ?></div>
                                <div class="stat-label">Overdue Amount</div>
                                <small class="text-danger"><?php echo $summary['overdue_count'] ?? 0; ?> invoices</small>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white;">
                                    <i class="ri-shield-check-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['insurance_pending'] ?? 0, 2); ?></div>
                                <div class="stat-label">Insurance Pending</div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="chart-card">
                                <h5 class="mb-3">Quick Actions</h5>
                                <div class="d-flex flex-wrap gap-2">
                                    <a href="record_payment.php" class="btn btn-success quick-action-btn">
                                        <i class="ri-money-dollar-circle-line"></i> Record Payment
                                    </a>
                                    <button type="button" class="btn btn-info quick-action-btn" id="sendBulkReminders">
                                        <i class="ri-mail-send-line"></i> Send Bulk Reminders
                                    </button>
                                    <a href="overdue_invoices.php" class="btn btn-danger quick-action-btn">
                                        <i class="ri-alarm-warning-line"></i> View Overdue
                                    </a>
                                    <a href="list_invoices.php" class="btn btn-outline-primary quick-action-btn">
                                        <i class="ri-file-list-line"></i> All Invoices
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Invoices Table -->
                    <div class="chart-card">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0"><i class="ri-file-text-line me-2"></i>Pending Invoices List</h5>
                            <div class="d-flex gap-2">
                                <button class="btn btn-outline-success btn-sm" id="exportExcel">
                                    <i class="ri-file-excel-line me-1"></i> Export
                                </button>
                                <button class="btn btn-outline-primary btn-sm" id="printList">
                                    <i class="ri-printer-line me-1"></i> Print
                                </button>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover table-striped" id="pendingInvoicesTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>
                                            <input type="checkbox" class="form-check-input" id="selectAll">
                                        </th>
                                        <th>Invoice #</th>
                                        <th>Date</th>
                                        <th>Due Date</th>
                                        <th>Patient</th>
                                        <th>Bill To</th>
                                        <th>Total Amount</th>
                                        <th>Paid</th>
                                        <th>Balance</th>
                                        <th>Status</th>
                                        <th>eTIMS</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (mysqli_num_rows($result) > 0): ?>
                                        <?php while ($invoice = mysqli_fetch_assoc($result)): ?>
                                        <tr>
                                            <td>
                                                <input type="checkbox" class="form-check-input invoice-checkbox" 
                                                       value="<?php echo $invoice['invoice_id']; ?>">
                                            </td>
                                            <td>
                                                <strong class="text-primary"><?php echo htmlspecialchars($invoice['invoice_number']); ?></strong>
                                            </td>
                                            <td><?php echo date('d M Y', strtotime($invoice['invoice_date'])); ?></td>
                                            <td>
                                                <?php 
                                                echo date('d M Y', strtotime($invoice['due_date']));
                                                if ($invoice['days_overdue'] > 0) {
                                                    echo '<br><span class="badge badge-overdue">' . $invoice['days_overdue'] . ' days overdue</span>';
                                                }
                                                ?>
                                            </td>
                                            <td>
                                                <div class="fw-medium"><?php echo htmlspecialchars($invoice['patient_name']); ?></div>
                                                <small class="text-muted"><?php echo htmlspecialchars($invoice['patient_number']); ?></small>
                                            </td>
                                            <td>
                                                <?php 
                                                $billToColors = [
                                                    'PATIENT' => 'primary',
                                                    'INSURANCE' => 'info',
                                                    'CORPORATE' => 'warning'
                                                ];
                                                $color = $billToColors[$invoice['bill_to']] ?? 'secondary';
                                                echo '<span class="badge bg-' . $color . '">' . $invoice['bill_to'] . '</span>';
                                                if ($invoice['bill_to'] == 'INSURANCE' && $invoice['provider_name']) {
                                                    echo '<br><small class="text-muted">' . htmlspecialchars($invoice['provider_name']) . '</small>';
                                                }
                                                ?>
                                            </td>
                                            <td class="fw-medium">KES <?php echo number_format($invoice['total_amount'], 2); ?></td>
                                            <td class="text-success">KES <?php echo number_format($invoice['amount_paid'], 2); ?></td>
                                            <td>
                                                <strong class="<?php echo $invoice['days_overdue'] > 0 ? 'text-danger' : 'text-warning'; ?>">
                                                    KES <?php echo number_format($invoice['balance'], 2); ?>
                                                </strong>
                                            </td>
                                            <td>
                                                <?php
                                                $statusColors = [
                                                    'SENT' => 'warning',
                                                    'PARTIAL_PAYMENT' => 'info',
                                                    'INSURANCE_PENDING' => 'secondary'
                                                ];
                                                $color = $statusColors[$invoice['status']] ?? 'secondary';
                                                echo '<span class="badge bg-' . $color . '">' . str_replace('_', ' ', $invoice['status']) . '</span>';
                                                ?>
                                            </td>
                                            <td>
                                                <?php
                                                if ($invoice['bill_to'] == 'PATIENT') {
                                                    if ($invoice['etims_submitted']) {
                                                        echo '<span class="badge bg-success" title="Submitted to eTIMS"><i class="ri-shield-check-line"></i> eTIMS</span>';
                                                        if ($invoice['etims_invoice_number']) {
                                                            echo '<br><small class="text-muted">' . htmlspecialchars($invoice['etims_invoice_number']) . '</small>';
                                                        }
                                                    } else {
                                                        $etimsStatus = $invoice['etims_status'] ?? null;
                                                        if ($etimsStatus == 'pending') {
                                                            echo '<span class="badge bg-warning">Pending</span>';
                                                        } elseif ($etimsStatus == 'failed') {
                                                            echo '<span class="badge bg-danger">Failed</span>';
                                                        } else {
                                                            echo '<span class="badge bg-secondary">Not Sent</span>';
                                                        }
                                                    }
                                                } else {
                                                    echo '<span class="text-muted">N/A</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="record_payment.php?invoice_id=<?php echo $invoice['invoice_id']; ?>" 
                                                       class="btn btn-outline-success" title="Record Payment">
                                                        <i class="ri-money-dollar-circle-line"></i>
                                                    </a>
                                                    <?php if ($invoice['bill_to'] == 'PATIENT' && !$invoice['etims_submitted']): ?>
                                                    <button type="button" class="btn btn-outline-warning submit-etims" 
                                                            data-invoice-id="<?php echo $invoice['invoice_id']; ?>" 
                                                            title="Submit to eTIMS">
                                                        <i class="ri-shield-line"></i>
                                                    </button>
                                                    <?php endif; ?>
                                                    <button type="button" class="btn btn-outline-info send-reminder" 
                                                            data-invoice-id="<?php echo $invoice['invoice_id']; ?>" 
                                                            data-phone="<?php echo $invoice['phone_number']; ?>"
                                                            data-patient="<?php echo htmlspecialchars($invoice['patient_name']); ?>" 
                                                            title="Send Reminder">
                                                        <i class="ri-notification-line"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="12" class="text-center py-5">
                                                <div class="text-muted">
                                                    <i class="ri-file-list-3-line" style="font-size: 3rem;"></i>
                                                    <p class="mt-3 mb-0">No pending invoices found</p>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>

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

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize DataTable
        const table = $('#pendingInvoicesTable').DataTable({
            order: [[3, 'asc']], // Sort by due date
            pageLength: 25,
            columnDefs: [
                { orderable: false, targets: [0, 11] } // Disable sorting for checkbox and actions
            ],
            language: {
                search: "_INPUT_",
                searchPlaceholder: "Search invoices..."
            }
        });

        // Select all checkboxes
        $('#selectAll').on('change', function() {
            $('.invoice-checkbox').prop('checked', $(this).prop('checked'));
        });

        // Send single reminder
        $('.send-reminder').on('click', function() {
            const invoiceId = $(this).data('invoice-id');
            const phone = $(this).data('phone');
            const patient = $(this).data('patient');
            
            Swal.fire({
                title: 'Send Payment Reminder?',
                html: `Send SMS reminder to <strong>${patient}</strong><br>Phone: ${phone}`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '<i class="ri-send-plane-line me-1"></i> Send',
                confirmButtonColor: '#0ea5e9',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/send_payment_reminder.php',
                        method: 'POST',
                        data: { invoice_id: invoiceId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Sent!',
                                    text: 'Payment reminder sent successfully',
                                    timer: 2000
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message || 'Failed to send reminder'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Network error. Please try again.'
                            });
                        }
                    });
                }
            });
        });

        // Send bulk reminders
        $('#sendBulkReminders').on('click', function() {
            const selected = $('.invoice-checkbox:checked').length;
            
            if (selected === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No Selection',
                    text: 'Please select invoices to send reminders'
                });
                return;
            }
            
            Swal.fire({
                title: 'Send Bulk Reminders?',
                text: `Send reminders for ${selected} selected invoice(s)?`,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '<i class="ri-send-plane-line me-1"></i> Send All',
                confirmButtonColor: '#0ea5e9'
            }).then((result) => {
                if (result.isConfirmed) {
                    const invoiceIds = $('.invoice-checkbox:checked').map(function() {
                        return $(this).val();
                    }).get();
                    
                    $.ajax({
                        url: 'ajax/send_bulk_reminders.php',
                        method: 'POST',
                        data: { invoice_ids: invoiceIds },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Sent!',
                                    text: `${response.sent} reminder(s) sent successfully`,
                                    timer: 2000
                                });
                                $('.invoice-checkbox').prop('checked', false);
                                $('#selectAll').prop('checked', false);
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error',
                                    text: response.message || 'Failed to send reminders'
                                });
                            }
                        }
                    });
                }
            });
        });

        // Export to Excel
        $('#exportExcel').on('click', function() {
            window.location.href = 'ajax/export_pending_invoices.php';
        });

        // Print list
        $('#printList').on('click', function() {
            window.print();
        });
        
        // Submit invoice to eTIMS
        $('.submit-etims').on('click', function() {
            const invoiceId = $(this).data('invoice-id');
            const btn = $(this);
            
            Swal.fire({
                title: 'Submit to eTIMS?',
                text: 'This will register the invoice with KRA eTIMS system',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '<i class="ri-shield-check-line me-1"></i> Submit',
                confirmButtonColor: '#0ea5e9'
            }).then((result) => {
                if (result.isConfirmed) {
                    btn.prop('disabled', true).html('<i class="ri-loader-4-line spinner-border spinner-border-sm"></i>');
                    
                    $.ajax({
                        url: 'ajax/submit_invoice_to_etims.php',
                        method: 'POST',
                        data: { invoice_id: invoiceId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Submitted!',
                                    text: 'Invoice successfully submitted to eTIMS',
                                    timer: 2000
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Submission Failed',
                                    html: response.message || 'Failed to submit to eTIMS'
                                });
                                btn.prop('disabled', false).html('<i class="ri-shield-line"></i>');
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Network error. Please try again.'
                            });
                            btn.prop('disabled', false).html('<i class="ri-shield-line"></i>');
                        }
                    });
                }
            });
        });
    });
    </script>
</body>
</html>