<?php
session_start();
include 'layouts/dbconn.php';
include 'includes/menu_config.php';

// Set timezone
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

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

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

// Handle AJAX requests for actions
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'record_payment':
            $payment_date = $_POST['payment_date'];
            $amount = floatval($_POST['amount']);
            $payment_method = $_POST['payment_method'];
            $reference_number = $_POST['reference_number'] ?? '';
            $notes = $_POST['notes'] ?? '';
            
            // Insert payment record
            $payment_sql = "INSERT INTO payments (invoice_id, customer_id, payment_date, payment_method, amount, reference_number, notes, status, created_by)
                           SELECT ?, customer_id, ?, ?, ?, ?, ?, 'CONFIRMED', ?
                           FROM invoices WHERE invoice_id = ?";
            $stmt = $conn->prepare($payment_sql);
            $stmt->bind_param("issdssii", $invoice_id, $payment_date, $payment_method, $amount, $reference_number, $notes, $user_id, $invoice_id);
            
            if ($stmt->execute()) {
                // Update invoice paid amount and balance
                $update_sql = "UPDATE invoices SET 
                              paid_amount = paid_amount + ?, 
                              balance_amount = total_amount - (paid_amount + ?),
                              status = CASE 
                                  WHEN total_amount <= (paid_amount + ?) THEN 'PAID'
                                  WHEN paid_amount + ? > 0 THEN 'PARTIAL'
                                  ELSE status
                              END,
                              updated_by = ?, updated_at = NOW()
                              WHERE invoice_id = ?";
                $stmt_update = $conn->prepare($update_sql);
                $stmt_update->bind_param("ddddii", $amount, $amount, $amount, $amount, $user_id, $invoice_id);
                $stmt_update->execute();
                
                echo json_encode(['success' => true, 'message' => 'Payment recorded successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to record payment']);
            }
            break;
            
        case 'send_invoice':
            $send_method = $_POST['method'];
            $message = $_POST['message'] ?? '';
            
            // In a real implementation, you would integrate with email/SMS services
            // For now, we'll just log the action
            $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, new_values) 
                       VALUES (?, 'SEND', 'invoices', ?, ?)";
            $stmt_log = $conn->prepare($log_sql);
            $details = json_encode(['method' => $send_method, 'message' => $message]);
            $stmt_log->bind_param("iss", $user_id, $invoice_id, $details);
            
            if ($stmt_log->execute()) {
                // Update invoice status to SENT if it's currently DRAFT
                $conn->query("UPDATE invoices SET status = 'SENT' WHERE invoice_id = $invoice_id AND status = 'DRAFT'");
                echo json_encode(['success' => true, 'message' => 'Invoice sent successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to send invoice']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit();
}

// Fetch invoice details with customer information
$sql_invoice = "
    SELECT 
        i.*,
        c.customer_code,
        c.company_name,
        c.first_name,
        c.last_name,
        c.customer_type,
        c.email,
        c.phone,
        c.address_line1,
        c.address_line2,
        c.city,
        c.state,
        c.postal_code,
        c.country,
        c.tax_id,
        creator.full_name as created_by_name
    FROM invoices i
    LEFT JOIN customers c ON i.customer_id = c.customer_id
    LEFT JOIN users creator ON i.created_by = creator.user_id
    WHERE i.invoice_id = ?";

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

if (!$invoice) {
    header('Location: invoices.php?error=Invoice not found');
    exit();
}

// Fetch invoice items with shipment details
$sql_items = "
    SELECT 
        ii.*,
        s.tracking_number,
        s.booking_date,
        s.sender_name,
        s.receiver_name,
        ol.location_name as origin_location,
        dl.location_name as destination_location
    FROM invoice_items ii
    LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id
    LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
    LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
    WHERE ii.invoice_id = ?
    ORDER BY ii.item_id";

$stmt_items = $conn->prepare($sql_items);
$stmt_items->bind_param("i", $invoice_id);
$stmt_items->execute();
$invoice_items = $stmt_items->get_result();

// Fetch payment history
$sql_payments = "
    SELECT 
        p.*,
        u.full_name as processed_by_name
    FROM payments p
    LEFT JOIN users u ON p.created_by = u.user_id
    WHERE p.invoice_id = ?
    ORDER BY p.created_at DESC";

$stmt_payments = $conn->prepare($sql_payments);
$stmt_payments->bind_param("i", $invoice_id);
$stmt_payments->execute();
$payments = $stmt_payments->get_result();

// Calculate overdue status
$is_overdue = ($invoice['status'] != 'PAID' && $invoice['due_date'] < date('Y-m-d'));
$days_overdue = $is_overdue ? (int)((strtotime(date('Y-m-d')) - strtotime($invoice['due_date'])) / 86400) : 0;

// Fetch company settings for PDF generation
$sql_settings = "SELECT setting_key, setting_value FROM settings 
                 WHERE setting_key IN ('company_name', 'company_address', 'company_phone', 'company_email')";
$settings_result = $conn->query($sql_settings);
$company_settings = [];
while ($setting = $settings_result->fetch_assoc()) {
    $company_settings[$setting['setting_key']] = $setting['setting_value'];
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Invoice #' . $invoice['invoice_number'])); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .invoice-wrapper {
            background: #f8f9fa;
            min-height: 100vh;
            padding: 2rem 0;
        }
        
        .invoice-container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .invoice-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 3rem 2rem;
            position: relative;
            overflow: hidden;
        }
        
        .invoice-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 100%;
            height: 200%;
            background: rgba(255,255,255,0.1);
            transform: rotate(45deg);
        }
        
        .invoice-header-content {
            position: relative;
            z-index: 2;
        }
        
        .invoice-number {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .invoice-status {
            display: inline-block;
            padding: 0.5rem 1.5rem;
            background: rgba(255,255,255,0.2);
            border-radius: 25px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .overdue-alert {
            background: linear-gradient(45deg, #ff6b6b, #ee5a24);
            color: white;
            padding: 1rem;
            margin: -3rem -2rem 2rem -2rem;
            position: relative;
            z-index: 3;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.02); }
            100% { transform: scale(1); }
        }
        
        .invoice-body {
            padding: 2rem;
        }
        
        .section-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            border: 1px solid #e9ecef;
        }
        
        .section-title {
            font-size: 1.25rem;
            font-weight: 600;
            color: #2d3436;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .customer-info {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .customer-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1.5rem;
        }
        
        .customer-details h4 {
            margin: 0 0 0.25rem 0;
            color: #2d3436;
        }
        
        .customer-details p {
            margin: 0.25rem 0;
            color: #636e72;
        }
        
        .invoice-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .invoice-table th {
            background: #667eea;
            color: white;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.875rem;
            letter-spacing: 0.05em;
        }
        
        .invoice-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f3f4;
        }
        
        .invoice-table tbody tr:hover {
            background: #f8f9fa;
        }
        
        .totals-section {
            background: white;
            padding: 1.5rem;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f3f4;
        }
        
        .total-row:last-child {
            border-bottom: none;
            font-size: 1.25rem;
            font-weight: 700;
            color: #2d3436;
            border-top: 2px solid #667eea;
            padding-top: 1rem;
        }
        
        .actions-sidebar {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            position: sticky;
            top: 2rem;
        }
        
        .action-btn {
            width: 100%;
            padding: 0.75rem 1rem;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            margin-bottom: 0.5rem;
            transition: all 0.3s ease;
            justify-content: center;
        }
        
        .btn-primary { background: #667eea; color: white; }
        .btn-success { background: #00b894; color: white; }
        .btn-warning { background: #fdcb6e; color: #2d3436; }
        .btn-danger { background: #e84393; color: white; }
        .btn-secondary { background: #636e72; color: white; }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .payment-timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .payment-timeline::before {
            content: '';
            position: absolute;
            left: 0.75rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #dee2e6;
        }
        
        .payment-item {
            position: relative;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
        }
        
        .payment-item::before {
            content: '';
            position: absolute;
            left: -1.5rem;
            top: 1rem;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #00b894;
            border: 3px solid white;
        }
        
        .amount-highlight {
            font-size: 2rem;
            font-weight: 700;
            color: #667eea;
        }
        
        @media print {
            .no-print,
            .actions-sidebar {
                display: none !important;
            }
            
            .invoice-wrapper {
                background: white;
                padding: 0;
            }
            
            .invoice-container {
                max-width: none;
                box-shadow: none;
                border-radius: 0;
            }
            
            .invoice-header {
                background: #667eea !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
        
        @media (max-width: 768px) {
            .invoice-wrapper {
                padding: 1rem;
            }
            
            .invoice-header {
                padding: 2rem 1rem;
                text-align: center;
            }
            
            .invoice-number {
                font-size: 2rem;
            }
            
            .invoice-body {
                padding: 1rem;
            }
            
            .customer-info {
                flex-direction: column;
                text-align: center;
            }
            
            .actions-sidebar {
                position: relative;
                top: auto;
                margin-top: 2rem;
            }
            
            .amount-highlight {
                font-size: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="invoice-wrapper">
                    <div class="container-fluid">
                        
                        <div class="row">
                            <!-- Main Invoice Content -->
                            <div class="col-xl-8">
                                <div class="invoice-container">
                                    
                                    <!-- Invoice Header -->
                                    <div class="invoice-header">
                                        <?php if ($is_overdue): ?>
                                        <div class="overdue-alert">
                                            <div class="d-flex align-items-center">
                                                <i class="ri-alert-line fs-2 me-3"></i>
                                                <div>
                                                    <strong>OVERDUE INVOICE</strong>
                                                    <p class="mb-0">This invoice is <?php echo $days_overdue; ?> day(s) past due</p>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <div class="invoice-header-content">
                                            <div class="row align-items-center">
                                                <div class="col-md-8">
                                                    <div class="invoice-number">#<?php echo $invoice['invoice_number']; ?></div>
                                                    <div class="invoice-status"><?php echo $invoice['status']; ?></div>
                                                </div>
                                                <div class="col-md-4 text-md-end mt-3 mt-md-0">
                                                    <div class="amount-highlight">$<?php echo number_format($invoice['total_amount'], 2); ?></div>
                                                    <div style="opacity: 0.9;">
                                                        Due: <?php echo date('M j, Y', strtotime($invoice['due_date'])); ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Invoice Body -->
                                    <div class="invoice-body">
                                        
                                        <!-- Company & Customer Info -->
                                        <div class="row mb-4">
                                            <div class="col-md-6">
                                                <div class="section-card">
                                                    <div class="section-title">
                                                        <i class="ri-building-line"></i>
                                                        From
                                                    </div>
                                                    <h4><?php echo $company_settings['company_name'] ?? 'Your Company'; ?></h4>
                                                    <p><?php echo $company_settings['company_address'] ?? ''; ?></p>
                                                    <p><?php echo $company_settings['company_phone'] ?? ''; ?></p>
                                                    <p><?php echo $company_settings['company_email'] ?? ''; ?></p>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <div class="section-card">
                                                    <div class="section-title">
                                                        <i class="ri-user-line"></i>
                                                        Bill To
                                                    </div>
                                                    <div class="customer-info">
                                                        <div class="customer-avatar">
                                                            <?php 
                                                            if ($invoice['customer_type'] == 'CORPORATE') {
                                                                echo strtoupper(substr($invoice['company_name'] ?? 'C', 0, 2));
                                                            } else {
                                                                echo strtoupper(substr($invoice['first_name'] ?? 'I', 0, 1) . substr($invoice['last_name'] ?? 'N', 0, 1));
                                                            }
                                                            ?>
                                                        </div>
                                                        <div class="customer-details">
                                                            <h4>
                                                                <?php 
                                                                echo $invoice['customer_type'] == 'CORPORATE' 
                                                                    ? ($invoice['company_name'] ?? 'Company') 
                                                                    : ($invoice['first_name'] ?? 'Individual') . ' ' . ($invoice['last_name'] ?? ''); 
                                                                ?>
                                                            </h4>
                                                            <p><strong>Customer:</strong> <?php echo $invoice['customer_code']; ?></p>
                                                            <?php if ($invoice['email']): ?>
                                                            <p><strong>Email:</strong> <?php echo $invoice['email']; ?></p>
                                                            <?php endif; ?>
                                                            <?php if ($invoice['phone']): ?>
                                                            <p><strong>Phone:</strong> <?php echo $invoice['phone']; ?></p>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                    
                                                    <?php if ($invoice['address_line1']): ?>
                                                    <div class="mt-3">
                                                        <strong>Address:</strong><br>
                                                        <?php echo $invoice['address_line1']; ?><br>
                                                        <?php if ($invoice['address_line2']): echo $invoice['address_line2'] . '<br>'; endif; ?>
                                                        <?php echo $invoice['city']; ?><?php if ($invoice['state']): echo ', ' . $invoice['state']; endif; ?>
                                                        <?php if ($invoice['postal_code']): echo ' ' . $invoice['postal_code']; endif; ?><br>
                                                        <?php echo $invoice['country']; ?>
                                                    </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Invoice Details -->
                                        <div class="section-card mb-4">
                                            <div class="section-title">
                                                <i class="ri-calendar-line"></i>
                                                Invoice Details
                                            </div>
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <strong>Invoice Date:</strong><br>
                                                    <?php echo date('M j, Y', strtotime($invoice['invoice_date'])); ?>
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Due Date:</strong><br>
                                                    <span class="<?php echo $is_overdue ? 'text-danger' : ''; ?>">
                                                        <?php echo date('M j, Y', strtotime($invoice['due_date'])); ?>
                                                    </span>
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Payment Terms:</strong><br>
                                                    <?php echo $invoice['payment_terms']; ?> days
                                                </div>
                                                <div class="col-md-3">
                                                    <strong>Created By:</strong><br>
                                                    <?php echo $invoice['created_by_name']; ?>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Invoice Items -->
                                        <div class="mb-4">
                                            <div class="section-title">
                                                <i class="ri-list-check"></i>
                                                Items & Services
                                            </div>
                                            <table class="invoice-table">
                                                <thead>
                                                    <tr>
                                                        <th>Description</th>
                                                        <th width="100" class="text-center">Qty</th>
                                                        <th width="120" class="text-end">Unit Price</th>
                                                        <th width="120" class="text-end">Total</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php while ($item = $invoice_items->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <div>
                                                                <strong><?php echo htmlspecialchars($item['description']); ?></strong>
                                                                <?php if ($item['tracking_number']): ?>
                                                                <br><small class="text-muted">
                                                                    Tracking: <?php echo $item['tracking_number']; ?>
                                                                    <?php if ($item['origin_location'] && $item['destination_location']): ?>
                                                                    | <?php echo $item['origin_location']; ?> → <?php echo $item['destination_location']; ?>
                                                                    <?php endif; ?>
                                                                </small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </td>
                                                        <td class="text-center"><?php echo number_format($item['quantity'], 2); ?></td>
                                                        <td class="text-end">$<?php echo number_format($item['unit_price'], 2); ?></td>
                                                        <td class="text-end">$<?php echo number_format($item['line_total'], 2); ?></td>
                                                    </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>

                                        <!-- Totals -->
                                        <div class="row justify-content-end">
                                            <div class="col-md-6">
                                                <div class="totals-section">
                                                    <div class="total-row">
                                                        <span>Subtotal:</span>
                                                        <span>$<?php echo number_format($invoice['subtotal'], 2); ?></span>
                                                    </div>
                                                    <?php if ($invoice['tax_amount'] > 0): ?>
                                                    <div class="total-row">
                                                        <span>Tax (<?php echo $invoice['tax_rate']; ?>%):</span>
                                                        <span>$<?php echo number_format($invoice['tax_amount'], 2); ?></span>
                                                    </div>
                                                    <?php endif; ?>
                                                    <div class="total-row">
                                                        <span>Total Amount:</span>
                                                        <span>$<?php echo number_format($invoice['total_amount'], 2); ?></span>
                                                    </div>
                                                    <div class="total-row">
                                                        <span>Amount Paid:</span>
                                                        <span class="text-success">$<?php echo number_format($invoice['paid_amount'], 2); ?></span>
                                                    </div>
                                                    <div class="total-row">
                                                        <span>Balance Due:</span>
                                                        <span class="<?php echo $invoice['balance_amount'] > 0 ? 'text-warning' : 'text-success'; ?>">
                                                            $<?php echo number_format($invoice['balance_amount'], 2); ?>
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Notes -->
                                        <?php if ($invoice['notes']): ?>
                                        <div class="section-card mt-4">
                                            <div class="section-title">
                                                <i class="ri-file-text-line"></i>
                                                Notes & Terms
                                            </div>
                                            <p class="mb-0"><?php echo nl2br(htmlspecialchars($invoice['notes'])); ?></p>
                                        </div>
                                        <?php endif; ?>

                                    </div>
                                </div>
                            </div>

                            <!-- Actions Sidebar -->
                            <div class="col-xl-4 no-print">
                                <div class="actions-sidebar">
                                    <h5 class="mb-3">
                                        <i class="ri-tools-line me-2"></i>Actions
                                    </h5>
                                    
                                    <a href="edit_invoice.php?id=<?php echo $invoice_id; ?>" class="action-btn btn-primary">
                                        <i class="ri-edit-line"></i>Edit Invoice
                                    </a>
                                    
                                    <button onclick="sendInvoice()" class="action-btn btn-success">
                                        <i class="ri-mail-send-line"></i>Send Invoice
                                    </button>
                                    
                                    <button onclick="recordPayment()" class="action-btn btn-warning">
                                        <i class="ri-money-dollar-circle-line"></i>Record Payment
                                    </button>
                                    
                                    <button onclick="window.print()" class="action-btn btn-secondary">
                                        <i class="ri-printer-line"></i>Print Invoice
                                    </button>
                                    
                                    <button onclick="downloadPDF()" class="action-btn btn-secondary">
                                        <i class="ri-download-line"></i>Download PDF
                                    </button>
                                    
                                    <hr class="my-3">
                                    
                                    <button onclick="deleteInvoice()" class="action-btn btn-danger">
                                        <i class="ri-delete-bin-line"></i>Delete Invoice
                                    </button>
                                    
                                    <a href="invoices.php" class="action-btn btn-secondary mt-3">
                                        <i class="ri-arrow-left-line"></i>Back to Invoices
                                    </a>
                                </div>

                                <!-- Payment History -->
                                <div class="actions-sidebar mt-3">
                                    <h5 class="mb-3">
                                        <i class="ri-history-line me-2"></i>Payment History
                                    </h5>
                                    
                                    <?php if ($payments->num_rows > 0): ?>
                                    <div class="payment-timeline">
                                        <?php while ($payment = $payments->fetch_assoc()): ?>
                                        <div class="payment-item">
                                            <div class="d-flex justify-content-between align-items-start mb-2">
                                                <h6 class="mb-0"><?php echo ucfirst(str_replace('_', ' ', $payment['payment_method'])); ?></h6>
                                                <span class="badge bg-success">$<?php echo number_format($payment['amount'], 2); ?></span>
                                            </div>
                                            <p class="text-muted small mb-1">
                                                <?php echo date('M j, Y H:i', strtotime($payment['created_at'])); ?>
                                                <?php if ($payment['processed_by_name']): ?>
                                                by <?php echo $payment['processed_by_name']; ?>
                                                <?php endif; ?>
                                            </p>
                                            <?php if ($payment['reference_number']): ?>
                                            <p class="text-muted small mb-0">Ref: <?php echo $payment['reference_number']; ?></p>
                                            <?php endif; ?>
                                            <?php if ($payment['notes']): ?>
                                            <p class="text-muted small mb-0"><?php echo htmlspecialchars($payment['notes']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                        <?php endwhile; ?>
                                    </div>
                                    <?php else: ?>
                                    <div class="text-center text-muted py-4">
                                        <i class="ri-money-dollar-circle-line display-4 mb-3 d-block opacity-50"></i>
                                        <p class="mb-0">No payments recorded yet</p>
                                        <button onclick="recordPayment()" class="btn btn-outline-primary btn-sm mt-2">
                                            Record First Payment
                                        </button>
                                    </div>
                                    <?php endif; ?>
                                </div>

                                <!-- Invoice Summary -->
                                <div class="actions-sidebar mt-3">
                                    <h5 class="mb-3">
                                        <i class="ri-information-line me-2"></i>Invoice Summary
                                    </h5>
                                    <div class="row g-3">
                                        <div class="col-12">
                                            <div class="d-flex justify-content-between">
                                                <span class="text-muted">Status:</span>
                                                <strong class="<?php echo $is_overdue ? 'text-danger' : ''; ?>">
                                                    <?php echo $invoice['status']; ?>
                                                </strong>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="d-flex justify-content-between">
                                                <span class="text-muted">Total Items:</span>
                                                <strong><?php echo $invoice_items->num_rows; ?></strong>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="d-flex justify-content-between">
                                                <span class="text-muted">Days Old:</span>
                                                <strong><?php echo (int)((time() - strtotime($invoice['created_at'])) / 86400); ?> days</strong>
                                            </div>
                                        </div>
                                        <?php if ($is_overdue): ?>
                                        <div class="col-12">
                                            <div class="d-flex justify-content-between">
                                                <span class="text-danger">Days Overdue:</span>
                                                <strong class="text-danger"><?php echo $days_overdue; ?> days</strong>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                        <?php if ($invoice['balance_amount'] > 0): ?>
                                        <div class="col-12">
                                            <div class="d-flex justify-content-between">
                                                <span class="text-muted">Payment Progress:</span>
                                                <strong><?php echo number_format(($invoice['paid_amount'] / $invoice['total_amount']) * 100, 1); ?>%</strong>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>

                            </div>
                        </div>

                    </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>
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
        // Send Invoice
        function sendInvoice() {
            Swal.fire({
                title: 'Send Invoice',
                html: `
                    <div class="text-start">
                        <div class="mb-3">
                            <label class="form-label">Send Method:</label>
                            <select class="form-select" id="sendMethod">
                                <option value="email">Email</option>
                                <option value="sms">SMS</option>
                                <option value="both">Both Email & SMS</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Additional Message:</label>
                            <textarea class="form-control" id="additionalMessage" rows="3" 
                                      placeholder="Optional message to include with the invoice..."></textarea>
                        </div>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Send Invoice',
                cancelButtonText: 'Cancel',
                preConfirm: () => {
                    return {
                        method: document.getElementById('sendMethod').value,
                        message: document.getElementById('additionalMessage').value
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const { method, message } = result.value;
                    
                    // Show loading
                    Swal.fire({
                        title: 'Sending Invoice...',
                        text: 'Please wait while we send the invoice.',
                        icon: 'info',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // Make AJAX call
                    $.ajax({
                        url: 'view_invoice.php?id=<?php echo $invoice_id; ?>',
                        method: 'POST',
                        data: {
                            action: 'send_invoice',
                            method: method,
                            message: message
                        },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    title: 'Invoice Sent!',
                                    text: response.message,
                                    icon: 'success',
                                    timer: 3000,
                                    showConfirmButton: false
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    title: 'Error',
                                    text: response.message,
                                    icon: 'error'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                title: 'Error',
                                text: 'An error occurred while sending the invoice.',
                                icon: 'error'
                            });
                        }
                    });
                }
            });
        }

        // Record Payment
        function recordPayment() {
            Swal.fire({
                title: 'Record Payment',
                html: `
                    <div class="text-start">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Payment Date:</label>
                                <input type="date" class="form-control" id="paymentDate" value="${new Date().toISOString().split('T')[0]}">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Amount ($):</label>
                                <input type="number" class="form-control" id="paymentAmount" 
                                       placeholder="Enter amount" step="0.01" max="<?php echo $invoice['balance_amount']; ?>" 
                                       value="<?php echo $invoice['balance_amount']; ?>">
                            </div>
                            <div class="col-12">
                                <label class="form-label">Payment Method:</label>
                                <select class="form-select" id="paymentMethod">
                                    <option value="CASH">Cash</option>
                                    <option value="BANK_TRANSFER">Bank Transfer</option>
                                    <option value="CARD">Card Payment</option>
                                    <option value="MOBILE_MONEY">Mobile Money</option>
                                    <option value="CHEQUE">Cheque</option>
                                    <option value="OTHER">Other</option>
                                </select>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Reference Number:</label>
                                <input type="text" class="form-control" id="referenceNumber" 
                                       placeholder="Enter reference number (optional)">
                            </div>
                            <div class="col-12">
                                <label class="form-label">Notes:</label>
                                <textarea class="form-control" id="paymentNotes" rows="2" 
                                          placeholder="Additional payment notes..."></textarea>
                            </div>
                        </div>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Record Payment',
                cancelButtonText: 'Cancel',
                width: '600px',
                preConfirm: () => {
                    const amount = parseFloat(document.getElementById('paymentAmount').value);
                    const date = document.getElementById('paymentDate').value;
                    
                    if (!amount || amount <= 0) {
                        Swal.showValidationMessage('Please enter a valid payment amount');
                        return false;
                    }
                    if (amount > <?php echo $invoice['balance_amount']; ?>) {
                        Swal.showValidationMessage('Payment amount cannot exceed the balance due');
                        return false;
                    }
                    if (!date) {
                        Swal.showValidationMessage('Please select a payment date');
                        return false;
                    }
                    
                    return {
                        date: date,
                        amount: amount,
                        method: document.getElementById('paymentMethod').value,
                        reference: document.getElementById('referenceNumber').value,
                        notes: document.getElementById('paymentNotes').value
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const { date, amount, method, reference, notes } = result.value;
                    
                    // Show loading
                    Swal.fire({
                        title: 'Recording Payment...',
                        text: 'Please wait while we record the payment.',
                        icon: 'info',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // Make AJAX call
                    $.ajax({
                        url: 'view_invoice.php?id=<?php echo $invoice_id; ?>',
                        method: 'POST',
                        data: {
                            action: 'record_payment',
                            payment_date: date,
                            amount: amount,
                            payment_method: method,
                            reference_number: reference,
                            notes: notes
                        },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    title: 'Payment Recorded!',
                                    text: response.message,
                                    icon: 'success',
                                    confirmButtonText: 'Refresh Page'
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    title: 'Error',
                                    text: response.message,
                                    icon: 'error'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                title: 'Error',
                                text: 'An error occurred while recording the payment.',
                                icon: 'error'
                            });
                        }
                    });
                }
            });
        }

        // Download PDF
        function downloadPDF() {
            Swal.fire({
                title: 'Generating PDF...',
                text: 'Please wait while we generate the PDF.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            setTimeout(() => {
                // Create download link
                const link = document.createElement('a');
                link.href = `generate_invoice_pdf.php?id=<?php echo $invoice_id; ?>`;
                link.download = `invoice_<?php echo $invoice['invoice_number']; ?>.pdf`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                
                Swal.close();
            }, 1500);
        }

        // Delete Invoice
        function deleteInvoice() {
            Swal.fire({
                title: 'Delete Invoice',
                text: 'Are you sure you want to delete this invoice? This action cannot be undone.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel',
                confirmButtonColor: '#e84393'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `delete_invoice.php?id=<?php echo $invoice_id; ?>`;
                }
            });
        }

        // Initialize page
        $(document).ready(function() {
            // Initialize tooltips if any
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
            
            // Add print media query styling
            const style = document.createElement('style');
            style.textContent = `
                @media print {
                    body * { visibility: hidden; }
                    .invoice-wrapper, .invoice-wrapper * { visibility: visible; }
                    .invoice-wrapper { position: absolute; left: 0; top: 0; width: 100%; }
                    .no-print { display: none !important; }
                }
            `;
            document.head.appendChild(style);
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>