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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "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_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Filter parameters
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to = $_GET['date_to'] ?? date('Y-m-t');
$currency_filter = $_GET['currency'] ?? '';
$tax_period = $_GET['tax_period'] ?? 'monthly'; // monthly, quarterly, annual
$report_type = $_GET['report_type'] ?? 'summary'; // summary, detailed, by_service

// Get company base currency and tax settings
$base_currency = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'default_currency'")->fetch_assoc()['setting_value'] ?? 'KES';
$company_tax_id = $conn->query("SELECT setting_value FROM settings WHERE setting_key = 'company_tax_id'")->fetch_assoc()['setting_value'] ?? '';

// Mock exchange rates and tax rates by country/currency
$exchange_rates = [
    'KES' => 1.0000, 'USD' => 0.0067, 'EUR' => 0.0061, 'GBP' => 0.0053,
    'UGX' => 24.85, 'TZS' => 16.75, 'RWF' => 8.95, 'AED' => 0.0246,
    'CNY' => 0.048, 'INR' => 0.558, 'ZAR' => 0.122, 'NGN' => 10.45,
    'GHS' => 0.081, 'ETB' => 0.382, 'EGP' => 0.328, 'MAD' => 0.067, 'DZD' => 0.905
];

// Tax rates by country/currency (VAT/GST rates)
$tax_rates_by_currency = [
    'KES' => ['rate' => 16.0, 'name' => 'VAT', 'country' => 'Kenya'],
    'USD' => ['rate' => 0.0, 'name' => 'N/A', 'country' => 'International'],
    'EUR' => ['rate' => 20.0, 'name' => 'VAT', 'country' => 'EU Average'],
    'GBP' => ['rate' => 20.0, 'name' => 'VAT', 'country' => 'United Kingdom'],
    'UGX' => ['rate' => 18.0, 'name' => 'VAT', 'country' => 'Uganda'],
    'TZS' => ['rate' => 18.0, 'name' => 'VAT', 'country' => 'Tanzania'],
    'RWF' => ['rate' => 18.0, 'name' => 'VAT', 'country' => 'Rwanda'],
    'AED' => ['rate' => 5.0, 'name' => 'VAT', 'country' => 'UAE'],
    'CNY' => ['rate' => 13.0, 'name' => 'VAT', 'country' => 'China'],
    'INR' => ['rate' => 18.0, 'name' => 'GST', 'country' => 'India'],
    'ZAR' => ['rate' => 15.0, 'name' => 'VAT', 'country' => 'South Africa'],
    'NGN' => ['rate' => 7.5, 'name' => 'VAT', 'country' => 'Nigeria']
];

// Currency formatting function
function formatCurrencyAmount($amount, $currency) {
    $symbols = [
        'KES' => 'KSh ', 'USD' => '$', 'EUR' => '€', 'GBP' => '£',
        'UGX' => 'USh ', 'TZS' => 'TSh ', 'RWF' => 'RF ', 'AED' => 'AED ',
        'CNY' => '¥', 'INR' => '₹', 'ZAR' => 'R ', 'NGN' => '₦',
        'GHS' => 'GH₵', 'ETB' => 'Br ', 'EGP' => 'E£', 'MAD' => 'MAD ', 'DZD' => 'DA '
    ];
    
    $symbol = $symbols[$currency] ?? $currency . ' ';
    return $symbol . number_format($amount, 2);
}

// Build where conditions
$where_conditions = ["s.booking_date BETWEEN ? AND ?"];
$params = [$date_from, $date_to];
$param_types = 'ss';

if (!empty($currency_filter)) {
    $where_conditions[] = "s.currency = ?";
    $params[] = $currency_filter;
    $param_types .= 's';
}

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

// Get tax summary by currency
$sql_tax_summary = "SELECT 
                      s.currency,
                      COUNT(*) as shipment_count,
                      SUM(s.freight_charges + s.fuel_surcharge + s.insurance_charges + s.handling_charges + s.customs_charges + s.other_charges) as taxable_amount,
                      SUM(s.tax_amount) as tax_collected,
                      SUM(s.total_charges) as total_revenue,
                      AVG(s.tax_rate) as avg_tax_rate,
                      SUM(CASE WHEN s.payment_status = 'PAID' THEN s.tax_amount ELSE 0 END) as tax_remitted
                    FROM shipments s
                    $where_clause
                    GROUP BY s.currency
                    ORDER BY tax_collected DESC";

$stmt_tax = $conn->prepare($sql_tax_summary);
$stmt_tax->bind_param($param_types, ...$params);
$stmt_tax->execute();
$tax_summary = $stmt_tax->get_result();

// Get tax by service type and currency
$sql_service_tax = "SELECT 
                      s.currency,
                      st.service_name,
                      st.service_category,
                      COUNT(*) as shipment_count,
                      SUM(s.freight_charges + s.fuel_surcharge + s.insurance_charges + s.handling_charges + s.customs_charges + s.other_charges) as taxable_amount,
                      SUM(s.tax_amount) as tax_collected,
                      AVG(s.tax_rate) as avg_tax_rate
                    FROM shipments s
                    LEFT JOIN service_types st ON s.service_id = st.service_id
                    $where_clause
                    GROUP BY s.currency, st.service_id
                    ORDER BY s.currency, tax_collected DESC";

$stmt_service_tax = $conn->prepare($sql_service_tax);
$stmt_service_tax->bind_param($param_types, ...$params);
$stmt_service_tax->execute();
$service_tax = $stmt_service_tax->get_result();

// Get monthly tax trends
$sql_monthly_tax = "SELECT 
                      DATE_FORMAT(s.booking_date, '%Y-%m') as tax_period,
                      s.currency,
                      COUNT(*) as shipment_count,
                      SUM(s.freight_charges + s.fuel_surcharge + s.insurance_charges + s.handling_charges + s.customs_charges + s.other_charges) as taxable_amount,
                      SUM(s.tax_amount) as tax_collected
                    FROM shipments s
                    $where_clause
                    GROUP BY DATE_FORMAT(s.booking_date, '%Y-%m'), s.currency
                    ORDER BY tax_period DESC, s.currency";

$stmt_monthly = $conn->prepare($sql_monthly_tax);
$stmt_monthly->bind_param($param_types, ...$params);
$stmt_monthly->execute();
$monthly_tax = $stmt_monthly->get_result();

// Get unique currencies for filter
$sql_currencies = "SELECT DISTINCT currency FROM shipments WHERE currency IS NOT NULL ORDER BY currency";
$currencies = $conn->query($sql_currencies);

// Calculate consolidated totals
$consolidated_totals = [
    'total_taxable' => 0,
    'total_tax_collected' => 0,
    'total_tax_remitted' => 0,
    'total_shipments' => 0
];

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Tax Reports - Freight Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap5.min.css">
    <!-- SweetAlert2 CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <style>
        .page-content { padding: 1.5rem; }
        .card { border: none; box-shadow: 0 0 20px rgba(0,0,0,0.1); border-radius: 10px; }
        .card-header { background: linear-gradient(45deg, #f8f9fa, #e9ecef); border-bottom: 1px solid #dee2e6; border-radius: 10px 10px 0 0; }
        
        .filter-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 12px; }
        
        .tax-summary-card {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .currency-tax-card {
            border: 1px solid #dee2e6;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            background: white;
            transition: all 0.3s ease;
        }
        
        .currency-tax-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .currency-tax-card.high-tax { border-left: 4px solid #28a745; }
        .currency-tax-card.medium-tax { border-left: 4px solid #ffc107; }
        .currency-tax-card.low-tax { border-left: 4px solid #17a2b8; }
        .currency-tax-card.no-tax { border-left: 4px solid #6c757d; }
        
        .currency-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #e9ecef;
        }
        
        .currency-flag {
            width: 40px;
            height: 30px;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
            font-size: 0.8rem;
        }
        
        .flag-kes { background: #006633; }
        .flag-usd { background: #b22234; }
        .flag-eur { background: #003399; }
        .flag-gbp { background: #012169; }
        .flag-ugx { background: #d90000; }
        .flag-tzs { background: #1eb53a; }
        .flag-rwf { background: #00a1de; }
        .flag-default { background: #6c757d; }
        
        .tax-amount {
            font-family: 'Courier New', monospace;
            font-weight: 700;
            font-size: 1.25rem;
        }
        
        .tax-breakdown {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }
        
        .tax-item {
            text-align: center;
            padding: 0.75rem;
            background: #f8f9fa;
            border-radius: 6px;
        }
        
        .tax-value {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            margin-bottom: 0.25rem;
        }
        
        .tax-label {
            font-size: 0.75rem;
            color: #6c757d;
        }
        
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            border-top: none;
        }
        
        .amount-cell {
            font-family: 'Courier New', monospace;
            font-weight: 600;
        }
        
        .tax-rate-badge {
            font-family: 'Courier New', monospace;
            font-weight: 600;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
        }
        
        .rate-high { background: #d4edda; color: #155724; }
        .rate-medium { background: #fff3cd; color: #856404; }
        .rate-low { background: #cce5ff; color: #004085; }
        .rate-zero { background: #f8f9fa; color: #6c757d; }
        
        .chart-container {
            position: relative;
            height: 400px;
            margin: 1rem 0;
        }
        
        .compliance-status {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 600;
            font-size: 0.875rem;
        }
        
        .status-compliant { background: #d4edda; color: #155724; }
        .status-pending { background: #fff3cd; color: #856404; }
        .status-overdue { background: #f8d7da; color: #721c24; }
        
        .period-selector {
            display: flex;
            gap: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .period-btn {
            padding: 0.5rem 1rem;
            border: 1px solid #dee2e6;
            background: white;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .period-btn.active {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }
        
        .period-btn:hover {
            background: #f8f9fa;
        }
        
        .period-btn.active:hover {
            background: #0056b3;
        }
    </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 Title -->
                    <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">Tax 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 active">Tax Reports</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card filter-card no-print">
                                <div class="card-header">
                                    <h4 class="card-title mb-0 text-white">
                                        <i class="ri-filter-line me-2"></i>Tax Report Filters
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label text-white">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 text-white">Date To</label>
                                            <input type="date" class="form-control" name="date_to" value="<?php echo $date_to; ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label text-white">Currency</label>
                                            <select class="form-control" name="currency">
                                                <option value="">All Currencies</option>
                                                <?php while ($curr = $currencies->fetch_assoc()): ?>
                                                <option value="<?php echo $curr['currency']; ?>" <?php echo $currency_filter === $curr['currency'] ? 'selected' : ''; ?>>
                                                    <?php echo $curr['currency']; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label text-white">Report Type</label>
                                            <select class="form-control" name="report_type">
                                                <option value="summary" <?php echo $report_type === 'summary' ? 'selected' : ''; ?>>Summary</option>
                                                <option value="detailed" <?php echo $report_type === 'detailed' ? 'selected' : ''; ?>>Detailed</option>
                                                <option value="by_service" <?php echo $report_type === 'by_service' ? 'selected' : ''; ?>>By Service</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2 d-flex align-items-end">
                                            <button type="submit" class="btn btn-light me-2">
                                                <i class="ri-search-line me-1"></i> Generate
                                            </button>
                                            <button type="button" class="btn btn-outline-light" onclick="exportReport()">
                                                <i class="ri-download-line me-1"></i> Export
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Tax Summary -->
                    <div class="row">
                        <div class="col-12">
                            <div class="tax-summary-card">
                                <div class="row align-items-center">
                                    <div class="col-md-8">
                                        <h4 class="text-white mb-3">
                                            <i class="ri-receipt-line me-2"></i>Tax Summary Report
                                            <small class="text-white-50 ms-3">
                                                Period: <?php echo date('M j, Y', strtotime($date_from)); ?> - <?php echo date('M j, Y', strtotime($date_to)); ?>
                                            </small>
                                        </h4>
                                        <div class="row">
                                            <div class="col-md-4">
                                                <h6 class="text-white-50 mb-1">Total Tax Collected</h6>
                                                <h3 class="text-white mb-0" id="totalTaxCollected">KSh 0.00</h3>
                                            </div>
                                            <div class="col-md-4">
                                                <h6 class="text-white-50 mb-1">Taxable Revenue</h6>
                                                <h3 class="text-white mb-0" id="totalTaxableRevenue">KSh 0.00</h3>
                                            </div>
                                            <div class="col-md-4">
                                                <h6 class="text-white-50 mb-1">Tax Remitted</h6>
                                                <h3 class="text-white mb-0" id="totalTaxRemitted">KSh 0.00</h3>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4 text-end">
                                        <div class="compliance-status status-compliant">
                                            <i class="ri-shield-check-line me-1"></i>
                                            Tax Compliant
                                        </div>
                                        <small class="text-white-50 mt-2 d-block">
                                            Tax ID: <?php echo $company_tax_id ?: 'Not Set'; ?>
                                        </small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Tax by Currency -->
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3">Tax Analysis by Currency</h5>
                        </div>
                        
                        <?php 
                        $tax_summary->data_seek(0);
                        while ($tax = $tax_summary->fetch_assoc()): 
                            $currency = $tax['currency'];
                            $tax_info = $tax_rates_by_currency[$currency] ?? ['rate' => 0, 'name' => 'N/A', 'country' => 'Unknown'];
                            
                            // Determine tax category
                            $tax_category = 'no-tax';
                            if ($tax_info['rate'] > 15) $tax_category = 'high-tax';
                            elseif ($tax_info['rate'] > 10) $tax_category = 'medium-tax';
                            elseif ($tax_info['rate'] > 0) $tax_category = 'low-tax';
                            
                            // Add to consolidated totals
                            $base_equivalent_taxable = $tax['taxable_amount'] * ($exchange_rates[$currency] ?? 1);
                            $base_equivalent_tax = $tax['tax_collected'] * ($exchange_rates[$currency] ?? 1);
                            $base_equivalent_remitted = $tax['tax_remitted'] * ($exchange_rates[$currency] ?? 1);
                            
                            $consolidated_totals['total_taxable'] += $base_equivalent_taxable;
                            $consolidated_totals['total_tax_collected'] += $base_equivalent_tax;
                            $consolidated_totals['total_tax_remitted'] += $base_equivalent_remitted;
                            $consolidated_totals['total_shipments'] += $tax['shipment_count'];
                        ?>
                        <div class="col-xl-6 col-lg-12">
                            <div class="currency-tax-card <?php echo $tax_category; ?>">
                                <div class="currency-header">
                                    <div class="d-flex align-items-center">
                                        <div class="currency-flag flag-<?php echo strtolower($currency); ?> me-3"><?php echo $currency; ?></div>
                                        <div>
                                            <h6 class="mb-0"><?php echo $currency; ?> Tax Summary</h6>
                                            <small class="text-muted">
                                                <?php echo $tax_info['country']; ?> - <?php echo $tax_info['name']; ?> <?php echo number_format($tax_info['rate'], 1); ?>%
                                            </small>
                                        </div>
                                    </div>
                                    <div class="tax-rate-badge rate-<?php echo $tax_info['rate'] > 15 ? 'high' : ($tax_info['rate'] > 10 ? 'medium' : ($tax_info['rate'] > 0 ? 'low' : 'zero')); ?>">
                                        <?php echo number_format($tax_info['rate'], 1); ?>%
                                    </div>
                                </div>
                                
                                <div class="tax-breakdown">
                                    <div class="tax-item">
                                        <div class="tax-value">
                                            <?php echo formatCurrencyAmount($tax['taxable_amount'], $currency); ?>
                                        </div>
                                        <div class="tax-label">Taxable Revenue</div>
                                    </div>
                                    
                                    <div class="tax-item">
                                        <div class="tax-value">
                                            <?php echo formatCurrencyAmount($tax['tax_collected'], $currency); ?>
                                        </div>
                                        <div class="tax-label">Tax Collected</div>
                                    </div>
                                    
                                    <div class="tax-item">
                                        <div class="tax-value">
                                            <?php echo formatCurrencyAmount($tax['tax_remitted'], $currency); ?>
                                        </div>
                                        <div class="tax-label">Tax Remitted</div>
                                    </div>
                                    
                                    <div class="tax-item">
                                        <div class="tax-value">
                                            <?php echo number_format($tax['shipment_count']); ?>
                                        </div>
                                        <div class="tax-label">Shipments</div>
                                    </div>
                                </div>
                                
                                <div class="mt-3 pt-3 border-top">
                                    <div class="row">
                                        <div class="col-6">
                                            <small class="text-muted">Effective Tax Rate:</small>
                                            <div class="tax-rate-badge rate-<?php echo $tax['avg_tax_rate'] > 15 ? 'high' : ($tax['avg_tax_rate'] > 10 ? 'medium' : 'low'); ?>">
                                                <?php echo number_format($tax['avg_tax_rate'], 2); ?>%
                                            </div>
                                        </div>
                                        <div class="col-6">
                                            <small class="text-muted">Base Equivalent:</small>
                                            <div class="tax-amount" style="font-size: 1rem;">
                                                <?php echo formatCurrencyAmount($base_equivalent_tax, $base_currency); ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endwhile; ?>
                    </div>

                    <!-- Service-wise Tax Analysis -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-service-line me-2"></i>Tax by Service Type
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <table id="serviceTaxTable" class="table table-striped table-hover dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Currency</th>
                                                <th>Service</th>
                                                <th>Category</th>
                                                <th>Shipments</th>
                                                <th>Taxable Amount</th>
                                                <th>Tax Collected</th>
                                                <th>Effective Rate</th>
                                                <th>Country Rate</th>
                                                <th>Compliance</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($service = $service_tax->fetch_assoc()): 
                                                $currency = $service['currency'];
                                                $tax_info = $tax_rates_by_currency[$currency] ?? ['rate' => 0, 'name' => 'N/A'];
                                                $compliance = abs($service['avg_tax_rate'] - $tax_info['rate']) <= 1 ? 'compliant' : 'non-compliant';
                                            ?>
                                            <tr>
                                                <td>
                                                    <span class="currency-flag flag-<?php echo strtolower($currency); ?>"><?php echo $currency; ?></span>
                                                </td>
                                                <td><?php echo $service['service_name']; ?></td>
                                                <td>
                                                    <span class="badge bg-primary"><?php echo $service['service_category']; ?></span>
                                                </td>
                                                <td class="text-center"><?php echo number_format($service['shipment_count']); ?></td>
                                                <td class="amount-cell">
                                                    <?php echo formatCurrencyAmount($service['taxable_amount'], $currency); ?>
                                                </td>
                                                <td class="amount-cell">
                                                    <?php echo formatCurrencyAmount($service['tax_collected'], $currency); ?>
                                                </td>
                                                <td class="text-center">
                                                    <span class="tax-rate-badge rate-<?php echo $service['avg_tax_rate'] > 15 ? 'high' : ($service['avg_tax_rate'] > 10 ? 'medium' : ($service['avg_tax_rate'] > 0 ? 'low' : 'zero')); ?>">
                                                        <?php echo number_format($service['avg_tax_rate'], 2); ?>%
                                                    </span>
                                                </td>
                                                <td class="text-center">
                                                    <span class="tax-rate-badge rate-<?php echo $tax_info['rate'] > 15 ? 'high' : ($tax_info['rate'] > 10 ? 'medium' : ($tax_info['rate'] > 0 ? 'low' : 'zero')); ?>">
                                                        <?php echo number_format($tax_info['rate'], 1); ?>%
                                                    </span>
                                                </td>
                                                <td>
                                                    <span class="compliance-status status-<?php echo $compliance; ?>">
                                                        <i class="ri-<?php echo $compliance === 'compliant' ? 'check' : 'error-warning'; ?>-line me-1"></i>
                                                        <?php echo ucfirst($compliance); ?>
                                                    </span>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Monthly Tax Trends -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-line-chart-line me-2"></i>Tax Collection Trends
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <div class="period-selector">
                                        <button class="period-btn active" onclick="updatePeriod('monthly')">Monthly</button>
                                        <button class="period-btn" onclick="updatePeriod('quarterly')">Quarterly</button>
                                        <button class="period-btn" onclick="updatePeriod('annual')">Annual</button>
                                    </div>
                                    
                                    <table id="monthlyTaxTable" class="table table-striped table-hover dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Period</th>
                                                <th>Currency</th>
                                                <th>Shipments</th>
                                                <th>Taxable Amount</th>
                                                <th>Tax Collected</th>
                                                <th>Base Equivalent</th>
                                                <th>Growth</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $previous_amounts = [];
                                            while ($monthly = $monthly_tax->fetch_assoc()): 
                                                $currency = $monthly['currency'];
                                                $base_equivalent = $monthly['tax_collected'] * ($exchange_rates[$currency] ?? 1);
                                                
                                                // Calculate growth (mock calculation)
                                                $growth = 0;
                                                if (isset($previous_amounts[$currency])) {
                                                    $growth = (($monthly['tax_collected'] - $previous_amounts[$currency]) / $previous_amounts[$currency]) * 100;
                                                }
                                                $previous_amounts[$currency] = $monthly['tax_collected'];
                                            ?>
                                            <tr>
                                                <td><?php echo date('M Y', strtotime($monthly['tax_period'] . '-01')); ?></td>
                                                <td>
                                                    <span class="currency-flag flag-<?php echo strtolower($currency); ?>"><?php echo $currency; ?></span>
                                                </td>
                                                <td class="text-center"><?php echo number_format($monthly['shipment_count']); ?></td>
                                                <td class="amount-cell">
                                                    <?php echo formatCurrencyAmount($monthly['taxable_amount'], $currency); ?>
                                                </td>
                                                <td class="amount-cell">
                                                    <?php echo formatCurrencyAmount($monthly['tax_collected'], $currency); ?>
                                                </td>
                                                <td class="amount-cell">
                                                    <?php echo formatCurrencyAmount($base_equivalent, $base_currency); ?>
                                                </td>
                                                <td class="text-center">
                                                    <?php if ($growth != 0): ?>
                                                    <span class="badge bg-<?php echo $growth > 0 ? 'success' : 'danger'; ?>">
                                                        <i class="ri-arrow-<?php echo $growth > 0 ? 'up' : 'down'; ?>-line me-1"></i>
                                                        <?php echo number_format(abs($growth), 1); ?>%
                                                    </span>
                                                    <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Tax Charts -->
                    <div class="row">
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Tax by Currency</h4>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="taxByCurrencyChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Tax Rate Compliance</h4>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="complianceChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- 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/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>
    <script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Update consolidated totals
            $('#totalTaxCollected').text('<?php echo formatCurrencyAmount($consolidated_totals['total_tax_collected'], $base_currency); ?>');
            $('#totalTaxableRevenue').text('<?php echo formatCurrencyAmount($consolidated_totals['total_taxable'], $base_currency); ?>');
            $('#totalTaxRemitted').text('<?php echo formatCurrencyAmount($consolidated_totals['total_tax_remitted'], $base_currency); ?>');
            
            // Initialize DataTables
            $('#serviceTaxTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[5, 'desc']], // Sort by tax collected
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'excel',
                        text: '<i class="ri-file-excel-line"></i> Excel',
                        className: 'btn btn-success btn-sm',
                        title: 'Service Tax Analysis'
                    },
                    {
                        extend: 'csv',
                        text: '<i class="ri-file-text-line"></i> CSV',
                        className: 'btn btn-info btn-sm'
                    }
                ],
                columnDefs: [
                    { targets: [3], className: 'text-center' },
                    { targets: [4, 5], className: 'text-end' },
                    { targets: [6, 7, 8], className: 'text-center' }
                ]
            });
            
            $('#monthlyTaxTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']], // Sort by period
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'excel',
                        text: '<i class="ri-file-excel-line"></i> Excel',
                        className: 'btn btn-success btn-sm',
                        title: 'Monthly Tax Trends'
                    }
                ],
                columnDefs: [
                    { targets: [2], className: 'text-center' },
                    { targets: [3, 4, 5], className: 'text-end' },
                    { targets: [6], className: 'text-center' }
                ]
            });
            
            // Initialize Charts
            initializeTaxCharts();
        });
        
        function initializeTaxCharts() {
            // Tax by Currency Chart
            const ctx1 = document.getElementById('taxByCurrencyChart').getContext('2d');
            const taxData = <?php 
                $tax_summary->data_seek(0);
                $chart_data = [];
                while ($row = $tax_summary->fetch_assoc()) {
                    $chart_data[] = [
                        'currency' => $row['currency'],
                        'tax_collected' => $row['tax_collected'],
                        'taxable_amount' => $row['taxable_amount']
                    ];
                }
                echo json_encode($chart_data);
            ?>;
            
            new Chart(ctx1, {
                type: 'bar',
                data: {
                    labels: taxData.map(item => item.currency),
                    datasets: [{
                        label: 'Tax Collected',
                        data: taxData.map(item => item.tax_collected),
                        backgroundColor: '#28a745',
                        borderColor: '#1e7e34',
                        borderWidth: 1
                    }, {
                        label: 'Taxable Amount',
                        data: taxData.map(item => item.taxable_amount),
                        backgroundColor: '#17a2b8',
                        borderColor: '#138496',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });
            
            // Compliance Chart
            const ctx2 = document.getElementById('complianceChart').getContext('2d');
            new Chart(ctx2, {
                type: 'doughnut',
                data: {
                    labels: ['Compliant', 'Non-Compliant', 'Under Review'],
                    datasets: [{
                        data: [85, 10, 5], // Mock compliance data
                        backgroundColor: ['#28a745', '#dc3545', '#ffc107'],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }
        
        function updatePeriod(period) {
            // Update active period button
            document.querySelectorAll('.period-btn').forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');
            
            // In a real application, this would reload data for the selected period
            Swal.fire({
                title: 'Period Updated',
                text: `Switched to ${period} view`,
                icon: 'info',
                timer: 1500,
                showConfirmButton: false
            });
        }
        
        function exportReport() {
            Swal.fire({
                title: 'Export Tax Report',
                text: 'Choose export format:',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Excel',
                cancelButtonText: 'CSV',
                showDenyButton: true,
                denyButtonText: 'PDF'
            }).then((result) => {
                if (result.isConfirmed) {
                    exportToExcel();
                } else if (result.isDenied) {
                    exportToPDF();
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    exportToCSV();
                }
            });
        }
        
        function exportToExcel() {
            $('#serviceTaxTable').DataTable().button('.buttons-excel').trigger();
        }
        
        function exportToCSV() {
            $('#serviceTaxTable').DataTable().button('.buttons-csv').trigger();
        }
        
        function exportToPDF() {
            Swal.fire('Tax report PDF export functionality would be implemented here', '', 'info');
        }
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>