<?php
/**
 * View Invoice Page
 * Display detailed invoice information including line items and payment history
 */

session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$invoice_id = isset($_GET['id']) ? intval($_GET['id']) : (isset($_GET['invoice_id']) ? intval($_GET['invoice_id']) : 0);

if (!$invoice_id) {
    header('Location: list_invoices.php');
    exit();
}

// Fetch invoice details
$invoice_sql = "SELECT 
    i.*,
    p.patient_id,
    p.patient_number,
    u.full_name as patient_name,
    u.gender,
    u.date_of_birth,
    u.phone_primary,
    u.phone_secondary,
    u.email,
    u.address,
    ip.provider_name as insurance_provider,
    creator.full_name as created_by_name,
    pv.visit_id,
    pv.registration_type,
    pv.smart_session_id
FROM invoices i
INNER JOIN patients p ON i.patient_id = p.patient_id
INNER 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 patient_visits pv ON i.visit_id = pv.visit_id
WHERE i.invoice_id = ?";

$stmt = $conn->prepare($invoice_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();

if (!$invoice) {
    die("Invoice not found");
}

// Calculate patient age
$age = null;
if ($invoice['date_of_birth']) {
    $dob = new DateTime($invoice['date_of_birth']);
    $now = new DateTime();
    $age = $now->diff($dob)->y;
}

// Fetch invoice line items
$items_sql = "SELECT 
    ii.*,
    s.service_name,
    s.service_code
FROM invoice_items ii
LEFT JOIN services s ON ii.reference_id = s.service_id AND ii.item_type = 'SERVICE'
WHERE ii.invoice_id = ?
ORDER BY ii.created_at, ii.item_id";

$stmt = $conn->prepare($items_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$items_result = $stmt->get_result();

// Fetch payment history
$payments_sql = "SELECT 
    pa.*,
    u.full_name as recorded_by_name,
    pm.payment_method_name
FROM payment_allocations pa
LEFT JOIN users u ON pa.recorded_by = u.user_id
LEFT JOIN payment_methods pm ON pa.payment_method_id = pm.payment_method_id
WHERE pa.invoice_id = ?
ORDER BY pa.payment_date DESC, pa.created_at DESC";

$stmt = $conn->prepare($payments_sql);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$payments_result = $stmt->get_result();

// Calculate days overdue
$days_overdue = 0;
if ($invoice['due_date'] && $invoice['balance'] > 0) {
    $due_date = new DateTime($invoice['due_date']);
    $now = new DateTime();
    if ($now > $due_date) {
        $days_overdue = $now->diff($due_date)->days;
    }
}

$page_title = "Invoice - " . htmlspecialchars($invoice['invoice_number']);
?>

<?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>
        .invoice-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 12px;
            margin-bottom: 2rem;
        }
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
            border: 1px solid #e2e8f0;
        }
        .info-card h5 {
            font-size: 1.125rem;
            font-weight: 600;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        .info-row:last-child {
            border-bottom: none;
        }
        .info-label {
            font-weight: 600;
            color: #64748b;
            min-width: 150px;
        }
        .info-value {
            color: #1e293b;
            flex: 1;
            text-align: right;
        }
        .items-table {
            width: 100%;
            border-collapse: collapse;
        }
        .items-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            border-bottom: 2px solid #e2e8f0;
        }
        .items-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
        }
        .items-table tr:hover {
            background: #f8fafc;
        }
        .text-end {
            text-align: right;
        }
        .summary-box {
            background: #f8fafc;
            padding: 1.5rem;
            border-radius: 8px;
            margin-top: 1rem;
        }
        .summary-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            font-size: 0.95rem;
        }
        .summary-row.total {
            font-size: 1.25rem;
            font-weight: 700;
            border-top: 2px solid #e2e8f0;
            margin-top: 0.5rem;
            padding-top: 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">
                    
                    <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="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_invoices.php">Invoices</a></li>
                                        <li class="breadcrumb-item active">View Invoice</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Invoice Header -->
                    <div class="invoice-header">
                        <div class="d-flex justify-content-between align-items-start flex-wrap">
                            <div>
                                <h2 class="text-white mb-2">Invoice #<?php echo htmlspecialchars($invoice['invoice_number']); ?></h2>
                                <div class="d-flex flex-wrap align-items-center gap-3">
                                    <span class="badge bg-<?php 
                                        echo $invoice['status'] == 'PAID' ? 'success' : 
                                            ($invoice['status'] == 'PARTIAL_PAYMENT' ? 'warning' : 
                                            ($invoice['status'] == 'OVERDUE' ? 'danger' : 'info')); 
                                    ?> fs-6">
                                        <?php echo htmlspecialchars($invoice['status']); ?>
                                    </span>
                                    <?php if ($invoice['bill_to']): ?>
                                    <span class="badge bg-secondary fs-6">
                                        Bill To: <?php echo htmlspecialchars($invoice['bill_to']); ?>
                                    </span>
                                    <?php endif; ?>
                                    <?php if ($days_overdue > 0): ?>
                                    <span class="badge bg-danger fs-6">
                                        <?php echo $days_overdue; ?> Days Overdue
                                    </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="text-end">
                                <a href="print_invoice.php?id=<?php echo $invoice_id; ?>" target="_blank" class="btn btn-light me-2">
                                    <i class="ri-printer-line me-1"></i> Print
                                </a>
                                <?php if ($invoice['status'] != 'PAID' && $invoice['balance'] > 0): ?>
                                <a href="collect_payment.php?invoice_id=<?php echo $invoice_id; ?>" class="btn btn-success me-2">
                                    <i class="ri-money-dollar-circle-line me-1"></i> Collect Payment
                                </a>
                                <?php endif; ?>
                                <a href="list_invoices.php" class="btn btn-light">
                                    <i class="ri-arrow-left-line me-1"></i> Back
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <!-- Patient Information -->
                        <div class="col-xl-6 mb-4">
                            <div class="info-card">
                                <h5><i class="ri-user-line me-2"></i>Patient Information</h5>
                                <div class="info-row">
                                    <span class="info-label">Name:</span>
                                    <span class="info-value"><strong><?php echo htmlspecialchars($invoice['patient_name']); ?></strong></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Patient Number:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($invoice['patient_number']); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Age / Gender:</span>
                                    <span class="info-value"><?php echo $age !== null ? $age . ' years' : 'N/A'; ?> / <?php echo htmlspecialchars($invoice['gender'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Phone:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($invoice['phone_primary'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Email:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($invoice['email'] ?? 'N/A'); ?></span>
                                </div>
                                <?php if ($invoice['address']): ?>
                                <div class="info-row">
                                    <span class="info-label">Address:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($invoice['address']); ?></span>
                                </div>
                                <?php endif; ?>
                                <?php if ($invoice['insurance_provider']): ?>
                                <div class="info-row">
                                    <span class="info-label">Insurance:</span>
                                    <span class="info-value">
                                        <?php echo htmlspecialchars($invoice['insurance_provider']); ?>
                                        <?php if ($invoice['insurance_claim_number']): ?>
                                            <small class="text-muted d-block">Claim: <?php echo htmlspecialchars($invoice['insurance_claim_number']); ?></small>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <?php endif; ?>
                                <?php if ($invoice['smart_session_id']): ?>
                                <div class="info-row">
                                    <span class="info-label">SMART Session:</span>
                                    <span class="info-value">
                                        <span class="badge bg-primary">SMART Enabled</span>
                                        <small class="text-muted d-block"><?php echo htmlspecialchars($invoice['smart_session_id']); ?></small>
                                    </span>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Invoice Information -->
                        <div class="col-xl-6 mb-4">
                            <div class="info-card">
                                <h5><i class="ri-file-list-3-line me-2"></i>Invoice Information</h5>
                                <div class="info-row">
                                    <span class="info-label">Invoice Number:</span>
                                    <span class="info-value"><strong><?php echo htmlspecialchars($invoice['invoice_number']); ?></strong></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Invoice Date:</span>
                                    <span class="info-value"><?php echo date('M d, Y', strtotime($invoice['invoice_date'])); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Due Date:</span>
                                    <span class="info-value">
                                        <?php echo date('M d, Y', strtotime($invoice['due_date'])); ?>
                                        <?php if ($days_overdue > 0): ?>
                                            <span class="badge bg-danger ms-2"><?php echo $days_overdue; ?> days overdue</span>
                                        <?php endif; ?>
                                    </span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Status:</span>
                                    <span class="info-value">
                                        <span class="badge bg-<?php 
                                            echo $invoice['status'] == 'PAID' ? 'success' : 
                                                ($invoice['status'] == 'PARTIAL_PAYMENT' ? 'warning' : 
                                                ($invoice['status'] == 'OVERDUE' ? 'danger' : 'info')); 
                                        ?>">
                                            <?php echo htmlspecialchars($invoice['status']); ?>
                                        </span>
                                    </span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Subtotal:</span>
                                    <span class="info-value">KES <?php echo number_format($invoice['subtotal'] ?? 0, 2); ?></span>
                                </div>
                                <?php if ($invoice['tax_amount'] > 0): ?>
                                <div class="info-row">
                                    <span class="info-label">Tax:</span>
                                    <span class="info-value">KES <?php echo number_format($invoice['tax_amount'], 2); ?></span>
                                </div>
                                <?php endif; ?>
                                <?php if ($invoice['discount_amount'] > 0): ?>
                                <div class="info-row">
                                    <span class="info-label">Discount:</span>
                                    <span class="info-value text-success">-KES <?php echo number_format($invoice['discount_amount'], 2); ?></span>
                                </div>
                                <?php endif; ?>
                                <div class="info-row">
                                    <span class="info-label">Total Amount:</span>
                                    <span class="info-value"><strong>KES <?php echo number_format($invoice['total_amount'], 2); ?></strong></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Amount Paid:</span>
                                    <span class="info-value text-success">KES <?php echo number_format($invoice['amount_paid'] ?? 0, 2); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Balance:</span>
                                    <span class="info-value">
                                        <strong class="text-<?php echo $invoice['balance'] > 0 ? 'danger' : 'success'; ?>">
                                            KES <?php echo number_format($invoice['balance'], 2); ?>
                                        </strong>
                                    </span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Created By:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($invoice['created_by_name'] ?? 'N/A'); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Invoice Items -->
                    <div class="info-card">
                        <h5><i class="ri-list-check me-2"></i>Invoice Items</h5>
                        <div class="table-responsive">
                            <table class="items-table">
                                <thead>
                                    <tr>
                                        <th>#</th>
                                        <th>Description</th>
                                        <th>Type</th>
                                        <th class="text-end">Quantity</th>
                                        <th class="text-end">Unit Price</th>
                                        <th class="text-end">Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if ($items_result->num_rows > 0): ?>
                                        <?php 
                                        $row_num = 1;
                                        $items_total = 0;
                                        while($item = $items_result->fetch_assoc()): 
                                            $line_total = floatval($item['total_price'] ?? ($item['line_total'] ?? ($item['unit_price'] * $item['quantity'])));
                                            $items_total += $line_total;
                                        ?>
                                        <tr>
                                            <td><?php echo $row_num++; ?></td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($item['description'] ?? $item['service_name'] ?? 'N/A'); ?></strong>
                                                <?php if ($item['service_code']): ?>
                                                    <br><small class="text-muted">Code: <?php echo htmlspecialchars($item['service_code']); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-secondary"><?php echo htmlspecialchars($item['item_type'] ?? 'GENERAL'); ?></span>
                                            </td>
                                            <td class="text-end"><?php echo number_format($item['quantity'], 2); ?></td>
                                            <td class="text-end">KES <?php echo number_format($item['unit_price'], 2); ?></td>
                                            <td class="text-end"><strong>KES <?php echo number_format($line_total, 2); ?></strong></td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="6" class="text-center py-4 text-muted">No items found</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="summary-box">
                            <div class="summary-row">
                                <span>Subtotal:</span>
                                <span>KES <?php echo number_format($invoice['subtotal'] ?? $items_total, 2); ?></span>
                            </div>
                            <?php if ($invoice['tax_amount'] > 0): ?>
                            <div class="summary-row">
                                <span>Tax:</span>
                                <span>KES <?php echo number_format($invoice['tax_amount'], 2); ?></span>
                            </div>
                            <?php endif; ?>
                            <?php if ($invoice['discount_amount'] > 0): ?>
                            <div class="summary-row">
                                <span>Discount:</span>
                                <span class="text-success">-KES <?php echo number_format($invoice['discount_amount'], 2); ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="summary-row total">
                                <span>Total Amount:</span>
                                <span>KES <?php echo number_format($invoice['total_amount'], 2); ?></span>
                            </div>
                            <div class="summary-row">
                                <span>Amount Paid:</span>
                                <span class="text-success">KES <?php echo number_format($invoice['amount_paid'] ?? 0, 2); ?></span>
                            </div>
                            <div class="summary-row total">
                                <span>Balance:</span>
                                <span class="text-<?php echo $invoice['balance'] > 0 ? 'danger' : 'success'; ?>">
                                    KES <?php echo number_format($invoice['balance'], 2); ?>
                                </span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Payment History -->
                    <?php if ($payments_result->num_rows > 0): ?>
                    <div class="info-card">
                        <h5><i class="ri-money-dollar-circle-line me-2"></i>Payment History</h5>
                        <div class="table-responsive">
                            <table class="items-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Payment Method</th>
                                        <th>Reference</th>
                                        <th>Recorded By</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($payment = $payments_result->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo date('M d, Y H:i', strtotime($payment['payment_date'])); ?></td>
                                        <td class="text-end"><strong>KES <?php echo number_format($payment['amount'], 2); ?></strong></td>
                                        <td><?php echo htmlspecialchars($payment['payment_method_name'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($payment['reference_number'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($payment['recorded_by_name'] ?? 'N/A'); ?></td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Action Buttons -->
                    <div class="row">
                        <div class="col-12">
                            <div class="d-flex gap-2">
                                <a href="list_invoices.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-1"></i> Back to Invoices
                                </a>
                                <a href="print_invoice.php?id=<?php echo $invoice_id; ?>" target="_blank" class="btn btn-primary">
                                    <i class="ri-printer-line me-1"></i> Print Invoice
                                </a>
                                <?php if ($invoice['status'] != 'PAID' && $invoice['balance'] > 0): ?>
                                <a href="collect_payment.php?invoice_id=<?php echo $invoice_id; ?>" class="btn btn-success">
                                    <i class="ri-money-dollar-circle-line me-1"></i> Collect Payment
                                </a>
                                <?php endif; ?>
                                <?php if ($invoice['status'] == 'DRAFT'): ?>
                                <a href="edit_invoice.php?id=<?php echo $invoice_id; ?>" class="btn btn-warning">
                                    <i class="ri-edit-line me-1"></i> Edit Invoice
                                </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                </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/js/app.js"></script>
</body>
</html>
