<?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();
}

// Get filter parameters
$report_type = isset($_GET['report_type']) ? $_GET['report_type'] : 'revenue_summary';
$date_from = isset($_GET['date_from']) ? $_GET['date_from'] : date('Y-m-01');
$date_to = isset($_GET['date_to']) ? $_GET['date_to'] : date('Y-m-d');
$currency_filter = isset($_GET['currency']) ? $_GET['currency'] : 'ALL';

// Handle AJAX requests
if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    switch ($_POST['action']) {
        case 'export_report':
            $format = $_POST['format'] ?? 'excel';
            $include_charts = isset($_POST['include_charts']) ? 1 : 0;
            
            // Generate export (mock response)
            echo json_encode([
                'success' => true, 
                'message' => 'Report exported successfully',
                'download_url' => "exports/financial_report_" . date('Y-m-d_H-i-s') . ".$format"
            ]);
            exit();
            break;
            
        case 'get_chart_data':
            $chart_type = $_POST['chart_type'] ?? 'revenue_trend';
            
            // Mock chart data - replace with actual queries
            $chart_data = [
                'labels' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
                'datasets' => [
                    [
                        'name' => 'Revenue',
                        'data' => [150000, 180000, 165000, 195000, 210000, 185000]
                    ],
                    [
                        'name' => 'Expenses',
                        'data' => [120000, 135000, 125000, 140000, 155000, 145000]
                    ]
                ]
            ];
            
            echo json_encode(['success' => true, 'data' => $chart_data]);
            exit();
            break;
    }
}

// Currency configurations
$currencies = [
    'KES' => ['name' => 'Kenyan Shilling', 'symbol' => 'KSh', 'rate' => 1.0],
    'USD' => ['name' => 'US Dollar', 'symbol' => '$', 'rate' => 0.0067],
    'EUR' => ['name' => 'Euro', 'symbol' => '€', 'rate' => 0.0062],
    'GBP' => ['name' => 'British Pound', 'symbol' => '£', 'rate' => 0.0054],
    'UGX' => ['name' => 'Uganda Shilling', 'symbol' => 'USh', 'rate' => 25.0],
    'TZS' => ['name' => 'Tanzania Shilling', 'symbol' => 'TSh', 'rate' => 15.5],
    'RWF' => ['name' => 'Rwanda Franc', 'symbol' => 'RF', 'rate' => 6.8]
];

// Helper function to format currency
/*function formatCurrency($amount, $currency_code, $currencies) {
    if (!isset($currencies[$currency_code])) {
        return number_format($amount, 2);
    }
    return $currencies[$currency_code]['symbol'] . ' ' . number_format($amount, 2);
}*/

// Generate reports based on type
$report_data = [];
$report_title = '';
$summary_stats = [];

switch ($report_type) {
    case 'revenue_summary':
        $report_title = 'Revenue Summary Report';
        
        // Build WHERE clause for filters
        $where_conditions = ["s.payment_status = 'PAID'"];
        $params = [$date_from, $date_to];
        $param_types = 'ss';
        
        if ($currency_filter != 'ALL') {
            $where_conditions[] = "s.currency = ?";
            $params[] = $currency_filter;
            $param_types .= 's';
        }
        
        $where_clause = 'WHERE ' . implode(' AND ', $where_conditions) . ' AND DATE(s.booking_date) BETWEEN ? AND ?';
        
        $sql = "SELECT 
            DATE_FORMAT(s.booking_date, '%Y-%m') as period,
            s.currency,
            COUNT(*) as shipment_count,
            SUM(s.total_charges) as total_revenue,
            SUM(s.freight_charges) as freight_revenue,
            SUM(s.fuel_surcharge) as fuel_surcharge,
            SUM(s.insurance_charges + s.handling_charges + s.customs_charges + s.other_charges) as other_charges,
            AVG(s.total_charges) as avg_shipment_value,
            st.service_name
        FROM shipments s
        LEFT JOIN service_types st ON s.service_id = st.service_id
        $where_clause
        GROUP BY DATE_FORMAT(s.booking_date, '%Y-%m'), s.currency, st.service_name
        ORDER BY period DESC, s.currency";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($param_types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $report_data[] = $row;
        }
        
        // Calculate summary statistics
        $summary_sql = "SELECT 
            COUNT(*) as total_shipments,
            SUM(total_charges) as total_revenue,
            COUNT(DISTINCT currency) as currencies_used,
            AVG(total_charges) as avg_shipment_value
        FROM shipments s
        $where_clause";
        
        $stmt_summary = $conn->prepare($summary_sql);
        $stmt_summary->bind_param($param_types, ...$params);
        $stmt_summary->execute();
        $summary_stats = $stmt_summary->get_result()->fetch_assoc();
        break;
        
    case 'profit_loss':
        $report_title = 'Profit & Loss Statement';
        
        // Revenue calculation
        $revenue_sql = "SELECT 
            s.currency,
            SUM(s.total_charges) as total_revenue,
            SUM(s.freight_charges) as freight_revenue,
            SUM(s.fuel_surcharge) as fuel_revenue,
            SUM(s.insurance_charges + s.handling_charges + s.customs_charges + s.other_charges) as other_revenue,
            COUNT(*) as shipment_count
        FROM shipments s
        WHERE s.payment_status = 'PAID' 
        AND DATE(s.booking_date) BETWEEN ? AND ?
        " . ($currency_filter != 'ALL' ? "AND s.currency = ?" : "") . "
        GROUP BY s.currency";
        
        $stmt_revenue = $conn->prepare($revenue_sql);
        if ($currency_filter != 'ALL') {
            $stmt_revenue->bind_param("sss", $date_from, $date_to, $currency_filter);
        } else {
            $stmt_revenue->bind_param("ss", $date_from, $date_to);
        }
        $stmt_revenue->execute();
        $revenue_result = $stmt_revenue->get_result();
        
        $report_data['revenue'] = [];
        while ($row = $revenue_result->fetch_assoc()) {
            $report_data['revenue'][] = $row;
        }
        
        // Mock expenses data - replace with actual expense tracking
        $report_data['expenses'] = [
            ['category' => 'Vehicle Maintenance', 'amount' => 150000, 'currency' => 'KES', 'percentage' => 12.5],
            ['category' => 'Fuel Costs', 'amount' => 300000, 'currency' => 'KES', 'percentage' => 25.0],
            ['category' => 'Staff Salaries', 'amount' => 800000, 'currency' => 'KES', 'percentage' => 45.0],
            ['category' => 'Office Rent', 'amount' => 200000, 'currency' => 'KES', 'percentage' => 11.2],
            ['category' => 'Insurance', 'amount' => 100000, 'currency' => 'KES', 'percentage' => 5.6],
            ['category' => 'Marketing', 'amount' => 50000, 'currency' => 'KES', 'percentage' => 0.7]
        ];
        
        // Calculate totals
        $summary_stats['total_revenue'] = array_sum(array_column($report_data['revenue'], 'total_revenue'));
        $summary_stats['total_expenses'] = array_sum(array_column($report_data['expenses'], 'amount'));
        $summary_stats['net_profit'] = $summary_stats['total_revenue'] - $summary_stats['total_expenses'];
        $summary_stats['profit_margin'] = $summary_stats['total_revenue'] > 0 ? 
            ($summary_stats['net_profit'] / $summary_stats['total_revenue']) * 100 : 0;
        break;
        
    case 'cash_flow':
        $report_title = 'Cash Flow Statement';
        
        // Cash inflows from payments
        $inflow_sql = "SELECT 
            DATE(p.created_at) as transaction_date,
            'PAYMENT' as transaction_type,
            p.amount as amount,
            'INFLOW' as flow_direction,
            p.reference_number,
            c.customer_code,
            CASE 
                WHEN c.customer_type = 'CORPORATE' THEN c.company_name
                ELSE CONCAT(c.first_name, ' ', c.last_name)
            END as customer_name
        FROM payments p
        LEFT JOIN customers c ON p.customer_id = c.customer_id
        WHERE p.status = 'CONFIRMED'
        AND DATE(p.created_at) BETWEEN ? AND ?
        ORDER BY p.created_at DESC";
        
        $stmt_inflow = $conn->prepare($inflow_sql);
        $stmt_inflow->bind_param("ss", $date_from, $date_to);
        $stmt_inflow->execute();
        $inflow_result = $stmt_inflow->get_result();
        
        while ($row = $inflow_result->fetch_assoc()) {
            $report_data[] = $row;
        }
        
        // Calculate summary
        $summary_stats['total_inflow'] = array_sum(array_column($report_data, 'amount'));
        $summary_stats['transaction_count'] = count($report_data);
        $summary_stats['avg_transaction'] = $summary_stats['transaction_count'] > 0 ? 
            $summary_stats['total_inflow'] / $summary_stats['transaction_count'] : 0;
        break;
        
    case 'accounts_receivable':
        $report_title = 'Accounts Receivable Aging Report';
        
        $ar_sql = "SELECT 
            i.invoice_number,
            i.invoice_date,
            i.due_date,
            DATEDIFF(CURDATE(), i.due_date) as days_overdue,
            i.total_amount,
            i.paid_amount,
            i.balance_amount,
            i.status,
            CASE 
                WHEN c.customer_type = 'CORPORATE' THEN c.company_name
                ELSE CONCAT(c.first_name, ' ', c.last_name)
            END as customer_name,
            c.customer_code,
            c.email,
            c.phone,
            GROUP_CONCAT(DISTINCT s.currency) as currencies
        FROM invoices i
        INNER 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 i.balance_amount > 0
        AND DATE(i.invoice_date) BETWEEN ? AND ?
        GROUP BY i.invoice_id
        ORDER BY days_overdue DESC, i.balance_amount DESC";
        
        $stmt_ar = $conn->prepare($ar_sql);
        $stmt_ar->bind_param("ss", $date_from, $date_to);
        $stmt_ar->execute();
        $result = $stmt_ar->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $report_data[] = $row;
        }
        
        // Calculate aging buckets
        $summary_stats = [
            'current' => 0,
            'days_30' => 0,
            'days_60' => 0,
            'days_90' => 0,
            'days_90_plus' => 0,
            'total_outstanding' => 0
        ];
        
        foreach ($report_data as $row) {
            $summary_stats['total_outstanding'] += $row['balance_amount'];
            
            if ($row['days_overdue'] <= 0) {
                $summary_stats['current'] += $row['balance_amount'];
            } elseif ($row['days_overdue'] <= 30) {
                $summary_stats['days_30'] += $row['balance_amount'];
            } elseif ($row['days_overdue'] <= 60) {
                $summary_stats['days_60'] += $row['balance_amount'];
            } elseif ($row['days_overdue'] <= 90) {
                $summary_stats['days_90'] += $row['balance_amount'];
            } else {
                $summary_stats['days_90_plus'] += $row['balance_amount'];
            }
        }
        break;
        
    case 'customer_analysis':
        $report_title = 'Customer Revenue Analysis';
        
        $customer_sql = "SELECT 
            CASE 
                WHEN c.customer_type = 'CORPORATE' THEN c.company_name
                ELSE CONCAT(c.first_name, ' ', c.last_name)
            END as customer_name,
            c.customer_code,
            c.customer_type,
            c.email,
            c.phone,
            s.currency,
            COUNT(s.shipment_id) as shipment_count,
            SUM(s.total_charges) as total_revenue,
            AVG(s.total_charges) as avg_shipment_value,
            MAX(s.booking_date) as last_shipment_date,
            MIN(s.booking_date) as first_shipment_date,
            SUM(s.chargeable_weight) as total_weight
        FROM customers c
        INNER JOIN shipments s ON c.customer_id = s.sender_customer_id
        WHERE s.payment_status = 'PAID'
        AND DATE(s.booking_date) BETWEEN ? AND ?
        " . ($currency_filter != 'ALL' ? "AND s.currency = ?" : "") . "
        GROUP BY c.customer_id, s.currency
        HAVING total_revenue > 0
        ORDER BY total_revenue DESC";
        
        $stmt_customer = $conn->prepare($customer_sql);
        if ($currency_filter != 'ALL') {
            $stmt_customer->bind_param("sss", $date_from, $date_to, $currency_filter);
        } else {
            $stmt_customer->bind_param("ss", $date_from, $date_to);
        }
        $stmt_customer->execute();
        $result = $stmt_customer->get_result();
        
        while ($row = $result->fetch_assoc()) {
            $report_data[] = $row;
        }
        
        // Calculate summary
        $summary_stats['top_customers'] = count($report_data);
        $summary_stats['total_customer_revenue'] = array_sum(array_column($report_data, 'total_revenue'));
        $summary_stats['avg_customer_value'] = $summary_stats['top_customers'] > 0 ? 
            $summary_stats['total_customer_revenue'] / $summary_stats['top_customers'] : 0;
        break;
}

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Financial Reports')); ?>
    <?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">
    
    <!-- ApexCharts CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.css">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .report-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;
        }
        
        .report-card:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.15);
            transform: translateY(-2px);
        }
        
        .report-type-selector {
            background: #f8fafc;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .report-type-card {
            background: white;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 1.5rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            margin-bottom: 1rem;
            height: 100%;
            display: flex;
            flex-direction: column;
            justify-content: center;
        }
        
        .report-type-card:hover {
            border-color: #3b82f6;
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
            transform: translateY(-2px);
        }
        
        .report-type-card.active {
            border-color: #3b82f6;
            background: #eff6ff;
            box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
        }
        
        .report-type-icon {
            font-size: 2.5rem;
            margin-bottom: 1rem;
            color: #6b7280;
            transition: color 0.3s ease;
        }
        
        .report-type-card:hover .report-type-icon,
        .report-type-card.active .report-type-icon {
            color: #3b82f6;
        }
        
        .summary-stats {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
            position: relative;
            overflow: hidden;
        }
        
        .summary-stats::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);
        }
        
        .stat-item {
            text-align: center;
            position: relative;
            z-index: 1;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .chart-container {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .aging-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .aging-current { background: #d1fae5; color: #065f46; }
        .aging-30 { background: #fef3c7; color: #92400e; }
        .aging-60 { background: #fed7aa; color: #9a3412; }
        .aging-90 { background: #fee2e2; color: #991b1b; }
        .aging-90-plus { background: #fecaca; color: #7f1d1d; }
        
        .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;
        }
        
        .profit-indicator {
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .profit-positive {
            color: #10b981;
        }
        
        .profit-negative {
            color: #ef4444;
        }
        
        .export-btn {
            background: linear-gradient(45deg, #10b981, #059669);
            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(16,185,129,0.3);
        }
        
        .export-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(16,185,129,0.4);
            color: white;
        }
        
        .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; }
        
        @media (max-width: 768px) {
            .summary-stats {
                padding: 1.5rem;
            }
            
            .stat-value {
                font-size: 1.5rem;
            }
            
            .report-type-card {
                padding: 1rem;
            }
            
            .report-type-icon {
                font-size: 2rem;
            }
        }
    </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-chart-line me-2"></i>Financial Reports</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">Financial</a></li>
                                        <li class="breadcrumb-item active">Reports</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Report Type Selection -->
                    <div class="report-type-selector">
                        <h5 class="mb-4"><i class="ri-file-list-3-line me-2"></i>Select Report Type</h5>
                        <div class="row g-3">
                            <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
                                <div class="report-type-card <?php echo $report_type == 'revenue_summary' ? 'active' : ''; ?>" onclick="selectReport('revenue_summary')">
                                    <i class="ri-line-chart-line report-type-icon"></i>
                                    <h6 class="mb-2">Revenue Summary</h6>
                                    <p class="text-muted mb-0 small">Monthly revenue breakdown</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
                                <div class="report-type-card <?php echo $report_type == 'profit_loss' ? 'active' : ''; ?>" onclick="selectReport('profit_loss')">
                                    <i class="ri-funds-line report-type-icon"></i>
                                    <h6 class="mb-2">Profit & Loss</h6>
                                    <p class="text-muted mb-0 small">P&L statement</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
                                <div class="report-type-card <?php echo $report_type == 'cash_flow' ? 'active' : ''; ?>" onclick="selectReport('cash_flow')">
                                    <i class="ri-exchange-dollar-line report-type-icon"></i>
                                    <h6 class="mb-2">Cash Flow</h6>
                                    <p class="text-muted mb-0 small">Cash movements</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
                                <div class="report-type-card <?php echo $report_type == 'accounts_receivable' ? 'active' : ''; ?>" onclick="selectReport('accounts_receivable')">
                                    <i class="ri-money-dollar-circle-line report-type-icon"></i>
                                    <h6 class="mb-2">Receivables</h6>
                                    <p class="text-muted mb-0 small">Outstanding invoices</p>
                                </div>
                            </div>
                            <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6">
                                <div class="report-type-card <?php echo $report_type == 'customer_analysis' ? 'active' : ''; ?>" onclick="selectReport('customer_analysis')">
                                    <i class="ri-user-star-line report-type-icon"></i>
                                    <h6 class="mb-2">Customer Analysis</h6>
                                    <p class="text-muted mb-0 small">Revenue by customer</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters and Actions -->
                    <div class="row">
                        <div class="col-12">
                            <div class="report-card">
                                <div class="card-body">
                                    <div class="row align-items-center">
                                        <div class="col-lg-8">
                                            <form method="GET" class="row g-3" id="reportForm">
                                                <input type="hidden" name="report_type" id="report_type_input" value="<?php echo $report_type; ?>">
                                                
                                                <div class="col-md-3">
                                                    <label class="form-label">Date From</label>
                                                    <input type="date" class="form-control" name="date_from" value="<?php echo $date_from; ?>">
                                                </div>
                                                <div class="col-md-3">
                                                    <label class="form-label">Date To</label>
                                                    <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                                                </div>
                                                <div class="col-md-3">
                                                    <label class="form-label">Currency</label>
                                                    <select class="form-select" name="currency">
                                                        <option value="ALL" <?php echo $currency_filter == 'ALL' ? 'selected' : ''; ?>>All Currencies</option>
                                                        <?php foreach ($currencies as $code => $currency_data): ?>
                                                        <option value="<?php echo $code; ?>" <?php echo $currency_filter == $code ? 'selected' : ''; ?>>
                                                            <?php echo $currency_data['symbol'] . ' - ' . $currency_data['name']; ?>
                                                        </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-3">
                                                    <label class="form-label">&nbsp;</label>
                                                    <div class="d-flex gap-2">
                                                        <button type="submit" class="btn btn-primary">
                                                            <i class="ri-search-line me-1"></i>Generate
                                                        </button>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                        <div class="col-lg-4 text-end">
                                            <div class="d-flex gap-2 justify-content-end">
                                                <button class="export-btn" onclick="showExportModal()">
                                                    <i class="ri-download-line me-1"></i>Export Report
                                                </button>
                                                <button class="btn btn-outline-info" onclick="printReport()">
                                                    <i class="ri-printer-line me-1"></i>Print
                                                </button>
                                                <button class="btn btn-outline-secondary" onclick="emailReport()">
                                                    <i class="ri-mail-send-line me-1"></i>Email
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Statistics -->
                    <?php if (!empty($summary_stats)): ?>
                    <div class="summary-stats">
                        <div class="row">
                            <?php if ($report_type == 'revenue_summary'): ?>
                            <div class="col-md-3">
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo number_format($summary_stats['total_shipments']); ?></div>
                                    <div class="stat-label">Total Shipments</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['total_revenue']); ?></div>
                                    <div class="stat-label">Total Revenue</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo $summary_stats['currencies_used']; ?></div>
                                    <div class="stat-label">Currencies Used</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['avg_shipment_value']); ?></div>
                                    <div class="stat-label">Avg Shipment Value</div>
                                </div>
                            </div>
                            <?php elseif ($report_type == 'profit_loss'): ?>
                            <div class="col-md-3">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['total_revenue']); ?></div>
                                    <div class="stat-label">Total Revenue</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['total_expenses']); ?></div>
                                    <div class="stat-label">Total Expenses</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-item">
                                    <div class="stat-value">
                                        <div class="profit-indicator <?php echo $summary_stats['net_profit'] >= 0 ? 'profit-positive' : 'profit-negative'; ?>">
                                            <?php echo $summary_stats['net_profit'] >= 0 ? '+' : ''; ?>KSh <?php echo number_format($summary_stats['net_profit']); ?>
                                        </div>
                                    </div>
                                    <div class="stat-label">Net Profit</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo number_format($summary_stats['profit_margin'], 1); ?>%</div>
                                    <div class="stat-label">Profit Margin</div>
                                </div>
                            </div>
                            <?php elseif ($report_type == 'cash_flow'): ?>
                            <div class="col-md-4">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['total_inflow']); ?></div>
                                    <div class="stat-label">Total Cash Inflow</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo number_format($summary_stats['transaction_count']); ?></div>
                                    <div class="stat-label">Transactions</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['avg_transaction']); ?></div>
                                    <div class="stat-label">Avg Transaction</div>
                                </div>
                            </div>
                            <?php elseif ($report_type == 'accounts_receivable'): ?>
                            <div class="col-md-2">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['total_outstanding']); ?></div>
                                    <div class="stat-label">Total Outstanding</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['current']); ?></div>
                                    <div class="stat-label">Current</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['days_30']); ?></div>
                                    <div class="stat-label">1-30 Days</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['days_60']); ?></div>
                                    <div class="stat-label">31-60 Days</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['days_90']); ?></div>
                                    <div class="stat-label">61-90 Days</div>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['days_90_plus']); ?></div>
                                    <div class="stat-label">90+ Days</div>
                                </div>
                            </div>
                            <?php elseif ($report_type == 'customer_analysis'): ?>
                            <div class="col-md-4">
                                <div class="stat-item">
                                    <div class="stat-value"><?php echo number_format($summary_stats['top_customers']); ?></div>
                                    <div class="stat-label">Active Customers</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['total_customer_revenue']); ?></div>
                                    <div class="stat-label">Total Revenue</div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="stat-item">
                                    <div class="stat-value">KSh <?php echo number_format($summary_stats['avg_customer_value']); ?></div>
                                    <div class="stat-label">Avg Customer Value</div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Chart Visualization -->
                    <?php if (in_array($report_type, ['revenue_summary', 'profit_loss', 'cash_flow'])): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="chart-container">
                                <div class="d-flex align-items-center justify-content-between mb-3">
                                    <h5 class="mb-0">
                                        <i class="ri-bar-chart-line me-2"></i><?php echo $report_title; ?> - Visual Analysis
                                    </h5>
                                    <div class="btn-group" role="group">
                                        <input type="radio" class="btn-check" name="chartType" id="chartBar" value="bar" checked>
                                        <label class="btn btn-outline-primary btn-sm" for="chartBar">
                                            <i class="ri-bar-chart-line me-1"></i>Bar
                                        </label>
                                        <input type="radio" class="btn-check" name="chartType" id="chartLine" value="line">
                                        <label class="btn btn-outline-primary btn-sm" for="chartLine">
                                            <i class="ri-line-chart-line me-1"></i>Line
                                        </label>
                                        <input type="radio" class="btn-check" name="chartType" id="chartArea" value="area">
                                        <label class="btn btn-outline-primary btn-sm" for="chartArea">
                                            <i class="ri-bar-chart-fill me-1"></i>Area
                                        </label>
                                    </div>
                                </div>
                                <div id="reportChart" style="height: 400px;"></div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Report Data Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="report-card">
                                <div class="card-header bg-transparent border-bottom">
                                    <div class="d-flex align-items-center justify-content-between">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-table-line me-2"></i><?php echo $report_title; ?> - Detailed Data
                                        </h5>
                                        <div class="d-flex gap-2">
                                            <span class="badge bg-info"><?php echo count($report_data); ?> records</span>
                                            <small class="text-muted">
                                                <?php echo date('d M Y', strtotime($date_from)) . ' to ' . date('d M Y', strtotime($date_to)); ?>
                                            </small>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($report_data)): ?>
                                    <div class="text-center py-5">
                                        <i class="ri-file-search-line display-4 text-muted"></i>
                                        <h5 class="mt-3">No Data Available</h5>
                                        <p class="text-muted">No data found for the selected criteria. Try adjusting your filters.</p>
                                        <button class="btn btn-primary" onclick="resetFilters()">
                                            <i class="ri-refresh-line me-1"></i>Reset Filters
                                        </button>
                                    </div>
                                    <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="table table-hover" id="reportTable">
                                            <thead>
                                                <tr>
                                                    <?php if ($report_type == 'revenue_summary'): ?>
                                                    <th>Period</th>
                                                    <th>Service</th>
                                                    <th>Currency</th>
                                                    <th>Shipments</th>
                                                    <th>Total Revenue</th>
                                                    <th>Freight Revenue</th>
                                                    <th>Fuel Surcharge</th>
                                                    <th>Other Charges</th>
                                                    <th>Avg Value</th>
                                                    <?php elseif ($report_type == 'profit_loss'): ?>
                                                    <th colspan="2">Revenue Breakdown</th>
                                                    <?php elseif ($report_type == 'cash_flow'): ?>
                                                    <th>Date</th>
                                                    <th>Customer</th>
                                                    <th>Type</th>
                                                    <th>Amount</th>
                                                    <th>Reference</th>
                                                    <?php elseif ($report_type == 'accounts_receivable'): ?>
                                                    <th>Invoice #</th>
                                                    <th>Customer</th>
                                                    <th>Invoice Date</th>
                                                    <th>Due Date</th>
                                                    <th>Total Amount</th>
                                                    <th>Paid Amount</th>
                                                    <th>Outstanding</th>
                                                    <th>Days Overdue</th>
                                                    <th>Actions</th>
                                                    <?php elseif ($report_type == 'customer_analysis'): ?>
                                                    <th>Customer</th>
                                                    <th>Type</th>
                                                    <th>Contact</th>
                                                    <th>Currency</th>
                                                    <th>Shipments</th>
                                                    <th>Revenue</th>
                                                    <th>Avg Value</th>
                                                    <th>Last Activity</th>
                                                    <th>Actions</th>
                                                    <?php endif; ?>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($report_type == 'revenue_summary'): ?>
                                                    <?php foreach ($report_data as $row): ?>
                                                    <tr>
                                                        <td><?php echo date('M Y', strtotime($row['period'] . '-01')); ?></td>
                                                        <td>
                                                            <span class="badge bg-primary"><?php echo $row['service_name'] ?? 'N/A'; ?></span>
                                                        </td>
                                                        <td>
                                                            <span class="currency-badge currency-<?php echo strtolower($row['currency']); ?>">
                                                                <?php echo $row['currency']; ?>
                                                            </span>
                                                        </td>
                                                        <td class="fw-semibold"><?php echo number_format($row['shipment_count']); ?></td>
                                                        <td class="fw-bold text-success"><?php echo formatCurrency($row['total_revenue'], $row['currency'], $currencies); ?></td>
                                                        <td><?php echo formatCurrency($row['freight_revenue'], $row['currency'], $currencies); ?></td>
                                                        <td><?php echo formatCurrency($row['fuel_surcharge'], $row['currency'], $currencies); ?></td>
                                                        <td><?php echo formatCurrency($row['other_charges'], $row['currency'], $currencies); ?></td>
                                                        <td class="text-info fw-semibold"><?php echo formatCurrency($row['avg_shipment_value'], $row['currency'], $currencies); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    
                                                <?php elseif ($report_type == 'profit_loss'): ?>
                                                    <tr class="table-success">
                                                        <td colspan="2"><strong>REVENUE</strong></td>
                                                    </tr>
                                                    <?php foreach ($report_data['revenue'] as $revenue): ?>
                                                    <tr>
                                                        <td class="ps-3">Total Revenue (<?php echo $revenue['currency']; ?>)</td>
                                                        <td class="text-end fw-bold"><?php echo formatCurrency($revenue['total_revenue'], $revenue['currency'], $currencies); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td class="ps-4">- Freight Charges</td>
                                                        <td class="text-end"><?php echo formatCurrency($revenue['freight_revenue'], $revenue['currency'], $currencies); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td class="ps-4">- Fuel Surcharge</td>
                                                        <td class="text-end"><?php echo formatCurrency($revenue['fuel_revenue'], $revenue['currency'], $currencies); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td class="ps-4">- Other Revenue</td>
                                                        <td class="text-end"><?php echo formatCurrency($revenue['other_revenue'], $revenue['currency'], $currencies); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    
                                                    <tr class="table-danger">
                                                        <td colspan="2"><strong>EXPENSES</strong></td>
                                                    </tr>
                                                    <?php foreach ($report_data['expenses'] as $expense): ?>
                                                    <tr>
                                                        <td class="ps-3"><?php echo $expense['category']; ?></td>
                                                        <td class="text-end fw-semibold"><?php echo formatCurrency($expense['amount'], $expense['currency'], $currencies); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    
                                                    <tr class="table-info">
                                                        <td><strong>NET PROFIT</strong></td>
                                                        <td class="text-end">
                                                            <strong class="<?php echo $summary_stats['net_profit'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                                KSh <?php echo number_format($summary_stats['net_profit'], 2); ?>
                                                            </strong>
                                                        </td>
                                                    </tr>
                                                    
                                                <?php elseif ($report_type == 'cash_flow'): ?>
                                                    <?php foreach ($report_data as $row): ?>
                                                    <tr>
                                                        <td><?php echo date('d/m/Y', strtotime($row['transaction_date'])); ?></td>
                                                        <td>
                                                            <div>
                                                                <div class="fw-semibold"><?php echo htmlspecialchars($row['customer_name']); ?></div>
                                                                <small class="text-muted"><?php echo $row['customer_code']; ?></small>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-success"><?php echo $row['transaction_type']; ?></span>
                                                        </td>
                                                        <td class="text-success fw-bold">+KSh <?php echo number_format($row['amount'], 2); ?></td>
                                                        <td><small class="text-muted"><?php echo $row['reference_number']; ?></small></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    
                                                <?php elseif ($report_type == 'accounts_receivable'): ?>
                                                    <?php foreach ($report_data as $row): ?>
                                                    <tr>
                                                        <td>
                                                            <a href="view_invoice.php?invoice_number=<?php echo $row['invoice_number']; ?>" 
                                                               class="text-primary fw-semibold">
                                                                <?php echo $row['invoice_number']; ?>
                                                            </a>
                                                        </td>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <div class="customer-avatar me-2">
                                                                    <?php echo strtoupper(substr($row['customer_name'], 0, 2)); ?>
                                                                </div>
                                                                <div>
                                                                    <div class="fw-semibold"><?php echo htmlspecialchars($row['customer_name']); ?></div>
                                                                    <small class="text-muted"><?php echo $row['customer_code']; ?></small>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td><?php echo date('d/m/Y', strtotime($row['invoice_date'])); ?></td>
                                                        <td class="<?php echo $row['days_overdue'] > 0 ? 'text-danger fw-bold' : ''; ?>">
                                                            <?php echo date('d/m/Y', strtotime($row['due_date'])); ?>
                                                        </td>
                                                        <td class="fw-semibold">KSh <?php echo number_format($row['total_amount'], 2); ?></td>
                                                        <td class="text-success">KSh <?php echo number_format($row['paid_amount'], 2); ?></td>
                                                        <td class="text-danger fw-bold">KSh <?php echo number_format($row['balance_amount'], 2); ?></td>
                                                        <td>
                                                            <?php if ($row['days_overdue'] > 0): ?>
                                                            <span class="aging-badge aging-<?php echo $row['days_overdue'] > 90 ? '90-plus' : ($row['days_overdue'] > 60 ? '90' : ($row['days_overdue'] > 30 ? '60' : '30')); ?>">
                                                                <?php echo $row['days_overdue']; ?> days
                                                            </span>
                                                            <?php else: ?>
                                                            <span class="aging-badge aging-current">Current</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group" role="group">
                                                                <button class="btn btn-sm btn-outline-primary" onclick="viewInvoice('<?php echo $row['invoice_number']; ?>')">
                                                                    <i class="ri-eye-line"></i>
                                                                </button>
                                                                <button class="btn btn-sm btn-outline-warning" onclick="sendReminder('<?php echo $row['invoice_number']; ?>')">
                                                                    <i class="ri-mail-send-line"></i>
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                    
                                                <?php elseif ($report_type == 'customer_analysis'): ?>
                                                    <?php foreach ($report_data as $row): ?>
                                                    <tr>
                                                        <td>
                                                            <div class="d-flex align-items-center">
                                                                <div class="customer-avatar me-2">
                                                                    <?php echo strtoupper(substr($row['customer_name'], 0, 2)); ?>
                                                                </div>
                                                                <div>
                                                                    <div class="fw-semibold"><?php echo htmlspecialchars($row['customer_name']); ?></div>
                                                                    <small class="text-muted"><?php echo $row['customer_code']; ?></small>
                                                                </div>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <span class="badge bg-<?php echo $row['customer_type'] == 'CORPORATE' ? 'primary' : 'secondary'; ?>">
                                                                <?php echo $row['customer_type']; ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <div>
                                                                <small class="d-block"><?php echo $row['email']; ?></small>
                                                                <small class="text-muted"><?php echo $row['phone']; ?></small>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <span class="currency-badge currency-<?php echo strtolower($row['currency']); ?>">
                                                                <?php echo $row['currency']; ?>
                                                            </span>
                                                        </td>
                                                        <td class="fw-semibold"><?php echo number_format($row['shipment_count']); ?></td>
                                                        <td class="fw-bold text-success">
                                                            <?php echo formatCurrency($row['total_revenue'], $row['currency'], $currencies); ?>
                                                        </td>
                                                        <td class="text-info fw-semibold">
                                                            <?php echo formatCurrency($row['avg_shipment_value'], $row['currency'], $currencies); ?>
                                                        </td>
                                                        <td>
                                                            <div>
                                                                <div><?php echo date('d/m/Y', strtotime($row['last_shipment_date'])); ?></div>
                                                                <small class="text-muted">
                                                                    Since <?php echo date('M Y', strtotime($row['first_shipment_date'])); ?>
                                                                </small>
                                                            </div>
                                                        </td>
                                                        <td>
                                                            <div class="btn-group" role="group">
                                                                <button class="btn btn-sm btn-outline-primary" 
                                                                        onclick="viewCustomerDetails('<?php echo $row['customer_code']; ?>')">
                                                                    <i class="ri-eye-line"></i>
                                                                </button>
                                                                <button class="btn btn-sm btn-outline-success" 
                                                                        onclick="contactCustomer('<?php echo $row['customer_code']; ?>')">
                                                                    <i class="ri-phone-line"></i>
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

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

    <!-- Export Modal -->
    <div class="modal fade" id="exportModal" tabindex="-1" aria-labelledby="exportModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exportModalLabel">
                        <i class="ri-download-line me-2"></i>Export Financial Report
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="exportForm">
                    <div class="modal-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">Export Format</label>
                                <select class="form-select" name="format" required>
                                    <option value="excel">Excel (.xlsx)</option>
                                    <option value="pdf">PDF Report</option>
                                    <option value="csv">CSV Data</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Report Scope</label>
                                <select class="form-select" name="scope">
                                    <option value="current">Current View</option>
                                    <option value="detailed">Detailed Report</option>
                                    <option value="summary">Summary Only</option>
                                </select>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Include Options</label>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="include_summary" id="includeSummary" checked>
                                    <label class="form-check-label" for="includeSummary">
                                        Include Summary Statistics
                                    </label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="include_filters" id="includeFilters" checked>
                                    <label class="form-check-label" for="includeFilters">
                                        Include Filter Information
                                    </label>
                                </div>
                            </div>
                            <div class="col-12">
                                <label class="form-label">Email Recipients (Optional)</label>
                                <input type="email" class="form-control" name="email_recipients" 
                                       placeholder="Enter email addresses separated by commas">
                                <div class="form-text">Leave blank to download only</div>
                            </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-download-line me-1"></i>Export Report
                        </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>
    
    <!-- ApexCharts JS -->
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@latest/dist/apexcharts.min.js"></script>
    
    <script>
    // Global variables
    let reportChart;
    const reportType = '<?php echo $report_type; ?>';
    const reportData = <?php echo json_encode($report_data); ?>;
    
    // Ensure DOM is ready and all scripts are loaded
    $(document).ready(function() {
        // Initialize DataTable
        initializeDataTable();
        
        // Initialize chart if applicable
        if (['revenue_summary', 'profit_loss', 'cash_flow'].includes(reportType)) {
            initializeChart();
        }
        
        // Export form handler
        $('#exportForm').on('submit', function(e) {
            e.preventDefault();
            exportReport();
        });
        
        // Chart type change handler
        $('input[name="chartType"]').on('change', function() {
            if (reportChart) {
                updateChartType(this.value);
            }
        });
    });
    
    function initializeDataTable() {
        const tableConfig = {
            responsive: true,
            pageLength: 25,
            order: [[0, 'desc']],
            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'
                },
                {
                    extend: 'csv',
                    text: '<i class="ri-file-text-line me-1"></i>CSV',
                    className: 'btn btn-info btn-sm'
                }
            ]
        };
        
        // Customize based on report type
        if (reportType === 'revenue_summary') {
            tableConfig.columnDefs = [
                { targets: [3, 4, 5, 6, 7, 8], className: 'text-end' }
            ];
        } else if (reportType === 'accounts_receivable') {
            tableConfig.columnDefs = [
                { targets: [4, 5, 6], className: 'text-end' },
                { targets: [-1], orderable: false }
            ];
        } else if (reportType === 'customer_analysis') {
            tableConfig.columnDefs = [
                { targets: [4, 5, 6], className: 'text-end' },
                { targets: [-1], orderable: false }
            ];
        }
        
        $('#reportTable').DataTable(tableConfig);
    }
    
    function initializeChart() {
        if (!reportData || reportData.length === 0) return;
        
        let chartOptions;
        
        if (reportType === 'revenue_summary') {
            chartOptions = generateRevenueChartOptions();
        } else if (reportType === 'profit_loss') {
            chartOptions = generateProfitLossChartOptions();
        } else if (reportType === 'cash_flow') {
            chartOptions = generateCashFlowChartOptions();
        }
        
        if (chartOptions) {
            reportChart = new ApexCharts(document.querySelector("#reportChart"), chartOptions);
            reportChart.render();
        }
    }
    
    function generateRevenueChartOptions() {
        // Group data by currency and period
        const currencies = [...new Set(reportData.map(item => item.currency))];
        const periods = [...new Set(reportData.map(item => item.period))].sort();
        
        const series = currencies.map(currency => {
            return {
                name: currency + ' Revenue',
                data: periods.map(period => {
                    const item = reportData.find(r => r.period === period && r.currency === currency);
                    return item ? parseFloat(item.total_revenue) : 0;
                })
            };
        });
        
        return {
            series: series,
            chart: {
                type: 'bar',
                height: 400,
                stacked: false,
                toolbar: { show: true }
            },
            plotOptions: {
                bar: {
                    horizontal: false,
                    columnWidth: '55%',
                    endingShape: 'rounded'
                }
            },
            dataLabels: {
                enabled: false
            },
            stroke: {
                show: true,
                width: 2,
                colors: ['transparent']
            },
            xaxis: {
                categories: periods.map(period => new Date(period + '-01').toLocaleDateString('en-US', {month: 'short', year: 'numeric'}))
            },
            yaxis: {
                title: {
                    text: 'Revenue Amount'
                },
                labels: {
                    formatter: function(val) {
                        return val.toLocaleString();
                    }
                }
            },
            fill: {
                opacity: 1
            },
            tooltip: {
                y: {
                    formatter: function(val) {
                        return val.toLocaleString();
                    }
                }
            },
            colors: ['#1e40af', '#059669', '#d97706', '#7c3aed', '#dc2626']
        };
    }
    
    function generateProfitLossChartOptions() {
        <?php if (!empty($summary_stats)): ?>
        return {
            series: [{
                name: 'Amount',
                data: [
                    <?php echo $summary_stats['total_revenue']; ?>,
                    -<?php echo $summary_stats['total_expenses']; ?>,
                    <?php echo $summary_stats['net_profit']; ?>
                ]
            }],
            chart: {
                type: 'bar',
                height: 400
            },
            plotOptions: {
                bar: {
                    colors: {
                        ranges: [{
                            from: -10000000,
                            to: -1,
                            color: '#ef4444'
                        }, {
                            from: 0,
                            to: 10000000,
                            color: '#10b981'
                        }]
                    }
                }
            },
            xaxis: {
                categories: ['Revenue', 'Expenses', 'Net Profit']
            },
            yaxis: {
                labels: {
                    formatter: function(val) {
                        return 'KSh ' + Math.abs(val).toLocaleString();
                    }
                }
            },
            dataLabels: {
                enabled: true,
                formatter: function(val) {
                    return 'KSh ' + Math.abs(val).toLocaleString();
                }
            },
            tooltip: {
                y: {
                    formatter: function(val) {
                        return 'KSh ' + Math.abs(val).toLocaleString();
                    }
                }
            }
        };
        <?php else: ?>
        return null;
        <?php endif; ?>
    }
    
    function generateCashFlowChartOptions() {
        // Group by date
        const groupedData = {};
        reportData.forEach(item => {
            const date = item.transaction_date;
            if (!groupedData[date]) {
                groupedData[date] = 0;
            }
            groupedData[date] += parseFloat(item.amount);
        });
        
        const dates = Object.keys(groupedData).sort();
        const amounts = dates.map(date => groupedData[date]);
        
        return {
            series: [{
                name: 'Cash Inflow',
                data: amounts
            }],
            chart: {
                type: 'area',
                height: 400
            },
            xaxis: {
                categories: dates.map(date => new Date(date).toLocaleDateString('en-US', {month: 'short', day: 'numeric'}))
            },
            yaxis: {
                labels: {
                    formatter: function(val) {
                        return 'KSh ' + val.toLocaleString();
                    }
                }
            },
            fill: {
                type: 'gradient',
                gradient: {
                    shadeIntensity: 1,
                    opacityFrom: 0.7,
                    opacityTo: 0.9,
                    stops: [0, 90, 100]
                }
            },
            colors: ['#10b981']
        };
    }
    
    function updateChartType(chartType) {
        if (!reportChart) return;
        
        reportChart.updateOptions({
            chart: {
                type: chartType
            }
        });
    }
    
    // Global functions accessible from onclick handlers
    window.selectReport = function(type) {
        document.getElementById('report_type_input').value = type;
        document.getElementById('reportForm').submit();
    };
    
    window.showExportModal = function() {
        $('#exportModal').modal('show');
    };
    
    window.exportReport = function() {
        const formData = new FormData($('#exportForm')[0]);
        formData.append('action', 'export_report');
        formData.append('report_type', reportType);
        
        Swal.fire({
            title: 'Generating Export...',
            text: 'Please wait while we prepare your report.',
            icon: 'info',
            allowOutsideClick: false,
            showConfirmButton: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        $.ajax({
            url: '',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Export Ready!',
                        text: 'Your report has been generated successfully.',
                        icon: 'success',
                        showCancelButton: true,
                        confirmButtonText: 'Download Now',
                        cancelButtonText: 'Close'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            // Trigger download
                            const link = document.createElement('a');
                            link.href = response.download_url;
                            link.download = response.download_url.split('/').pop();
                            link.click();
                        }
                        $('#exportModal').modal('hide');
                    });
                } else {
                    Swal.fire('Error', response.message || 'Export failed', 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'An error occurred while generating the export.', 'error');
            }
        });
    };
    
    window.printReport = function() {
        window.print();
    };
    
    window.emailReport = function() {
        Swal.fire({
            title: 'Email Report',
            html: `
                <div class="mb-3">
                    <label class="form-label">Email Recipients:</label>
                    <input type="email" class="form-control" id="emailRecipients" 
                           placeholder="Enter email addresses separated by commas" multiple>
                </div>
                <div class="mb-3">
                    <label class="form-label">Message:</label>
                    <textarea class="form-control" id="emailMessage" rows="3" 
                              placeholder="Optional message to include with the report..."></textarea>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Send Report',
            preConfirm: () => {
                const recipients = document.getElementById('emailRecipients').value;
                const message = document.getElementById('emailMessage').value;
                
                if (!recipients) {
                    Swal.showValidationMessage('Please enter at least one email address');
                    return false;
                }
                
                return { recipients, message };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Sending...',
                    text: 'Please wait while we send your report.',
                    allowOutsideClick: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                        setTimeout(() => {
                            Swal.fire('Success!', 'Report has been sent successfully.', 'success');
                        }, 2000);
                    }
                });
            }
        });
    };
    
    window.resetFilters = function() {
        window.location.href = 'financial_reports.php?report_type=' + reportType;
    };
    
    window.viewInvoice = function(invoiceNumber) {
        window.open(`view_invoice.php?invoice_number=${invoiceNumber}`, '_blank');
    };
    
    window.sendReminder = function(invoiceNumber) {
        Swal.fire({
            title: 'Send Payment Reminder',
            text: `Send a payment reminder for invoice ${invoiceNumber}?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Send Reminder',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Sending...',
                    allowOutsideClick: false,
                    showConfirmButton: false,
                    didOpen: () => {
                        Swal.showLoading();
                        setTimeout(() => {
                            Swal.fire('Success!', 'Payment reminder sent successfully.', 'success');
                        }, 1500);
                    }
                });
            }
        });
    };
    
    window.viewCustomerDetails = function(customerCode) {
        window.open(`view_customer.php?code=${customerCode}`, '_blank');
    };
    
    window.contactCustomer = function(customerCode) {
        Swal.fire({
            title: 'Contact Customer',
            html: `
                <div class="mb-3">
                    <label class="form-label">Contact Method:</label>
                    <select class="form-select" id="contactMethod">
                        <option value="phone">Phone Call</option>
                        <option value="email">Send Email</option>
                        <option value="sms">Send SMS</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Message/Notes:</label>
                    <textarea class="form-control" id="contactMessage" rows="3" 
                              placeholder="Enter your message or call notes..."></textarea>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Proceed',
            preConfirm: () => {
                return {
                    method: document.getElementById('contactMethod').value,
                    message: document.getElementById('contactMessage').value
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                const method = result.value.method;
                if (method === 'phone') {
                    Swal.fire('Info', 'Phone contact initiated. Please use your phone system to make the call.', 'info');
                } else {
                    Swal.fire('Success!', `${method.toUpperCase()} sent successfully.`, 'success');
                }
            }
        });
    };
    </script>

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