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

// Set timezone to East Africa Time
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'];
$shipment_id = isset($_GET['shipment_id']) ? intval($_GET['shipment_id']) : 0;

if (!$shipment_id) {
    die('Invalid shipment ID');
}

// Fetch user details
$user_sql = "SELECT full_name FROM users WHERE user_id = ?";
$user_stmt = $conn->prepare($user_sql);
if (!$user_stmt) {
    die('Database error: ' . $conn->error);
}
$user_stmt->bind_param("i", $user_id);
$user_stmt->execute();
$user_result = $user_stmt->get_result();
if ($user_result->num_rows === 0) {
    die('User not found');
}
$user_data = $user_result->fetch_assoc();
$user_stmt->close();

// Fetch complete shipment and customer details
$shipment_sql = "SELECT 
    s.*,
    st.service_name,
    st.service_code,
    ol.location_name as origin_location,
    oc.country_name as origin_country,
    oc.currency_code as origin_currency,
    dl.location_name as destination_location,
    dc.country_name as destination_country,
    dc.currency_code as destination_currency,
    c.customer_code,
    c.customer_type,
    c.company_name,
    c.first_name,
    c.last_name,
    c.email as customer_email,
    c.phone as customer_phone,
    c.address_line1,
    c.address_line2,
    c.city as customer_city,
    c.state as customer_state,
    c.postal_code as customer_postal_code,
    c.country as customer_country,
    c.tax_id as customer_tax_id,
    creator.full_name as created_by_name
FROM shipments s
LEFT JOIN service_types st ON s.service_id = st.service_id
LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
LEFT JOIN countries oc ON ol.country_id = oc.country_id
LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
LEFT JOIN countries dc ON dl.country_id = dc.country_id
LEFT JOIN customers c ON s.sender_customer_id = c.customer_id
LEFT JOIN users creator ON s.created_by = creator.user_id
WHERE s.shipment_id = ?";

$stmt = $conn->prepare($shipment_sql);
if (!$stmt) {
    die('Database error: ' . $conn->error);
}
$stmt->bind_param("i", $shipment_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die('Shipment not found');
}

$shipment = $result->fetch_assoc();
$stmt->close();

// Check if invoice already exists for this shipment
$existing_invoice_sql = "SELECT i.invoice_id, i.invoice_number, i.status 
                        FROM invoices i
                        INNER JOIN invoice_items ii ON i.invoice_id = ii.invoice_id
                        WHERE ii.shipment_id = ? LIMIT 1";
$existing_stmt = $conn->prepare($existing_invoice_sql);
if (!$existing_stmt) {
    die('Database error: ' . $conn->error);
}
$existing_stmt->bind_param("i", $shipment_id);
$existing_stmt->execute();
$existing_result = $existing_stmt->get_result();
$existing_invoice = $existing_result->fetch_assoc();
$existing_stmt->close();

$invoice_number = '';
$invoice_id = null;
$invoice_status = 'DRAFT';

if ($existing_invoice) {
    // Use existing invoice
    $invoice_number = $existing_invoice['invoice_number'];
    $invoice_id = $existing_invoice['invoice_id'];
    $invoice_status = $existing_invoice['status'];
} else {
    // Create new invoice only if shipment has a customer
    if ($shipment['sender_customer_id']) {
        try {
            // Start transaction
            $conn->begin_transaction();
            
            // Generate invoice number using stored procedure or manual generation
            $invoice_prefix = 'INV';
            $current_year = date('Y');
            
            // Get next invoice number
            $next_number_sql = "SELECT COALESCE(MAX(CAST(SUBSTRING(invoice_number, LENGTH(?) + 5) AS UNSIGNED)), 0) + 1 as next_number 
                               FROM invoices 
                               WHERE invoice_number LIKE CONCAT(?, ?, '%')";
            $next_stmt = $conn->prepare($next_number_sql);
            if (!$next_stmt) {
                throw new Exception('Failed to prepare next number query: ' . $conn->error);
            }
            
            $next_stmt->bind_param("sss", $invoice_prefix, $invoice_prefix, $current_year);
            $next_stmt->execute();
            $next_result = $next_stmt->get_result()->fetch_assoc();
            $next_number = $next_result['next_number'];
            $next_stmt->close();
            
            $invoice_number = $invoice_prefix . $current_year . str_pad($next_number, 4, '0', STR_PAD_LEFT);
            
            // Calculate due date (30 days from now)
            $due_date = date('Y-m-d', strtotime('+30 days'));
            
            // Calculate subtotal (total minus tax)
            $subtotal = $shipment['total_charges'] - ($shipment['tax_amount'] ?? 0);
            $tax_rate = 16.00;
            $tax_amount = $shipment['tax_amount'] ?? 0;
            
            // Create invoice
            $create_invoice_sql = "INSERT INTO invoices (invoice_number, customer_id, invoice_date, due_date, 
                                  subtotal, tax_rate, tax_amount, total_amount, status, created_by) 
                                  VALUES (?, ?, CURDATE(), ?, ?, ?, ?, ?, 'DRAFT', ?)";
            $create_stmt = $conn->prepare($create_invoice_sql);
            if (!$create_stmt) {
                throw new Exception('Failed to prepare invoice creation query: ' . $conn->error);
            }
            
            $create_stmt->bind_param("sisiddsi", 
                $invoice_number, 
                $shipment['sender_customer_id'], 
                $due_date,
                $subtotal, 
                $tax_rate,
                $tax_amount, 
                $shipment['total_charges'], 
                $user_id
            );
            
            if (!$create_stmt->execute()) {
                throw new Exception('Failed to create invoice: ' . $create_stmt->error);
            }
            
            // Get the inserted invoice ID
            $invoice_id = $conn->insert_id;
            $create_stmt->close();
            
            if ($invoice_id <= 0) {
                throw new Exception('Failed to get valid invoice ID after insert');
            }
            
            // Create invoice item
            $create_item_sql = "INSERT INTO invoice_items (invoice_id, shipment_id, description, quantity, unit_price, line_total) 
                               VALUES (?, ?, ?, 1, ?, ?)";
            $description = "Freight services for " . $shipment['service_name'] . " - " . $shipment['tracking_number'];
            $create_item_stmt = $conn->prepare($create_item_sql);
            
            if (!$create_item_stmt) {
                throw new Exception('Failed to prepare invoice item creation query: ' . $conn->error);
            }
            
            $create_item_stmt->bind_param("iisdd", 
                $invoice_id, 
                $shipment_id, 
                $description,
                $shipment['total_charges'], 
                $shipment['total_charges']
            );
            
            if (!$create_item_stmt->execute()) {
                throw new Exception('Failed to create invoice item: ' . $create_item_stmt->error);
            }
            
            $create_item_stmt->close();
            
            // Commit transaction
            $conn->commit();
            $invoice_status = 'DRAFT';
            
        } catch (Exception $e) {
            // Rollback transaction on error
            $conn->rollback();
            error_log("Invoice creation error: " . $e->getMessage());
            die('Error creating invoice: ' . $e->getMessage());
        }
    } else {
        // No customer associated with shipment
        $invoice_number = 'N/A - No Customer';
    }
}

// Fetch company settings
$settings_sql = "SELECT setting_key, setting_value FROM settings 
                 WHERE setting_key IN ('company_name', 'company_address', 'company_city', 'company_state',
                                       'company_postal_code', 'company_phone', 'company_email', 'company_logo',
                                       'company_tax_id', 'company_website')";
$settings_result = $conn->query($settings_sql);

$settings = [];
if ($settings_result) {
    while ($row = $settings_result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
}

function getSetting($key, $default = '') {
    global $settings;
    return $settings[$key] ?? $default;
}

// Currency helper function
function formatCurrency($amount, $currency_code = null, $origin_currency = null, $destination_currency = null) {
    // Determine display currency
    $display_currency = $currency_code;
    if (!$display_currency && $origin_currency) {
        $display_currency = $origin_currency;
    } elseif (!$display_currency && $destination_currency) {
        $display_currency = $destination_currency;
    } else {
        $display_currency = 'KES';
    }
    
    $symbols = [
        'KES' => 'KSh ',
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£',
        'UGX' => 'USh ',
        'TZS' => 'TSh ',
        'RWF' => 'RF ',
        'AED' => 'AED ',
        'CNY' => '¥',
        'INR' => '₹',
        'ZAR' => 'R ',
        'NGN' => '₦'
    ];
    
    $symbol = $symbols[$display_currency] ?? $display_currency . ' ';
    return $symbol . number_format(floatval($amount), 2);
}

// Don't close connection yet as we might need it for the markAsSent function
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice <?php echo $invoice_number; ?> - <?php echo getSetting('company_name', 'Freight Company'); ?></title>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background: white;
            color: #000;
            line-height: 1.5;
        }
        
        .invoice-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: white;
        }
        
        .invoice-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #000;
        }
        
        .company-info {
            flex: 1;
        }
        
        .company-logo {
            max-width: 120px;
            max-height: 80px;
            margin-bottom: 10px;
        }
        
        .company-name {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 5px;
            color: #1e40af;
        }
        
        .company-details {
            font-size: 14px;
            margin-bottom: 3px;
            color: #666;
        }
        
        .invoice-title {
            flex: 1;
            text-align: right;
        }
        
        .invoice-title h1 {
            font-size: 36px;
            color: #1e40af;
            margin-bottom: 10px;
        }
        
        .invoice-meta {
            font-size: 14px;
            color: #666;
        }
        
        .invoice-details {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
        }
        
        .bill-to, .ship-to {
            flex: 1;
            margin-right: 20px;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: bold;
            color: #1e40af;
            margin-bottom: 10px;
            padding: 8px 0;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .customer-info {
            font-size: 14px;
            line-height: 1.6;
        }
        
        .items-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        
        .items-table th {
            background: #f8fafc;
            border: 1px solid #e5e7eb;
            padding: 12px;
            text-align: left;
            font-weight: bold;
            color: #374151;
        }
        
        .items-table td {
            border: 1px solid #e5e7eb;
            padding: 12px;
            vertical-align: top
        }
        
        .items-table .amount {
            text-align: right;
        }
        
        .totals-section {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 30px;
        }
        
        .totals-table {
            width: 300px;
        }
        
        .totals-table td {
            padding: 8px 12px;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .totals-table .total-row {
            background: #f8fafc;
            font-weight: bold;
            font-size: 16px;
            border-top: 2px solid #1e40af;
        }
        
        .payment-terms {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 30px;
        }
        
        .payment-terms h3 {
            color: #059669;
            margin-bottom: 10px;
        }
        
        .footer {
            text-align: center;
            font-size: 12px;
            color: #666;
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #e5e7eb;
        }
        
        .no-print {
            display: block;
        }
        
        @media print {
            body {
                margin: 0;
                padding: 0;
            }
            
            .invoice-container {
                max-width: 100%;
                margin: 0;
                padding: 10px;
            }
            
            .no-print {
                display: none !important;
            }
            
            @page {
                margin: 0.5in;
                size: A4;
            }
        }
        
        .action-buttons {
            position: fixed;
            top: 20px;
            right: 20px;
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            font-weight: 600;
        }
        
        .btn-primary {
            background: #3b82f6;
            color: white;
        }
        
        .btn-success {
            background: #10b981;
            color: white;
        }
        
        .btn-secondary {
            background: #64748b;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
        
        .status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .status-draft {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-sent {
            background: #dbeafe;
            color: #1e40af;
        }
        
        .status-paid {
            background: #d1fae5;
            color: #059669;
        }
        
        .shipment-details {
            background: #f8fafc;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .shipment-details h3 {
            color: #374151;
            margin-bottom: 10px;
        }
        
        .route-info {
            display: flex;
            align-items: center;
            margin: 10px 0;
        }
        
        .route-point {
            flex: 1;
            text-align: center;
            padding: 10px;
            background: white;
            border: 1px solid #d1d5db;
            border-radius: 6px;
        }
        
        .route-arrow {
            margin: 0 10px;
            font-size: 20px;
            color: #6b7280;
        }
    </style>
</head>

<body>
    <!-- Action Buttons -->
    <div class="action-buttons no-print">
        <button onclick="window.print()" class="btn btn-primary">
            🖨️ Print Invoice
        </button>
        <?php if ($invoice_id): ?>
        <button onclick="markAsSent()" class="btn btn-success">
            📧 Mark as Sent
        </button>
        <?php endif; ?>
        <a href="view_shipment.php?id=<?php echo $shipment_id; ?>" class="btn btn-secondary">
            ← Back to Shipment
        </a>
    </div>

    <div class="invoice-container">
        <!-- Invoice Header -->
        <div class="invoice-header">
            <div class="company-info">
                <?php if (getSetting('company_logo')): ?>
                <img src="<?php echo getSetting('company_logo'); ?>" alt="Logo" class="company-logo">
                <?php endif; ?>
                
                <div class="company-name"><?php echo getSetting('company_name', 'Freight Company'); ?></div>
                <div class="company-details"><?php echo getSetting('company_address'); ?></div>
                <div class="company-details">
                    <?php echo getSetting('company_city'); ?>, <?php echo getSetting('company_state'); ?> 
                    <?php echo getSetting('company_postal_code'); ?>
                </div>
                <div class="company-details">Phone: <?php echo getSetting('company_phone'); ?></div>
                <div class="company-details">Email: <?php echo getSetting('company_email'); ?></div>
                <?php if (getSetting('company_website')): ?>
                <div class="company-details">Web: <?php echo getSetting('company_website'); ?></div>
                <?php endif; ?>
                <?php if (getSetting('company_tax_id')): ?>
                <div class="company-details">Tax ID: <?php echo getSetting('company_tax_id'); ?></div>
                <?php endif; ?>
            </div>
            
            <div class="invoice-title">
                <h1>INVOICE</h1>
                <div class="invoice-meta">
                    <strong>Invoice #: <?php echo $invoice_number; ?></strong><br>
                    <span class="status-badge status-draft">DRAFT</span><br><br>
                    Invoice Date: <?php echo date('F j, Y'); ?><br>
                    Due Date: <?php echo date('F j, Y', strtotime('+30 days')); ?><br>
                    Terms: Net 30 Days
                </div>
            </div>
        </div>

        <!-- Customer and Shipment Details -->
        <div class="invoice-details">
            <div class="bill-to">
                <div class="section-title">BILL TO:</div>
                <div class="customer-info">
                    <?php if ($shipment['customer_type'] === 'CORPORATE' && $shipment['company_name']): ?>
                        <strong><?php echo htmlspecialchars($shipment['company_name']); ?></strong><br>
                        Attn: <?php echo htmlspecialchars($shipment['first_name'] . ' ' . $shipment['last_name']); ?><br>
                    <?php else: ?>
                        <strong><?php echo htmlspecialchars($shipment['first_name'] . ' ' . $shipment['last_name']); ?></strong><br>
                    <?php endif; ?>
                    
                    <?php if ($shipment['customer_code']): ?>
                    Customer ID: <?php echo $shipment['customer_code']; ?><br>
                    <?php endif; ?>
                    
                    <?php echo htmlspecialchars($shipment['address_line1']); ?><br>
                    <?php if ($shipment['address_line2']): ?>
                    <?php echo htmlspecialchars($shipment['address_line2']); ?><br>
                    <?php endif; ?>
                    
                    <?php echo htmlspecialchars($shipment['customer_city']); ?>
                    <?php if ($shipment['customer_state']): ?>
                    , <?php echo htmlspecialchars($shipment['customer_state']); ?>
                    <?php endif; ?>
                    <?php if ($shipment['customer_postal_code']): ?>
                    <?php echo $shipment['customer_postal_code']; ?>
                    <?php endif; ?><br>
                    
                    <?php echo htmlspecialchars($shipment['customer_country']); ?><br><br>
                    
                    Phone: <?php echo $shipment['customer_phone']; ?><br>
                    <?php if ($shipment['customer_email']): ?>
                    Email: <?php echo $shipment['customer_email']; ?><br>
                    <?php endif; ?>
                    
                    <?php if ($shipment['customer_tax_id']): ?>
                    Tax ID: <?php echo $shipment['customer_tax_id']; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="ship-to">
                <div class="section-title">SHIPMENT DETAILS:</div>
                <div class="shipment-details">
                    <strong>Tracking Number:</strong> <?php echo $shipment['tracking_number']; ?><br>
                    <strong>Service:</strong> <?php echo $shipment['service_name']; ?><br>
                    <strong>Booking Date:</strong> <?php echo date('F j, Y', strtotime($shipment['booking_date'])); ?><br>
                    <strong>Status:</strong> <?php echo ucfirst(strtolower(str_replace('_', ' ', $shipment['status']))); ?><br>
                    
                    <div class="route-info">
                        <div class="route-point">
                            <strong>FROM</strong><br>
                            <?php echo $shipment['origin_location']; ?><br>
                            <?php echo $shipment['origin_country']; ?>
                        </div>
                        <div class="route-arrow">→</div>
                        <div class="route-point">
                            <strong>TO</strong><br>
                            <?php echo $shipment['destination_location']; ?><br>
                            <?php echo $shipment['destination_country']; ?>
                        </div>
                    </div>
                    
                    <strong>Package Details:</strong><br>
                    • Pieces: <?php echo $shipment['pieces']; ?><br>
                    • Weight: <?php echo $shipment['chargeable_weight']; ?> kg<br>
                    • Contents: <?php echo htmlspecialchars($shipment['content_description']); ?><br>
                    • Declared Value: <?php echo $shipment['currency'],$shipment['declared_value']; ?>
                </div>
            </div>
        </div>

        <!-- Invoice Items Table -->
        <table class="items-table">
            <thead>
                <tr>
                    <th style="width: 50%;">Description</th>
                    <th style="width: 15%;">Qty</th>
                    <th style="width: 15%;">Unit Price</th>
                    <th style="width: 20%;" class="amount">Amount</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <strong>Freight Charges</strong><br>
                        <?php echo $shipment['service_name']; ?> service for shipment <?php echo $shipment['tracking_number']; ?>
                    </td>
                    <td>1</td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['freight_charges']; ?></td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['freight_charges']; ?></td>
                </tr>
                
                <?php if ($shipment['fuel_surcharge'] > 0): ?>
                <tr>
                    <td>Fuel Surcharge</td>
                    <td>1</td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['fuel_surcharge']; ?></td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['fuel_surcharge']; ?></td>
                </tr>
                <?php endif; ?>
                
                <?php if ($shipment['insurance_charges'] > 0): ?>
                <tr>
                    <td>Insurance</td>
                    <td>1</td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['insurance_charges']; ?></td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['insurance_charges']; ?></td>
                </tr>
                <?php endif; ?>
                
                <?php if ($shipment['handling_charges'] > 0): ?>
                <tr>
                    <td>Handling Charges</td>
                    <td>1</td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['handling_charges']; ?></td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['handling_charges']; ?></td>
                </tr>
                <?php endif; ?>
                
                <?php if ($shipment['customs_charges'] > 0): ?>
                <tr>
                    <td>Customs Clearance</td>
                    <td>1</td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['customs_charges']; ?></td>
                   <td class="amount"><?php echo $shipment['currency'], $shipment['customs_charges']; ?></td>
                </tr>
                <?php endif; ?>
                
                <?php if ($shipment['other_charges'] > 0): ?>
                <tr>
                    <td>Other Charges</td>
                    <td>1</td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['other_charges']; ?></td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['other_charges']; ?></td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Totals Section -->
        <div class="totals-section">
            <table class="totals-table">
                <tr>
                    <td><strong>Subtotal:</strong></td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['total_charges'] - $shipment['tax_amount']; ?></td>
                </tr>
                <?php if ($shipment['tax_amount'] > 0): ?>
                <tr>
                    <td><strong>Tax (16%):</strong></td>
                    <td class="amount"><?php echo $shipment['currency'], $shipment['tax_amount'] ; ?></td>
                </tr>
                <?php endif; ?>
                <tr class="total-row">
                    <td><strong>TOTAL AMOUNT:</strong></td>
                    <td class="amount"><strong><?php echo $shipment['currency'], $shipment['total_charges']; ?></strong></td>
                </tr>
            </table>
        </div>

        <!-- Payment Terms -->
        <div class="payment-terms">
            <h3>Payment Terms & Information</h3>
            <p><strong>Payment Due:</strong> <?php echo date('F j, Y', strtotime('+30 days')); ?> (Net 30 days)</p>
            <p><strong>Late Fees:</strong> A 1.5% monthly service charge will be added to overdue accounts.</p>
            
            <h4 style="margin-top: 15px;">Payment Methods:</h4>
            <ul style="margin: 10px 0; padding-left: 20px;">
                <li><strong>Bank Transfer:</strong> Contact our accounts department for banking details</li>
                <li><strong>Mobile Money:</strong> Available for local payments</li>
                <li><strong>Cash:</strong> Pay at our office during business hours</li>
            </ul>
            
            <p style="margin-top: 15px;"><strong>Questions about this invoice?</strong> Contact our accounts department at <?php echo getSetting('company_email'); ?> or <?php echo getSetting('company_phone'); ?></p>
        </div>

        <!-- Footer -->
        <div class="footer">
            <p><strong><?php echo getSetting('company_name', 'Freight Company'); ?></strong> - Professional Freight & Logistics Services</p>
            <p>This is a computer-generated invoice and is valid without signature.</p>
            <p>Invoice generated on <?php echo date('F j, Y \a\t H:i'); ?> by <?php echo $user_result['full_name']; ?></p>
        </div>
    </div>

    <script>
        // Auto print on load for direct print links
        if (window.location.search.includes('auto_print=1')) {
            window.onload = function() {
                setTimeout(function() {
                    window.print();
                }, 500);
            };
        }
        
        // Mark invoice as sent
        function markAsSent() {
            if (confirm('Mark this invoice as sent to the customer?')) {
                fetch('update_invoice_status.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'invoice_id=<?php echo $invoice_id; ?>&status=SENT'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Invoice marked as sent!');
                        location.reload();
                    } else {
                        alert('Error updating invoice status');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error updating invoice status');
                });
            }
        }
        
        // Keyboard shortcut for printing
        document.addEventListener('keydown', function(e) {
            if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
                e.preventDefault();
                window.print();
            }
        });
        
        // Copy invoice number to clipboard
        function copyInvoiceNumber() {
            const invoiceNumber = '<?php echo $invoice_number; ?>';
            navigator.clipboard.writeText(invoiceNumber).then(function() {
                alert('Invoice number copied to clipboard!');
            });
        }
        
        // Add click handler to invoice number
        document.addEventListener('DOMContentLoaded', function() {
            const invoiceNumberElements = document.querySelectorAll('strong');
            invoiceNumberElements.forEach(function(element) {
                if (element.textContent.includes('<?php echo $invoice_number; ?>')) {
                    element.style.cursor = 'pointer';
                    element.title = 'Click to copy invoice number';
                    element.addEventListener('click', copyInvoiceNumber);
                }
            });
        });
    </script>
</body>
</html>