<?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'];
$user_role = $_SESSION['role_name'] ?? 'User';

// Fetch user details
$sql_user = "SELECT u.*, ur.role_name FROM users u 
             INNER JOIN user_roles ur ON u.role_id = ur.role_id 
             WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if (!$user_details) {
    header('Location: logout.php');
    exit();
}

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'update_status':
            $invoice_id = intval($_POST['invoice_id']);
            $new_status = $_POST['status'];
            
            $allowed_statuses = ['DRAFT', 'SENT', 'PAID', 'PARTIAL', 'OVERDUE', 'CANCELLED'];
            if (!in_array($new_status, $allowed_statuses)) {
                echo json_encode(['success' => false, 'message' => 'Invalid status']);
                exit();
            }
            
            $update_sql = "UPDATE invoices SET status = ?, updated_by = ?, updated_at = NOW() WHERE invoice_id = ?";
            $stmt = $conn->prepare($update_sql);
            $stmt->bind_param("sii", $new_status, $user_id, $invoice_id);
            
            if ($stmt->execute()) {
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values) 
                           VALUES (?, 'UPDATE', 'invoices', ?, 'status_change', ?)";
                $stmt_log = $conn->prepare($log_sql);
                $stmt_log->bind_param("iss", $user_id, $invoice_id, $new_status);
                $stmt_log->execute();
                
                echo json_encode(['success' => true, 'message' => 'Invoice status updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update invoice status']);
            }
            break;
            
        case 'generate_invoice':
            $customer_id = intval($_POST['customer_id']);
            $shipment_ids = json_decode($_POST['shipment_ids'], true);
            $invoice_date = $_POST['invoice_date'];
            $due_date = $_POST['due_date'];
            $payment_terms = intval($_POST['payment_terms']);
            $notes = $_POST['notes'] ?? '';
            
            // Generate invoice number
            $year = date('Y');
            $invoice_sql = "SELECT COALESCE(MAX(CAST(SUBSTRING(invoice_number, 4) AS UNSIGNED)), 0) + 1 as next_number 
                           FROM invoices WHERE invoice_number LIKE 'INV{$year}%'";
            $result = $conn->query($invoice_sql);
            $next_number = $result->fetch_assoc()['next_number'];
            $invoice_number = 'INV' . $year . str_pad($next_number, 6, '0', STR_PAD_LEFT);
            
            // Calculate totals from shipments
            $shipment_ids_str = implode(',', array_map('intval', $shipment_ids));
            $totals_sql = "SELECT 
                            COUNT(*) as item_count,
                            SUM(total_charges) as subtotal,
                            currency,
                            AVG(16) as tax_rate
                           FROM shipments 
                           WHERE shipment_id IN ($shipment_ids_str) AND sender_customer_id = ?";
            $stmt_totals = $conn->prepare($totals_sql);
            $stmt_totals->bind_param("i", $customer_id);
            $stmt_totals->execute();
            $totals = $stmt_totals->get_result()->fetch_assoc();
            
            if ($totals['item_count'] == 0) {
                echo json_encode(['success' => false, 'message' => 'No valid shipments found']);
                exit();
            }
            
            $subtotal = $totals['subtotal'];
            $tax_rate = 16.00; // VAT rate
            $tax_amount = ($subtotal * $tax_rate) / 100;
            $total_amount = $subtotal + $tax_amount;
            
            // Create invoice
            $create_sql = "INSERT INTO invoices (
                            invoice_number, customer_id, invoice_date, due_date, 
                            subtotal, tax_rate, tax_amount, total_amount, 
                            payment_terms, notes, created_by, status
                           ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'DRAFT')";
            
            $stmt_create = $conn->prepare($create_sql);
            $stmt_create->bind_param("sissddddisi", 
                $invoice_number, $customer_id, $invoice_date, $due_date,
                $subtotal, $tax_rate, $tax_amount, $total_amount,
                $payment_terms, $notes, $user_id
            );
            
            if ($stmt_create->execute()) {
                $invoice_id = $conn->insert_id;
                
                // Create invoice items
                foreach ($shipment_ids as $shipment_id) {
                    $item_sql = "INSERT INTO invoice_items (invoice_id, shipment_id, description, quantity, unit_price, line_total)
                                SELECT ?, s.shipment_id, 
                                       CONCAT('Shipment: ', s.tracking_number, ' - ', s.content_description),
                                       1, s.total_charges, s.total_charges
                                FROM shipments s WHERE s.shipment_id = ?";
                    $stmt_item = $conn->prepare($item_sql);
                    $stmt_item->bind_param("ii", $invoice_id, $shipment_id);
                    $stmt_item->execute();
                }
                
                echo json_encode(['success' => true, 'message' => 'Invoice created successfully', 'invoice_id' => $invoice_id, 'invoice_number' => $invoice_number]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to create invoice']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
    exit();
}

// Filter parameters
$status_filter = $_GET['status'] ?? '';
$customer_filter = $_GET['customer'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$currency_filter = $_GET['currency'] ?? '';

// Build WHERE clause
$where_conditions = [];
$params = [];
$param_types = '';

if ($status_filter) {
    $where_conditions[] = "i.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if ($customer_filter) {
    $where_conditions[] = "(c.company_name LIKE ? OR CONCAT(c.first_name, ' ', c.last_name) LIKE ?)";
    $search_term = "%$customer_filter%";
    $params[] = $search_term;
    $params[] = $search_term;
    $param_types .= 'ss';
}

if ($date_from) {
    $where_conditions[] = "i.invoice_date >= ?";
    $params[] = $date_from;
    $param_types .= 's';
}

if ($date_to) {
    $where_conditions[] = "i.invoice_date <= ?";
    $params[] = $date_to;
    $param_types .= 's';
}

$where_clause = empty($where_conditions) ? '' : 'WHERE ' . implode(' AND ', $where_conditions);

// Get invoices with customer details
$sql_invoices = "
    SELECT 
        i.*,
        c.customer_code,
        c.company_name,
        c.first_name,
        c.last_name,
        c.customer_type,
        c.email,
        c.phone,
        creator.full_name as created_by_name,
        COUNT(ii.item_id) as item_count,
        GROUP_CONCAT(DISTINCT s.currency) as currencies
    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
    LEFT JOIN invoice_items ii ON i.invoice_id = ii.invoice_id
    LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id
    $where_clause
    GROUP BY i.invoice_id, i.invoice_number, i.customer_id, i.invoice_date, i.due_date, 
             i.subtotal, i.tax_amount, i.total_amount, i.paid_amount, i.balance_amount, 
             i.status, i.created_at, c.customer_code, c.company_name, c.first_name, 
             c.last_name, c.customer_type, creator.full_name
    ORDER BY i.created_at DESC";

$stmt_invoices = $conn->prepare($sql_invoices);
if (!empty($params)) {
    $stmt_invoices->bind_param($param_types, ...$params);
}
$stmt_invoices->execute();
$invoices_result = $stmt_invoices->get_result();

// Get summary statistics
$sql_summary = "
    SELECT 
        COUNT(*) as total_invoices,
        SUM(CASE WHEN i.status = 'PAID' THEN total_amount ELSE 0 END) as total_paid,
        SUM(CASE WHEN i.status = 'PENDING' OR i.status = 'SENT' THEN total_amount ELSE 0 END) as total_pending,
        SUM(CASE WHEN i.status = 'OVERDUE' THEN total_amount ELSE 0 END) as total_overdue,
        SUM(total_amount) as total_invoiced,
        AVG(total_amount) as avg_invoice_amount
    FROM invoices i
    LEFT JOIN customers c ON i.customer_id = c.customer_id
    LEFT JOIN invoice_items ii ON i.invoice_id = ii.invoice_id
    LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id
    $where_clause";

$stmt_summary = $conn->prepare($sql_summary);
if (!empty($params)) {
    $stmt_summary->bind_param($param_types, ...$params);
}
$stmt_summary->execute();
$summary = $stmt_summary->get_result()->fetch_assoc();

// Get customers for invoice generation
$sql_customers = "SELECT customer_id, customer_code, company_name, first_name, last_name, customer_type 
                  FROM customers WHERE status = 'ACTIVE' ORDER BY customer_code";
$customers_result = $conn->query($sql_customers);

// Get uninvoiced shipments for selected customer
if (isset($_GET['get_shipments']) && $_GET['customer_id']) {
    header('Content-Type: application/json');
    $customer_id = intval($_GET['customer_id']);
    
    $shipments_sql = "SELECT s.shipment_id, s.tracking_number, s.content_description, 
                             s.total_charges, s.currency, s.booking_date,
                             CONCAT(ol.location_name, ' → ', dl.location_name) as route
                      FROM shipments s
                      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 s.sender_customer_id = ? 
                      AND s.shipment_id NOT IN (SELECT shipment_id FROM invoice_items WHERE shipment_id IS NOT NULL)
                      AND s.status NOT IN ('DRAFT', 'CANCELLED')
                      ORDER BY s.booking_date DESC";
    
    $stmt_shipments = $conn->prepare($shipments_sql);
    $stmt_shipments->bind_param("i", $customer_id);
    $stmt_shipments->execute();
    $shipments = $stmt_shipments->get_result();
    
    $shipments_array = [];
    while ($row = $shipments->fetch_assoc()) {
        $shipments_array[] = $row;
    }
    
    echo json_encode($shipments_array);
    exit();
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Invoice Management')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css" rel="stylesheet">
    
    <!-- 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-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
        }
        
        .invoice-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 1.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .summary-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
            transform: translate(30px, -30px);
        }
        
        .summary-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .summary-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-draft { background: #f8f9fa; color: #6c757d; }
        .status-sent { background: #cff4fc; color: #055160; }
        .status-paid { background: #d1e7dd; color: #0a3622; }
        .status-partial { background: #fff3cd; color: #664d03; }
        .status-overdue { background: #f8d7da; color: #58151c; }
        .status-cancelled { background: #f1f3f4; color: #3c4043; }
        
        .currency-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 8px;
            font-size: 0.7rem;
            font-weight: 600;
            margin: 0.1rem;
        }
        
        .currency-usd { background: #e3f2fd; color: #1976d2; }
        .currency-kes { background: #e8f5e8; color: #2e7d32; }
        .currency-eur { background: #fff3e0; color: #ef6c00; }
        .currency-gbp { background: #f3e5f5; color: #7b1fa2; }
        
        .action-btn {
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            font-size: 0.75rem;
            margin: 0.1rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-view { background: #e3f2fd; color: #1976d2; }
        .btn-edit { background: #fff3e0; color: #ef6c00; }
        .btn-delete { background: #ffebee; color: #c62828; }
        .btn-send { background: #e8f5e8; color: #2e7d32; }
        
        .action-btn:hover {
            transform: scale(1.05);
        }
        
        .customer-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .invoice-amount {
            font-size: 1.1rem;
            font-weight: 700;
        }
        
        .overdue-indicator {
            background: #dc3545;
            color: white;
            padding: 0.1rem 0.3rem;
            border-radius: 3px;
            font-size: 0.6rem;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        
        .filter-section {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e9ecef;
        }
        
        .create-invoice-btn {
            background: linear-gradient(45deg, #28a745, #20c997);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(40,167,69,0.3);
        }
        
        .create-invoice-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(40,167,69,0.4);
            color: white;
        }
        
        @media (max-width: 768px) {
            .summary-card {
                margin-bottom: 1rem;
            }
            
            .summary-value {
                font-size: 1.5rem;
            }
            
            .table-responsive {
                font-size: 0.875rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <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"><i class="ri-file-text-line me-2"></i>Invoice Management</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="revenue_dashboard.php">Revenue</a></li>
                                        <li class="breadcrumb-item active">Invoices</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                <div class="summary-value"><?php echo number_format($summary['total_invoices']); ?></div>
                                <div class="summary-label">Total Invoices</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                <div class="summary-value">$<?php echo number_format($summary['total_paid'], 2); ?></div>
                                <div class="summary-label">Total Paid</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                <div class="summary-value">$<?php echo number_format($summary['total_pending'], 2); ?></div>
                                <div class="summary-label">Pending Payment</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="summary-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                <div class="summary-value">$<?php echo number_format($summary['total_overdue'], 2); ?></div>
                                <div class="summary-label">Overdue Amount</div>
                            </div>
                        </div>
                    </div>

                    <!-- Actions and Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="invoice-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-md-6">
                                            <button class="btn create-invoice-btn me-2" onclick="showCreateInvoiceModal()">
                                                <i class="ri-add-line me-1"></i>Create Invoice
                                            </button>
                                            <button class="btn btn-outline-success me-2" onclick="exportInvoices()">
                                                <i class="ri-download-line me-1"></i>Export
                                            </button>
                                            <button class="btn btn-outline-info" onclick="sendBulkReminders()">
                                                <i class="ri-mail-send-line me-1"></i>Send Reminders
                                            </button>
                                        </div>
                                        <div class="col-md-6 text-end">
                                            <button class="btn btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#filterSection">
                                                <i class="ri-filter-3-line me-1"></i>Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="collapse" id="filterSection">
                        <div class="filter-section">
                            <form method="GET" class="row g-3">
                                <div class="col-md-2">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" name="status" id="status">
                                        <option value="">All Status</option>
                                        <option value="DRAFT" <?php echo $status_filter == 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                        <option value="SENT" <?php echo $status_filter == 'SENT' ? 'selected' : ''; ?>>Sent</option>
                                        <option value="PAID" <?php echo $status_filter == 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                        <option value="PARTIAL" <?php echo $status_filter == 'PARTIAL' ? 'selected' : ''; ?>>Partial</option>
                                        <option value="OVERDUE" <?php echo $status_filter == 'OVERDUE' ? 'selected' : ''; ?>>Overdue</option>
                                        <option value="CANCELLED" <?php echo $status_filter == 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-3">
                                    <label for="customer" class="form-label">Customer</label>
                                    <input type="text" class="form-control" name="customer" id="customer" 
                                           placeholder="Search customer..." value="<?php echo htmlspecialchars($customer_filter); ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="date_from" class="form-label">Date From</label>
                                    <input type="date" class="form-control" name="date_from" id="date_from" value="<?php echo $date_from; ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="date_to" class="form-label">Date To</label>
                                    <input type="date" class="form-control" name="date_to" id="date_to" value="<?php echo $date_to; ?>">
                                </div>
                                
                                <div class="col-md-2">
                                    <label for="currency" class="form-label">Currency</label>
                                    <select class="form-select" name="currency" id="currency">
                                        <option value="">All Currencies</option>
                                        <option value="USD" <?php echo $currency_filter == 'USD' ? 'selected' : ''; ?>>USD</option>
                                        <option value="KES" <?php echo $currency_filter == 'KES' ? 'selected' : ''; ?>>KES</option>
                                        <option value="EUR" <?php echo $currency_filter == 'EUR' ? 'selected' : ''; ?>>EUR</option>
                                        <option value="GBP" <?php echo $currency_filter == 'GBP' ? 'selected' : ''; ?>>GBP</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-1">
                                    <label class="form-label">&nbsp;</label>
                                    <button type="submit" class="btn btn-primary d-block w-100">
                                        <i class="ri-search-line"></i>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Invoices Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="invoice-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-file-list-3-line me-2"></i>Invoices List
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="invoicesTable">
                                            <thead>
                                                <tr>
                                                    <th>Invoice #</th>
                                                    <th>Customer</th>
                                                    <th>Date</th>
                                                    <th>Due Date</th>
                                                    <th>Amount</th>
                                                    <th>Paid</th>
                                                    <th>Balance</th>
                                                    <th>Status</th>
                                                    <th>Items</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($invoice = $invoices_result->fetch_assoc()): ?>
                                                <?php
                                                    $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;
                                                ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <strong><?php echo $invoice['invoice_number']; ?></strong>
                                                            <?php if ($is_overdue): ?>
                                                            <span class="overdue-indicator ms-2"><?php echo $days_overdue; ?>d</span>
                                                            <?php endif; ?>
                                                        </div>
                                                        <small class="text-muted">by <?php echo $invoice['created_by_name']; ?></small>
                                                    </td>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="customer-avatar me-2">
                                                                <?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>
                                                                <div class="fw-bold">
                                                                    <?php 
                                                                    echo $invoice['customer_type'] == 'CORPORATE' 
                                                                        ? ($invoice['company_name'] ?? 'Company') 
                                                                        : ($invoice['first_name'] ?? 'Individual') . ' ' . ($invoice['last_name'] ?? ''); 
                                                                    ?>
                                                                </div>
                                                                <small class="text-muted"><?php echo $invoice['customer_code'] ?? 'N/A'; ?></small>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td><?php echo date('M j, Y', strtotime($invoice['invoice_date'])); ?></td>
                                                    <td>
                                                        <span class="<?php echo $is_overdue ? 'text-danger fw-bold' : ''; ?>">
                                                            <?php echo date('M j, Y', strtotime($invoice['due_date'])); ?>
                                                        </span>
                                                    </td>
                                                    <td class="invoice-amount">$<?php echo number_format($invoice['total_amount'], 2); ?></td>
                                                    <td class="text-success">$<?php echo number_format($invoice['paid_amount'], 2); ?></td>
                                                    <td class="<?php echo $invoice['balance_amount'] > 0 ? 'text-warning fw-bold' : 'text-muted'; ?>">
                                                        $<?php echo number_format($invoice['balance_amount'], 2); ?>
                                                    </td>
                                                    <td>
                                                        <select class="form-select form-select-sm status-badge status-<?php echo strtolower($invoice['status']); ?>" 
                                                                onchange="updateInvoiceStatus(<?php echo $invoice['invoice_id']; ?>, this.value)" 
                                                                style="border: none; background: transparent; font-weight: 600;">
                                                            <option value="DRAFT" <?php echo $invoice['status'] == 'DRAFT' ? 'selected' : ''; ?>>Draft</option>
                                                            <option value="SENT" <?php echo $invoice['status'] == 'SENT' ? 'selected' : ''; ?>>Sent</option>
                                                            <option value="PAID" <?php echo $invoice['status'] == 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                                            <option value="PARTIAL" <?php echo $invoice['status'] == 'PARTIAL' ? 'selected' : ''; ?>>Partial</option>
                                                            <option value="OVERDUE" <?php echo $invoice['status'] == 'OVERDUE' ? 'selected' : ''; ?>>Overdue</option>
                                                            <option value="CANCELLED" <?php echo $invoice['status'] == 'CANCELLED' ? 'selected' : ''; ?>>Cancelled</option>
                                                        </select>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-info"><?php echo $invoice['item_count']; ?> items</span>
                                                        <?php if ($invoice['currencies']): ?>
                                                        <div class="mt-1">
                                                            <?php 
                                                            $currencies = explode(',', $invoice['currencies']);
                                                            foreach (array_unique($currencies) as $currency): 
                                                            ?>
                                                            <span class="currency-badge currency-<?php echo strtolower($currency); ?>">
                                                                <?php echo $currency; ?>
                                                            </span>
                                                            <?php endforeach; ?>
                                                        </div>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group" role="group">
                                                            <button class="action-btn btn-view" onclick="viewInvoice(<?php echo $invoice['invoice_id']; ?>)" 
                                                                    title="View Invoice">
                                                                <i class="ri-eye-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-edit" onclick="editInvoice(<?php echo $invoice['invoice_id']; ?>)" 
                                                                    title="Edit Invoice">
                                                                <i class="ri-edit-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-send" onclick="sendInvoice(<?php echo $invoice['invoice_id']; ?>)" 
                                                                    title="Send Invoice">
                                                                <i class="ri-mail-send-line"></i>
                                                            </button>
                                                            <button class="action-btn btn-delete" onclick="deleteInvoice(<?php echo $invoice['invoice_id']; ?>)" 
                                                                    title="Delete Invoice">
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Create Invoice Modal -->
    <div class="modal fade" id="createInvoiceModal" tabindex="-1" aria-labelledby="createInvoiceModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createInvoiceModalLabel">
                        <i class="ri-file-add-line me-2"></i>Create New Invoice
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="createInvoiceForm">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="invoice_customer" class="form-label">Customer *</label>
                                <select class="form-select" id="invoice_customer" name="customer_id" required onchange="loadCustomerShipments()">
                                    <option value="">Select Customer</option>
                                    <?php 
                                    $customers_result->data_seek(0);
                                    while ($customer = $customers_result->fetch_assoc()): 
                                    ?>
                                    <option value="<?php echo $customer['customer_id']; ?>">
                                        <?php 
                                        echo $customer['customer_type'] == 'CORPORATE' 
                                            ? $customer['company_name'] 
                                            : $customer['first_name'] . ' ' . $customer['last_name']; 
                                        ?> 
                                        (<?php echo $customer['customer_code']; ?>)
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            
                            <div class="col-md-3">
                                <label for="invoice_date" class="form-label">Invoice Date *</label>
                                <input type="date" class="form-control" id="invoice_date" name="invoice_date" 
                                       value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                            
                            <div class="col-md-3">
                                <label for="due_date" class="form-label">Due Date *</label>
                                <input type="date" class="form-control" id="due_date" name="due_date" 
                                       value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                            </div>
                            
                            <div class="col-md-6">
                                <label for="payment_terms" class="form-label">Payment Terms (Days)</label>
                                <input type="number" class="form-control" id="payment_terms" name="payment_terms" 
                                       value="30" min="0" max="365">
                            </div>
                            
                            <div class="col-12">
                                <label class="form-label">Available Shipments for Invoicing</label>
                                <div id="shipmentsContainer" class="border rounded p-3" style="max-height: 300px; overflow-y: auto;">
                                    <div class="text-muted text-center py-4">
                                        <i class="ri-ship-line fs-2"></i>
                                        <p class="mt-2">Select a customer to view available shipments</p>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-12">
                                <label for="invoice_notes" class="form-label">Notes</label>
                                <textarea class="form-control" id="invoice_notes" name="notes" rows="3" 
                                         placeholder="Enter any additional notes or terms..."></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">
                            <i class="ri-file-add-line me-1"></i>Create Invoice
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
// Ensure DOM is ready and all scripts are loaded
$(document).ready(function() {
    // Initialize DataTable
    $('#invoicesTable').DataTable({
        responsive: true,
        pageLength: 25,
        order: [[2, 'desc']],
        columnDefs: [
            { targets: [4, 5, 6], className: 'text-end' },
            { targets: [7], className: 'text-center' },
            { targets: [9], orderable: false }
        ],
        dom: 'Bfrtip',
        buttons: [
            {
                extend: 'excel',
                text: '<i class="ri-file-excel-line me-1"></i>Excel',
                className: 'btn btn-success btn-sm'
            },
            {
                extend: 'pdf',
                text: '<i class="ri-file-pdf-line me-1"></i>PDF', 
                className: 'btn btn-danger btn-sm'
            }
        ]
    });

    // Create Invoice Form Handler
    $('#createInvoiceForm').on('submit', function(e) {
        e.preventDefault();
        
        const selectedShipments = [];
        $('input[name="selected_shipments"]:checked').each(function() {
            selectedShipments.push(this.value);
        });
        
        if (selectedShipments.length === 0) {
            Swal.fire({
                title: 'No Shipments Selected',
                text: 'Please select at least one shipment to include in the invoice.',
                icon: 'warning',
                confirmButtonText: 'OK'
            });
            return;
        }
        
        const formData = new FormData(this);
        formData.append('action', 'generate_invoice');
        formData.append('shipment_ids', JSON.stringify(selectedShipments));
        
        // Show loading
        Swal.fire({
            title: 'Creating Invoice...',
            text: 'Please wait while we generate your invoice.',
            icon: 'info',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        $.ajax({
            url: 'invoices.php',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Invoice Created!',
                        text: `Invoice ${response.invoice_number} has been created successfully.`,
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: 'View Invoice',
                        cancelButtonText: 'Stay Here'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.open(`view_invoice.php?id=${response.invoice_id}`, '_blank');
                        }
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error',
                        text: response.message,
                        icon: 'error'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error',
                    text: 'An error occurred while creating the invoice.',
                    icon: 'error'
                });
            }
        });
    });

    // Initialize tooltips
    var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
});

// Define all functions in global scope to ensure they're accessible from onclick handlers
window.showCreateInvoiceModal = function() {
    $('#createInvoiceModal').modal('show');
};

window.loadCustomerShipments = function() {
    const customerId = $('#invoice_customer').val();
    const container = $('#shipmentsContainer');
    
    if (!customerId) {
        container.html(`
            <div class="text-muted text-center py-4">
                <i class="ri-ship-line fs-2"></i>
                <p class="mt-2">Select a customer to view available shipments</p>
            </div>
        `);
        return;
    }
    
    container.html(`
        <div class="text-center py-4">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p class="mt-2">Loading shipments...</p>
        </div>
    `);
    
    $.ajax({
        url: 'invoices.php',
        method: 'GET',
        data: { get_shipments: true, customer_id: customerId },
        dataType: 'json',
        success: function(shipments) {
            if (shipments.length === 0) {
                container.html(`
                    <div class="text-muted text-center py-4">
                        <i class="ri-inbox-line fs-2"></i>
                        <p class="mt-2">No uninvoiced shipments found for this customer</p>
                    </div>
                `);
                return;
            }
            
            let html = '<div class="row g-2">';
            let totalAmount = 0;
            
            shipments.forEach(function(shipment, index) {
                totalAmount += parseFloat(shipment.total_charges);
                html += `
                    <div class="col-12">
                        <div class="form-check border rounded p-3">
                            <input class="form-check-input" type="checkbox" name="selected_shipments" 
                                   value="${shipment.shipment_id}" id="shipment_${shipment.shipment_id}"
                                   onchange="updateInvoiceTotal()">
                            <label class="form-check-label w-100" for="shipment_${shipment.shipment_id}">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <strong>${shipment.tracking_number}</strong>
                                        <p class="mb-1">${shipment.content_description}</p>
                                        <small class="text-muted">${shipment.route} • ${new Date(shipment.booking_date).toLocaleDateString()}</small>
                                    </div>
                                    <div class="text-end">
                                        <div class="fw-bold">${shipment.currency} ${parseFloat(shipment.total_charges).toLocaleString()}</div>
                                        <span class="badge bg-primary">${shipment.currency}</span>
                                    </div>
                                </div>
                            </label>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            html += `
                <div class="mt-3 p-3 bg-light rounded">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <button type="button" class="btn btn-sm btn-outline-primary me-2" onclick="selectAllShipments()">
                                <i class="ri-check-double-line me-1"></i>Select All
                            </button>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearAllShipments()">
                                <i class="ri-close-line me-1"></i>Clear All
                            </button>
                        </div>
                        <div>
                            <strong>Selected Total: <span id="selectedTotal">$0.00</span></strong>
                        </div>
                    </div>
                </div>
            `;
            
            container.html(html);
        },
        error: function() {
            container.html(`
                <div class="text-danger text-center py-4">
                    <i class="ri-error-warning-line fs-2"></i>
                    <p class="mt-2">Error loading shipments. Please try again.</p>
                </div>
            `);
        }
    });
};

window.updateInvoiceTotal = function() {
    let total = 0;
    $('input[name="selected_shipments"]:checked').each(function() {
        const shipmentCard = $(this).closest('.form-check');
        const amountText = shipmentCard.find('.fw-bold').text();
        const amount = parseFloat(amountText.match(/[\d,]+\.?\d*/)[0].replace(',', ''));
        total += amount;
    });
    
    $('#selectedTotal').text('$' + total.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
};

window.selectAllShipments = function() {
    $('input[name="selected_shipments"]').prop('checked', true);
    updateInvoiceTotal();
};

window.clearAllShipments = function() {
    $('input[name="selected_shipments"]').prop('checked', false);
    updateInvoiceTotal();
};

window.updateInvoiceStatus = function(invoiceId, newStatus) {
    const originalSelect = event.target;
    const originalValue = originalSelect.getAttribute('data-original-value') || originalSelect.value;
    
    if (newStatus === originalValue) return;
    
    Swal.fire({
        title: 'Update Invoice Status',
        text: `Change invoice status to ${newStatus.toLowerCase()}?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Yes, Update',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'invoices.php',
                method: 'POST',
                data: {
                    action: 'update_status',
                    invoice_id: invoiceId,
                    status: newStatus
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        originalSelect.setAttribute('data-original-value', newStatus);
                        originalSelect.className = `form-select form-select-sm status-badge status-${newStatus.toLowerCase()}`;
                        
                        Swal.fire({
                            title: 'Success',
                            text: response.message,
                            icon: 'success',
                            timer: 2000,
                            showConfirmButton: false
                        });
                    } else {
                        originalSelect.value = originalValue;
                        Swal.fire({
                            title: 'Error',
                            text: response.message,
                            icon: 'error'
                        });
                    }
                },
                error: function() {
                    originalSelect.value = originalValue;
                    Swal.fire({
                        title: 'Error',
                        text: 'An error occurred while updating the status.',
                        icon: 'error'
                    });
                }
            });
        } else {
            originalSelect.value = originalValue;
        }
    });
};

window.viewInvoice = function(invoiceId) {
    window.open(`view_invoice.php?id=${invoiceId}`, '_blank');
};

window.editInvoice = function(invoiceId) {
    window.location.href = `edit_invoice.php?id=${invoiceId}`;
};

window.sendInvoice = function(invoiceId) {
    Swal.fire({
        title: 'Send Invoice',
        html: `
            <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>
        `,
        showCancelButton: true,
        confirmButtonText: 'Send Invoice',
        preConfirm: () => {
            return {
                method: document.getElementById('sendMethod').value,
                message: document.getElementById('additionalMessage').value
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Sending Invoice...',
                text: 'Please wait while we send the invoice.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    // Simulate sending
                    setTimeout(() => {
                        Swal.fire({
                            title: 'Invoice Sent!',
                            text: 'The invoice has been sent successfully.',
                            icon: 'success',
                            timer: 3000,
                            showConfirmButton: false
                        });
                    }, 2000);
                }
            });
        }
    });
};

window.deleteInvoice = function(invoiceId) {
    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: '#d33'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Deleted!',
                text: 'The invoice has been deleted.',
                icon: 'success',
                timer: 2000,
                showConfirmButton: false
            }).then(() => {
                location.reload();
            });
        }
    });
};

window.exportInvoices = function() {
    Swal.fire({
        title: 'Export Invoices',
        html: `
            <div class="mb-3">
                <label class="form-label">Export Format:</label>
                <select class="form-select" id="exportFormat">
                    <option value="excel">Excel (.xlsx)</option>
                    <option value="pdf">PDF Report</option>
                    <option value="csv">CSV Data</option>
                </select>
            </div>
            <div class="mb-3">
                <label class="form-label">Include:</label>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includeItems" checked>
                    <label class="form-check-label" for="includeItems">Invoice Items</label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="includePayments" checked>
                    <label class="form-check-label" for="includePayments">Payment History</label>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Export',
        preConfirm: () => {
            return {
                format: document.getElementById('exportFormat').value,
                includeItems: document.getElementById('includeItems').checked,
                includePayments: document.getElementById('includePayments').checked
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { format, includeItems, includePayments } = result.value;
            
            Swal.fire({
                title: 'Generating Export...',
                text: 'Please wait while we prepare your export.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.close();
                        // Trigger download
                        const link = document.createElement('a');
                        link.href = `exports/invoices_export.php?format=${format}&items=${includeItems}&payments=${includePayments}`;
                        link.download = `invoices_${new Date().toISOString().split('T')[0]}.${format}`;
                        link.click();
                    }, 2000);
                }
            });
        }
    });
};

window.sendBulkReminders = function() {
    Swal.fire({
        title: 'Send Payment Reminders',
        text: 'Send payment reminders to customers with overdue invoices?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Send Reminders',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Sending Reminders...',
                text: 'Please wait while we send payment reminders.',
                icon: 'info',
                allowOutsideClick: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                    setTimeout(() => {
                        Swal.fire({
                            title: 'Reminders Sent!',
                            text: 'Payment reminders have been sent to customers with overdue invoices.',
                            icon: 'success',
                            timer: 3000,
                            showConfirmButton: false
                        });
                    }, 3000);
                }
            });
        }
    });
};
</script>

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