(<?php
session_start();
include('../db_connect.php');

// Check if an admin is logged in
if (!isset($_SESSION['admin_id'])) {
    header("Location: ../admin_login.php");
    exit();
}

// Function to generate CSRF token
function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
}

// Function to validate CSRF token
function validateCsrfToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Generate CSRF token
generateCsrfToken();

// Handle invoice deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_invoice'])) {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'])) {
        $error_message = "Invalid CSRF token.";
    } else {
        // Validate invoice_id
        if (isset($_POST['invoice_id']) && is_numeric($_POST['invoice_id'])) {
            $invoice_id = intval($_POST['invoice_id']);

            // Start transaction
            $pdo->beginTransaction();

            try {
                // Delete related invoice services
                $sql_delete_services = "DELETE FROM invoice_services WHERE invoice_id = :invoice_id";
                $stmt_delete_services = $pdo->prepare($sql_delete_services);
                $stmt_delete_services->bindParam(':invoice_id', $invoice_id, PDO::PARAM_INT);
                $stmt_delete_services->execute();

                // Delete the invoice
                $sql_delete_invoice = "DELETE FROM invoices WHERE id = :invoice_id";
                $stmt_delete_invoice = $pdo->prepare($sql_delete_invoice);
                $stmt_delete_invoice->bindParam(':invoice_id', $invoice_id, PDO::PARAM_INT);
                $stmt_delete_invoice->execute();

                // Commit transaction
                $pdo->commit();

                $success_message = "Invoice (ID: $invoice_id) deleted successfully.";
            } catch (Exception $e) {
                // Rollback transaction on error
                $pdo->rollBack();
                $error_message = "Error deleting invoice: " . $e->getMessage();
            }
        } else {
            $error_message = "Invalid Invoice ID.";
        }
    }
}

// Fetch all invoices with patient information
$sql = "SELECT 
            i.id, 
            i.patient_id, 
            p.name AS patient_name, 
            i.total_amount, 
            i.invoice_date, 
            i.notes, 
            i.discount,
            i.tax
        FROM invoices i 
        JOIN patients p ON i.patient_id = p.id 
        ORDER BY i.invoice_date DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$invoices = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch services for each invoice and append to the invoice data
foreach ($invoices as &$invoice) {
    $invoice['services'] = fetchInvoiceServices($invoice['id'], $pdo);
}
unset($invoice);

// Function to fetch services for a specific invoice
function fetchInvoiceServices($invoice_id, $pdo) {
    $sql_services = "SELECT isrv.id, isrv.service_id, s.service_name, s.service_price, isrv.cost 
                    FROM invoice_services isrv 
                    JOIN services s ON isrv.service_id = s.service_id 
                    WHERE isrv.invoice_id = :invoice_id";
    $stmt_services = $pdo->prepare($sql_services);
    $stmt_services->bindParam(':invoice_id', $invoice_id, PDO::PARAM_INT);
    $stmt_services->execute();
    return $stmt_services->fetchAll(PDO::FETCH_ASSOC);
}
?>

<?php include('../includes/header.php'); ?>

<!-- Custom Styles -->
<style>
    :root {
        --invoice-primary-color: #4F3F02; /* Dark Brown */
        --invoice-secondary-color: #D1C287; /* Light Golden */
        --invoice-background-color: #f8f9fa; /* Light Grey */
        --invoice-text-color: #333333; /* Dark Grey */
        --invoice-error-color: #dc3545; /* Red */
        --invoice-success-color: #28a745; /* Green */
        --invoice-input-border-color: #ced4da; /* Light Grey */
        --invoice-input-focus-border-color: var(--invoice-primary-color);
        --invoice-button-hover-color: var(--invoice-secondary-color);
        --invoice-border-radius: 8px;
        --invoice-box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        --invoice-font-size-base: 0.9rem;
        --invoice-font-size-small: 0.8rem;
    }

    body {
        font-family: 'Roboto', sans-serif;
        line-height: 1.6;
        background-color: var(--invoice-background-color);
        color: var(--invoice-text-color);
        margin: 0;
        padding: 0;
    }

    /* Invoice Container */
    .invoice-container {
        max-width: 1200px;
        margin: 40px auto;
        padding: 30px;
        background-color: white;
        border-radius: var(--invoice-border-radius);
        box-shadow: var(--invoice-box-shadow);
    }

    /* Dashboard Header */
    .invoice-dashboard-header {
        background: linear-gradient(135deg, var(--invoice-primary-color) 0%, var(--invoice-secondary-color) 100%);
        color: white;
        padding: 20px;
        text-align: center;
        border-radius: var(--invoice-border-radius) var(--invoice-border-radius) 0 0;
        position: relative;
        overflow: hidden;
    }

    .invoice-dashboard-header h1 {
        margin: 0;
        font-size: 2.5rem;
        font-weight: 700;
        letter-spacing: 1px;
    }

    .invoice-dashboard-header::before {
        content: "";
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 70%);
        transform: rotate(30deg);
    }

    /* Table Styling */
    .invoice-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }

    .invoice-table thead th {
        background-color: var(--invoice-primary-color);
        color: #ffffff;
        padding: 15px;
        font-weight: 600;
        text-transform: uppercase;
        font-size: var(--invoice-font-size-small);
        cursor: pointer;
        position: relative;
    }

    .invoice-table thead th.sortable::after {
        content: '';
        position: absolute;
        right: 10px;
        top: 50%;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 5px solid white;
        transform: translateY(-50%);
        transition: all 0.3s ease;
    }

    .invoice-table thead th.sortable.desc::after {
        border-top: none;
        border-bottom: 5px solid white;
    }

    .invoice-table tbody tr {
        transition: background-color 0.3s ease;
    }

    .invoice-table tbody tr:hover {
        background-color: rgba(209, 194, 135, 0.2);
    }

    .invoice-table tbody td {
        padding: 12px 15px;
        vertical-align: middle;
        font-size: var(--invoice-font-size-small);
        border-bottom: 1px solid #e0e0e0;
    }

    /* Button Styling */
    .invoice-btn {
        border-radius: var(--invoice-border-radius);
        transition: all 0.3s ease;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        padding: 8px 16px;
        font-size: var(--invoice-font-size-small);
    }

    .invoice-btn-primary {
        background-color: var(--invoice-primary-color);
        border: none;
        color: #ffffff;
    }

    .invoice-btn-primary:hover, .invoice-btn-primary:focus {
        background-color: var(--invoice-secondary-color);
        color: var(--invoice-primary-color);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .invoice-btn-outline-secondary {
        background-color: transparent;
        border: 1px solid var(--invoice-primary-color);
        color: var(--invoice-primary-color);
    }

    .invoice-btn-outline-secondary:hover, .invoice-btn-outline-secondary:focus {
        background-color: var(--invoice-primary-color);
        color: #ffffff;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    /* Alerts */
    .invoice-alert {
        margin-top: 20px;
        border-radius: var(--invoice-border-radius);
        border: none;
        box-shadow: var(--invoice-box-shadow);
        padding: 15px;
        font-size: 1rem;
    }

    .invoice-alert-success {
        background-color: var(--invoice-success-color);
        color: #ffffff;
    }

    .invoice-alert-danger {
        background-color: var(--invoice-error-color);
        color: #ffffff;
    }

    /* Action Buttons */
    .invoice-action-btn {
        margin-right: 5px;
        font-size: 0.8rem;
    }

    /* Responsive Table */
    @media (max-width: 768px) {
        .invoice-table thead {
            display: none;
        }

        .invoice-table, .invoice-table tbody, .invoice-table tr, .invoice-table td {
            display: block;
            width: 100%;
        }

        .invoice-table tr {
            margin-bottom: 15px;
        }

        .invoice-table td {
            text-align: right;
            padding-left: 50%;
            position: relative;
            border-bottom: none;
        }

        .invoice-table td::before {
            content: attr(data-label);
            position: absolute;
            left: 15px;
            width: 45%;
            padding-right: 10px;
            white-space: nowrap;
            text-align: left;
            font-weight: 700;
        }

        .invoice-btn-group {
            display: flex;
            flex-direction: column;
        }

        .invoice-btn-group .invoice-action-btn {
            margin-bottom: 5px;
            width: 100%;
        }
    }

    /* Additional Styling for Toggle Details */
    .invoice-details {
        background-color: #f1f1f1;
        padding: 15px;
        border-radius: var(--invoice-border-radius);
        margin-top: 10px;
    }
</style>

<div class="invoice-container">
    <!-- Dashboard Header -->
    <div class="invoice-dashboard-header">
        <h1>Patient Invoices</h1>
    </div>

    <!-- Success and Error Messages -->
    <?php if (isset($success_message)): ?>
        <div class="invoice-alert invoice-alert-success alert alert-dismissible fade show" role="alert" style="display: block;">
            <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($error_message)): ?>
        <div class="invoice-alert invoice-alert-danger alert alert-dismissible fade show" role="alert" style="display: block;">
            <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- Action Buttons -->
    <div class="d-flex justify-content-between mb-3 flex-wrap">
        <div class="mb-2">
            <a href="../admin_dashboard.php" class="invoice-btn invoice-btn-outline-secondary me-2">Back to Dashboard</a>
            <a href="create_invoice.php" class="invoice-btn invoice-btn-primary">Create an Invoice</a>
        </div>
        <div class="mb-2">
            <a href="services.php" class="invoice-btn invoice-btn-outline-secondary me-2">Our Services</a>
            <!-- Removed 'Download All PDFs' Button as per request -->
        </div>
    </div>

    <!-- Invoices Table -->
    <?php if (empty($invoices)): ?>
        <p>No invoices found.</p>
    <?php else: ?>
        <div class="table-responsive">
            <table id="invoiceTable" class="invoice-table table table-striped table-hover align-middle">
                <thead>
                    <tr>
                        <th class="sortable">Invoice ID</th>
                        <th class="sortable">Patient ID</th>
                        <th class="sortable">Patient Name</th>
                        <th>Services</th>
                        <th class="sortable">Subtotal ($)</th>
                        <th class="sortable">Total Amount ($)</th>
                        <th class="sortable">Invoice Date</th>
                        <th class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($invoices as $invoice): ?>
                    <tr>
                        <td data-label="Invoice ID"><?php echo htmlspecialchars($invoice['id']); ?></td>
                        <td data-label="Patient ID"><?php echo htmlspecialchars($invoice['patient_id']); ?></td>
                        <td data-label="Patient Name"><?php echo htmlspecialchars($invoice['patient_name']); ?></td>
                        <td data-label="Services">
                            <?php 
                                if (!empty($invoice['services'])) {
                                    $service_names = array_map(function($service) {
                                        return htmlspecialchars($service['service_name']);
                                    }, $invoice['services']);
                                    echo implode(", ", $service_names);
                                } else {
                                    echo "No services";
                                }
                            ?>
                        </td>
                        <td data-label="Subtotal ($)"><?php echo '$' . number_format(array_sum(array_column($invoice['services'], 'cost')), 2); ?></td>
                        <td data-label="Total Amount ($)">
                            <?php
                                // Calculate Total Amount: (Subtotal - Discount) + Tax Amount
                                $subtotal = array_sum(array_column($invoice['services'], 'cost'));
                                $discount = isset($invoice['discount']) ? $invoice['discount'] : 0;
                                $tax_rate = isset($invoice['tax']) ? $invoice['tax'] : 0;
                                $taxable_amount = ($subtotal - $discount);
                                $tax_amount = ($taxable_amount * ($tax_rate / 100));
                                $total_amount = ($taxable_amount + $tax_amount);
                                echo '$' . number_format($total_amount, 2);
                            ?>
                        </td>
                        <td data-label="Invoice Date"><?php echo htmlspecialchars(date("F j, Y", strtotime($invoice['invoice_date']))); ?></td>
                        <td data-label="Actions" class="text-center">
                            <div class="invoice-btn-group">
                                <button class="invoice-btn invoice-btn-outline-secondary invoice-action-btn toggle-details" data-invoice-id="<?php echo htmlspecialchars($invoice['id']); ?>">
                                    <i class="fas fa-plus-circle me-1"></i>Details
                                </button>
                                <a href="view_invoice.php?invoice_id=<?php echo urlencode($invoice['id']); ?>" class="invoice-btn invoice-btn-outline-secondary invoice-action-btn">View</a>
                                <a href="edit_invoice.php?invoice_id=<?php echo urlencode($invoice['id']); ?>" class="invoice-btn invoice-btn-outline-secondary invoice-action-btn">Edit</a>
                                <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this invoice?');">
                                    <input type="hidden" name="invoice_id" value="<?php echo htmlspecialchars($invoice['id']); ?>">
                                    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                                    <button type="submit" name="delete_invoice" class="invoice-btn invoice-btn-outline-secondary invoice-action-btn">Delete</button>
                                </form>
                                <a href="download_invoice.php?invoice_id=<?php echo urlencode($invoice['id']); ?>" class="invoice-btn invoice-btn-primary invoice-action-btn">Download PDF</a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<?php include('../includes/footer.php'); ?>

<!-- JavaScript for DataTables and Enhanced Functionality -->
<script>
    $(document).ready(function() {
        // Initialize DataTables
        var table = $('#invoiceTable').DataTable({
            "paging": true,
            "lengthMenu": [10, 25, 50, 100],
            "ordering": true,
            "info": true,
            "searching": true,
            "order": [[6, "desc"]], // Order by Invoice Date descending by default
            "columnDefs": [
                { "orderable": false, "targets": [3, 7] }, // Disable ordering on Services and Actions columns
                { "className": "dt-center", "targets": [7] }, // Center align the Actions column
                { "type": "num", "targets": [0,1,4,5] }, // Ensure numeric sorting for these columns
                { "type": "date", "targets": [6] } // Ensure date sorting for Invoice Date
            ],
            "responsive": true
        });

        // Handle toggle-details using DataTables Child Rows
        $('.toggle-details').on('click', function(){
            var btn = $(this);
            var invoiceId = btn.attr('data-invoice-id');
            var tr = btn.closest('tr');
            var row = table.row(tr);

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
                btn.html('<i class="fas fa-plus-circle me-1"></i>Details');
            }
            else {
                // Open this row
                // Find the invoice data
                var invoiceData = <?php echo json_encode($invoices); ?>;
                var currentInvoice = invoiceData.find(function(inv) { return inv.id == invoiceId; });

                if (currentInvoice) {
                    // Calculate required data
                    var subtotal = parseFloat(currentInvoice.services.reduce(function(acc, service) {
                        return acc + parseFloat(service.cost);
                    }, 0)).toFixed(2);
                    var discount = parseFloat(currentInvoice.discount).toFixed(2);
                    var tax_rate = parseFloat(currentInvoice.tax).toFixed(2);
                    var taxable_amount = (parseFloat(subtotal) - parseFloat(discount)).toFixed(2);
                    var tax_amount = (parseFloat(taxable_amount) * (parseFloat(tax_rate) / 100)).toFixed(2);
                    var total_amount = (parseFloat(taxable_amount) + parseFloat(tax_amount)).toFixed(2);
                    var notes = currentInvoice.notes ? currentInvoice.notes : 'N/A';

                    // Fetch services
                    var services_html = '';
                    if (currentInvoice.services.length > 0) {
                        services_html += '<ul>';
                        currentInvoice.services.forEach(function(service){
                            services_html += '<li>' + service.service_name + ' - $' + parseFloat(service.cost).toFixed(2) + '</li>';
                        });
                        services_html += '</ul>';
                    } else {
                        services_html += '<p>No services associated with this invoice.</p>';
                    }

                    // Create child row content
                    var detailsHtml = '<div class="invoice-details">' +
                                      '<h5>Invoice Details</h5>' +
                                      '<p><strong>Subtotal:</strong> $' + subtotal + '</p>' +
                                      '<p><strong>Discount:</strong> $' + discount + '</p>' +
                                      '<p><strong>Taxable Amount:</strong> $' + taxable_amount + '</p>' +
                                      '<p><strong>Tax Rate:</strong> ' + tax_rate + '%</p>' +
                                      '<p><strong>Tax Amount:</strong> $' + tax_amount + '</p>' +
                                      '<p><strong>Total Amount:</strong> $' + total_amount + '</p>' +
                                      '<h6>Services:</h6>' +
                                      services_html +
                                      '<h6>Notes:</h6>' +
                                      '<p>' + nl2br_html(notes) + '</p>' +
                                      '</div>';

                    row.child(detailsHtml).show();
                    tr.addClass('shown');
                    btn.html('<i class="fas fa-minus-circle me-1"></i>Details');
                } else {
                    alert("Invoice details not found.");
                }
            }
        });

        // Function to convert newlines to <br>
        function nl2br_html(str) {
            return str.replace(/\r\n|\r|\n/g, '<br>');
        }

        // Auto-dismiss alerts after 5 seconds
        setTimeout(function () {
            var alertNode = document.querySelector('.invoice-alert');
            if (alertNode) {
                var alert = new bootstrap.Alert(alertNode);
                alert.close();
            }
        }, 5000);
    });
</script>) in this codes, change the table fully and remove details button in action col and add more codes to be better and type full codes with inline codes css