<?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'] ?? '';
$period_type = $_GET['period_type'] ?? 'daily'; // daily, weekly, monthly

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

// Mock exchange rates
$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
];

// 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 = [];
$params = [];
$param_types = '';

if (!empty($currency_filter)) {
    $currency_where = "currency = ?";
    $currency_params = [$currency_filter];
    $currency_types = 's';
} else {
    $currency_where = "1=1";
    $currency_params = [];
    $currency_types = '';
}

// Get period grouping SQL
$period_group = match($period_type) {
    'weekly' => "YEARWEEK(DATE_COLUMN, 1)",
    'monthly' => "DATE_FORMAT(DATE_COLUMN, '%Y-%m')",
    default => "DATE(DATE_COLUMN)"
};

$period_format = match($period_type) {
    'weekly' => "CONCAT(YEAR(DATE_COLUMN), '-W', LPAD(WEEK(DATE_COLUMN, 1), 2, '0'))",
    'monthly' => "DATE_FORMAT(DATE_COLUMN, '%Y-%m')",
    default => "DATE(DATE_COLUMN)"
};

// Cash Inflows - Payments Received
$sql_inflows = "SELECT 
                  " . str_replace('DATE_COLUMN', 'p.payment_date', $period_format) . " as period,
                  p.payment_method as source_type,
                  'Payment Received' as transaction_type,
                  COUNT(*) as transaction_count,
                  SUM(p.amount) as amount,
                  'KES' as currency
                FROM payments p
                WHERE p.payment_date BETWEEN ? AND ?
                  AND p.status = 'CONFIRMED'
                GROUP BY " . str_replace('DATE_COLUMN', 'p.payment_date', $period_group) . ", p.payment_method
                
                UNION ALL
                
                SELECT 
                  " . str_replace('DATE_COLUMN', 's.booking_date', $period_format) . " as period,
                  st.service_category as source_type,
                  'Revenue Recognition' as transaction_type,
                  COUNT(*) as transaction_count,
                  SUM(s.total_charges) as amount,
                  s.currency
                FROM shipments s
                LEFT JOIN service_types st ON s.service_id = st.service_id
                WHERE s.booking_date BETWEEN ? AND ?
                  AND s.payment_status = 'PAID'
                  AND ($currency_where)
                " . (!empty($currency_filter) ? "" : "") . "
                GROUP BY " . str_replace('DATE_COLUMN', 's.booking_date', $period_group) . ", st.service_category, s.currency
                
                ORDER BY period DESC, currency, source_type";

$stmt_inflows = $conn->prepare($sql_inflows);
$inflow_params = array_merge([$date_from, $date_to, $date_from, $date_to], $currency_params);
$inflow_types = 'ssss' . $currency_types;
$stmt_inflows->bind_param($inflow_types, ...$inflow_params);
$stmt_inflows->execute();
$cash_inflows = $stmt_inflows->get_result();

// Cash Outflows - Operating Expenses (Mock data - in real system would come from expense tracking)
$mock_outflows = [
    ['period' => $date_from, 'expense_type' => 'Fuel Costs', 'transaction_type' => 'Operating Expense', 'amount' => 150000, 'currency' => 'KES'],
    ['period' => $date_from, 'expense_type' => 'Vehicle Maintenance', 'transaction_type' => 'Operating Expense', 'amount' => 85000, 'currency' => 'KES'],
    ['period' => $date_from, 'expense_type' => 'Staff Salaries', 'transaction_type' => 'Payroll', 'amount' => 280000, 'currency' => 'KES'],
    ['period' => $date_from, 'expense_type' => 'Warehouse Rent', 'transaction_type' => 'Fixed Costs', 'amount' => 120000, 'currency' => 'KES'],
    ['period' => $date_from, 'expense_type' => 'Insurance', 'transaction_type' => 'Fixed Costs', 'amount' => 45000, 'currency' => 'KES'],
    ['period' => $date_from, 'expense_type' => 'International Fees', 'transaction_type' => 'Operating Expense', 'amount' => 5500, 'currency' => 'USD'],
    ['period' => $date_from, 'expense_type' => 'Equipment', 'transaction_type' => 'Capital Expense', 'amount' => 2800, 'currency' => 'USD'],
];

// Get current cash balances by currency (Mock data - integrate with bank APIs)
$mock_cash_balances = [
    'KES' => 2456789.50,
    'USD' => 45678.25,
    'EUR' => 12350.75,
    'GBP' => 8950.00,
    'UGX' => 185000000.00,
    'TZS' => 156000000.00
];

// Calculate cash flow summary
$cash_flow_summary = [];
$total_inflows = 0;
$total_outflows = 0;

// Process inflows
$inflows_by_currency = [];
while ($inflow = $cash_inflows->fetch_assoc()) {
    $currency = $inflow['currency'];
    if (!isset($inflows_by_currency[$currency])) {
        $inflows_by_currency[$currency] = 0;
    }
    $inflows_by_currency[$currency] += $inflow['amount'];
    $total_inflows += $inflow['amount'] * ($exchange_rates[$currency] ?? 1);
}

// Process outflows
$outflows_by_currency = [];
foreach ($mock_outflows as $outflow) {
    $currency = $outflow['currency'];
    if (!isset($outflows_by_currency[$currency])) {
        $outflows_by_currency[$currency] = 0;
    }
    $outflows_by_currency[$currency] += $outflow['amount'];
    $total_outflows += $outflow['amount'] * ($exchange_rates[$currency] ?? 1);
}

// Get unique currencies
$all_currencies = array_unique(array_merge(array_keys($inflows_by_currency), array_keys($outflows_by_currency), array_keys($mock_cash_balances)));
sort($all_currencies);

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Cash Flow Report - 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">
    <!-- 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; }
        
        .balance-card {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            position: relative;
            overflow: hidden;
        }
        
        .balance-card::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 100%;
            height: 100%;
            background: rgba(255,255,255,0.1);
            transform: rotate(45deg);
        }
        
        .cash-flow-card {
            border: 1px solid #dee2e6;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            background: white;
            transition: all 0.3s ease;
        }
        
        .cash-flow-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .cash-flow-card.inflow { border-left: 4px solid #28a745; }
        .cash-flow-card.outflow { border-left: 4px solid #dc3545; }
        .cash-flow-card.net-positive { border-left: 4px solid #17a2b8; }
        .cash-flow-card.net-negative { border-left: 4px solid #fd7e14; }
        
        .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-default { background: #6c757d; }
        
        .cash-amount {
            font-family: 'Courier New', monospace;
            font-weight: 700;
            font-size: 1.5rem;
        }
        
        .flow-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem;
            margin-bottom: 0.5rem;
            background: #f8f9fa;
            border-radius: 6px;
        }
        
        .flow-amount {
            font-family: 'Courier New', monospace;
            font-weight: 600;
        }
        
        .positive-flow { color: #28a745; }
        .negative-flow { color: #dc3545; }
        .neutral-flow { color: #6c757d; }
        
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .chart-container {
            position: relative;
            height: 400px;
            margin: 1rem 0;
        }
        
        .table th {
            background-color: #f8f9fa;
            font-weight: 600;
            border-top: none;
        }
    </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">Cash Flow Report</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">Cash Flow</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>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-3">
                                            <label class="form-label text-white">Currency</label>
                                            <select class="form-control" name="currency">
                                                <option value="">All Currencies</option>
                                                <?php foreach ($all_currencies as $curr): ?>
                                                <option value="<?php echo $curr; ?>" <?php echo $currency_filter === $curr ? 'selected' : ''; ?>>
                                                    <?php echo $curr; ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label text-white">Period</label>
                                            <select class="form-control" name="period_type">
                                                <option value="daily" <?php echo $period_type === 'daily' ? 'selected' : ''; ?>>Daily</option>
                                                <option value="weekly" <?php echo $period_type === 'weekly' ? 'selected' : ''; ?>>Weekly</option>
                                                <option value="monthly" <?php echo $period_type === 'monthly' ? 'selected' : ''; ?>>Monthly</option>
                                            </select>
                                        </div>
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-light">
                                                <i class="ri-search-line me-1"></i> Generate Report
                                            </button>
                                            <button type="button" class="btn btn-outline-light" onclick="exportReport()">
                                                <i class="ri-download-line me-1"></i> Export
                                            </button>
                                            <button type="button" class="btn btn-outline-light" onclick="window.print()">
                                                <i class="ri-printer-line me-1"></i> Print
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Current Cash Balances -->
                    <div class="row">
                        <div class="col-12">
                            <h5 class="mb-3">Current Cash Balances</h5>
                        </div>
                        <?php foreach ($mock_cash_balances as $currency => $balance): ?>
                        <div class="col-xl-4 col-md-6">
                            <div class="balance-card">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div>
                                        <div class="currency-flag flag-<?php echo strtolower($currency); ?> mb-2"><?php echo $currency; ?></div>
                                        <h6 class="text-white-50 mb-1">Available Balance</h6>
                                        <div class="cash-amount">
                                            <?php echo formatCurrencyAmount($balance, $currency); ?>
                                        </div>
                                        <small class="text-white-50">
                                            Equivalent: <?php echo formatCurrencyAmount($balance * ($exchange_rates[$currency] ?? 1), $base_currency); ?>
                                        </small>
                                    </div>
                                    <div class="avatar-sm">
                                        <span class="avatar-title bg-white bg-opacity-25 rounded">
                                            <i class="ri-wallet-line fs-4"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Cash Flow Summary -->
                    <div class="summary-grid">
                        <div class="cash-flow-card inflow">
                            <h6 class="text-muted mb-2">Total Cash Inflows</h6>
                            <div class="cash-amount positive-flow">
                                <?php echo formatCurrencyAmount($total_inflows, $base_currency); ?>
                            </div>
                            <small class="text-muted">Payments & Revenue</small>
                        </div>
                        
                        <div class="cash-flow-card outflow">
                            <h6 class="text-muted mb-2">Total Cash Outflows</h6>
                            <div class="cash-amount negative-flow">
                                <?php echo formatCurrencyAmount($total_outflows, $base_currency); ?>
                            </div>
                            <small class="text-muted">Operating Expenses</small>
                        </div>
                        
                        <div class="cash-flow-card <?php echo ($total_inflows - $total_outflows) >= 0 ? 'net-positive' : 'net-negative'; ?>">
                            <h6 class="text-muted mb-2">Net Cash Flow</h6>
                            <div class="cash-amount <?php echo ($total_inflows - $total_outflows) >= 0 ? 'positive-flow' : 'negative-flow'; ?>">
                                <?php echo formatCurrencyAmount($total_inflows - $total_outflows, $base_currency); ?>
                            </div>
                            <small class="text-muted">Period Net Flow</small>
                        </div>
                    </div>

                    <!-- Cash Flow by Currency -->
                    <div class="row">
                        <?php foreach ($all_currencies as $currency): 
                            $inflow_amount = $inflows_by_currency[$currency] ?? 0;
                            $outflow_amount = $outflows_by_currency[$currency] ?? 0;
                            $net_flow = $inflow_amount - $outflow_amount;
                        ?>
                        <div class="col-xl-4 col-md-6">
                            <div class="cash-flow-card">
                                <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>
                                        <h6 class="mb-0"><?php echo $currency; ?> Cash Flow</h6>
                                    </div>
                                </div>
                                
                                <div class="flow-item">
                                    <div>
                                        <i class="ri-arrow-down-line text-success me-2"></i>
                                        <strong>Cash Inflows</strong>
                                    </div>
                                    <div class="flow-amount positive-flow">
                                        <?php echo formatCurrencyAmount($inflow_amount, $currency); ?>
                                    </div>
                                </div>
                                
                                <div class="flow-item">
                                    <div>
                                        <i class="ri-arrow-up-line text-danger me-2"></i>
                                        <strong>Cash Outflows</strong>
                                    </div>
                                    <div class="flow-amount negative-flow">
                                        <?php echo formatCurrencyAmount($outflow_amount, $currency); ?>
                                    </div>
                                </div>
                                
                                <div class="flow-item" style="background: #e9ecef; font-weight: bold;">
                                    <div>
                                        <i class="ri-calculator-line me-2"></i>
                                        <strong>Net Flow</strong>
                                    </div>
                                    <div class="flow-amount <?php echo $net_flow >= 0 ? 'positive-flow' : 'negative-flow'; ?>">
                                        <?php echo formatCurrencyAmount($net_flow, $currency); ?>
                                    </div>
                                </div>
                                
                                <div class="mt-3 pt-3 border-top">
                                    <small class="text-muted">
                                        <strong>Equivalent in <?php echo $base_currency; ?>:</strong>
                                        <?php echo formatCurrencyAmount($net_flow * ($exchange_rates[$currency] ?? 1), $base_currency); ?>
                                    </small>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>

                    <!-- Detailed Cash Inflows -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-arrow-down-circle-line text-success me-2"></i>Cash Inflows Detail
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <table id="inflowsTable" class="table table-striped table-hover dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Period</th>
                                                <th>Source Type</th>
                                                <th>Transaction Type</th>
                                                <th>Currency</th>
                                                <th>Count</th>
                                                <th>Amount</th>
                                                <th>Base Equivalent</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            $cash_inflows->data_seek(0);
                                            while ($inflow = $cash_inflows->fetch_assoc()): 
                                                $base_equivalent = $inflow['amount'] * ($exchange_rates[$inflow['currency']] ?? 1);
                                            ?>
                                            <tr>
                                                <td><?php echo date('M j, Y', strtotime($inflow['period'])); ?></td>
                                                <td><?php echo $inflow['source_type']; ?></td>
                                                <td>
                                                    <span class="badge bg-success"><?php echo $inflow['transaction_type']; ?></span>
                                                </td>
                                                <td>
                                                    <span class="currency-flag flag-<?php echo strtolower($inflow['currency']); ?>"><?php echo $inflow['currency']; ?></span>
                                                </td>
                                                <td><?php echo number_format($inflow['transaction_count']); ?></td>
                                                <td class="flow-amount positive-flow">
                                                    <?php echo formatCurrencyAmount($inflow['amount'], $inflow['currency']); ?>
                                                </td>
                                                <td class="flow-amount">
                                                    <?php echo formatCurrencyAmount($base_equivalent, $base_currency); ?>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Mock Cash Outflows -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">
                                        <i class="ri-arrow-up-circle-line text-danger me-2"></i>Cash Outflows Detail
                                    </h4>
                                </div>
                                <div class="card-body">
                                    <table id="outflowsTable" class="table table-striped table-hover dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Period</th>
                                                <th>Expense Type</th>
                                                <th>Transaction Type</th>
                                                <th>Currency</th>
                                                <th>Amount</th>
                                                <th>Base Equivalent</th>
                                                <th>Status</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($mock_outflows as $outflow): 
                                                $base_equivalent = $outflow['amount'] * ($exchange_rates[$outflow['currency']] ?? 1);
                                            ?>
                                            <tr>
                                                <td><?php echo date('M j, Y', strtotime($outflow['period'])); ?></td>
                                                <td><?php echo $outflow['expense_type']; ?></td>
                                                <td>
                                                    <span class="badge bg-danger"><?php echo $outflow['transaction_type']; ?></span>
                                                </td>
                                                <td>
                                                    <span class="currency-flag flag-<?php echo strtolower($outflow['currency']); ?>"><?php echo $outflow['currency']; ?></span>
                                                </td>
                                                <td class="flow-amount negative-flow">
                                                    <?php echo formatCurrencyAmount($outflow['amount'], $outflow['currency']); ?>
                                                </td>
                                                <td class="flow-amount">
                                                    <?php echo formatCurrencyAmount($base_equivalent, $base_currency); ?>
                                                </td>
                                                <td>
                                                    <span class="badge bg-success">Paid</span>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Cash Flow Charts -->
                    <div class="row">
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Cash Flow Trend</h4>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="cashFlowChart"></canvas>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Currency Distribution</h4>
                                </div>
                                <div class="card-body">
                                    <div class="chart-container">
                                        <canvas id="currencyChart"></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>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTables
            $('#inflowsTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']],
                columnDefs: [
                    { targets: [4], className: 'text-center' },
                    { targets: [5, 6], className: 'text-end' }
                ]
            });
            
            $('#outflowsTable').DataTable({
                responsive: true,
                pageLength: 25,
                order: [[0, 'desc']],
                columnDefs: [
                    { targets: [4, 5], className: 'text-end' }
                ]
            });
            
            // Initialize Charts
            initializeCashFlowCharts();
        });
        
        function initializeCashFlowCharts() {
            // Cash Flow Trend Chart
            const ctx1 = document.getElementById('cashFlowChart').getContext('2d');
            new Chart(ctx1, {
                type: 'line',
                data: {
                    labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
                    datasets: [{
                        label: 'Cash Inflows',
                        data: [<?php echo $total_inflows * 0.2; ?>, <?php echo $total_inflows * 0.3; ?>, <?php echo $total_inflows * 0.25; ?>, <?php echo $total_inflows * 0.25; ?>],
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'Cash Outflows',
                        data: [<?php echo $total_outflows * 0.25; ?>, <?php echo $total_outflows * 0.2; ?>, <?php echo $total_outflows * 0.3; ?>, <?php echo $total_outflows * 0.25; ?>],
                        borderColor: '#dc3545',
                        backgroundColor: 'rgba(220, 53, 69, 0.1)',
                        tension: 0.4
                    }, {
                        label: 'Net Cash Flow',
                        data: [
                            <?php echo ($total_inflows * 0.2) - ($total_outflows * 0.25); ?>,
                            <?php echo ($total_inflows * 0.3) - ($total_outflows * 0.2); ?>,
                            <?php echo ($total_inflows * 0.25) - ($total_outflows * 0.3); ?>,
                            <?php echo ($total_inflows * 0.25) - ($total_outflows * 0.25); ?>
                        ],
                        borderColor: '#007bff',
                        backgroundColor: 'rgba(0, 123, 255, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: {
                                callback: function(value) {
                                    return value.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });
            
            // Currency Distribution Chart
            const ctx2 = document.getElementById('currencyChart').getContext('2d');
            new Chart(ctx2, {
                type: 'doughnut',
                data: {
                    labels: <?php echo json_encode($all_currencies); ?>,
                    datasets: [{
                        data: [
                            <?php 
                            $data_points = [];
                            foreach ($all_currencies as $curr) {
                                $balance = $mock_cash_balances[$curr] ?? 0;
                                $base_equivalent = $balance * ($exchange_rates[$curr] ?? 1);
                                $data_points[] = $base_equivalent;
                            }
                            echo implode(',', $data_points);
                            ?>
                        ],
                        backgroundColor: [
                            '#667eea', '#764ba2', '#f093fb', '#f5576c',
                            '#4facfe', '#00f2fe', '#43e97b', '#38f9d7'
                        ],
                        borderWidth: 2,
                        borderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const currency = context.label;
                                    const value = context.parsed;
                                    return `${currency}: ${value.toLocaleString()} <?php echo $base_currency; ?>`;
                                }
                            }
                        }
                    }
                }
            });
        }
        
        function exportReport() {
            Swal.fire({
                title: 'Export Cash Flow 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) {
                    Swal.fire('PDF export functionality can be implemented here', '', 'info');
                } else if (result.dismiss === Swal.DismissReason.cancel) {
                    exportToCSV();
                }
            });
        }
        
        function exportToExcel() {
            // Generate Excel export with cash flow data
            const data = {
                inflows: <?php 
                    $cash_inflows->data_seek(0);
                    $inflow_data = [];
                    while ($row = $cash_inflows->fetch_assoc()) {
                        $inflow_data[] = $row;
                    }
                    echo json_encode($inflow_data);
                ?>,
                outflows: <?php echo json_encode($mock_outflows); ?>,
                balances: <?php echo json_encode($mock_cash_balances); ?>
            };
            
            Swal.fire('Excel export with cash flow data would be generated here', '', 'info');
        }
        
        function exportToCSV() {
            Swal.fire('CSV export with cash flow data would be generated here', '', 'info');
        }
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>