<?php
/**
 * ============================================================================
 * farm/reports.php - Enhanced Financial Reports & Analytics
 * ============================================================================
 */
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

requireLogin();

if (getUserType() !== 'farmer') {
    redirect('/dashboard/', 'Only farmers can access farm management', 'error');
}

$pageTitle = 'Financial Reports';
$userId = getUserId();

// Get database connection
$database = new Database();
$db = $database->getConnection();

// Get transaction class
$transactionClass = new \App\Transaction($db);

// Get monthly summary for last 6 months
$monthlySummary = $transactionClass->getMonthlySummary($userId, 6);

// Get category breakdown
$incomeBreakdown = $transactionClass->getCategoryBreakdown($userId, 'income');
$expenseBreakdown = $transactionClass->getCategoryBreakdown($userId, 'expense');

// Get overall summary
$overallSummary = $transactionClass->getSummary($userId);

// Get current year summary
$yearStart = date('Y-01-01');
$yearEnd = date('Y-12-31');
$yearSummary = $transactionClass->getSummary($userId, $yearStart, $yearEnd);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div>
                    <h2 class="mb-1">
                        <i class="bi bi-bar-chart text-warning"></i> Financial Reports
                    </h2>
                    <p class="text-muted mb-0">Analysis of your farm finances</p>
                </div>
                <div>
                    <a href="<?php echo APP_URL; ?>/farm/transactions.php" class="btn btn-outline-primary me-2">
                        <i class="bi bi-list-ul"></i> Transactions
                    </a>
                    <button class="btn btn-outline-secondary" onclick="window.print()">
                        <i class="bi bi-printer"></i> Print
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Overall Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <h6 class="text-muted mb-1">All-Time Income</h6>
                            <h4 class="text-success mb-0"><?php echo formatCurrency($overallSummary['total_income'] ?? 0); ?></h4>
                        </div>
                        <div class="bg-success bg-opacity-10 p-2 rounded">
                            <i class="bi bi-arrow-up-circle text-success fs-4"></i>
                        </div>
                    </div>
                    <small class="text-muted"><?php echo $overallSummary['income_count'] ?? 0; ?> transactions</small>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <h6 class="text-muted mb-1">All-Time Expenses</h6>
                            <h4 class="text-danger mb-0"><?php echo formatCurrency($overallSummary['total_expenses'] ?? 0); ?></h4>
                        </div>
                        <div class="bg-danger bg-opacity-10 p-2 rounded">
                            <i class="bi bi-arrow-down-circle text-danger fs-4"></i>
                        </div>
                    </div>
                    <small class="text-muted"><?php echo $overallSummary['expense_count'] ?? 0; ?> transactions</small>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <h6 class="text-muted mb-1">All-Time Net</h6>
                            <h4 class="<?php echo ($overallSummary['net_profit'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?> mb-0">
                                <?php echo formatCurrency(abs($overallSummary['net_profit'] ?? 0)); ?>
                            </h4>
                        </div>
                        <div class="bg-primary bg-opacity-10 p-2 rounded">
                            <i class="bi bi-graph-up text-primary fs-4"></i>
                        </div>
                    </div>
                    <small class="<?php echo ($overallSummary['net_profit'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?>">
                        <?php echo ($overallSummary['net_profit'] ?? 0) >= 0 ? 'Profit' : 'Loss'; ?>
                    </small>
                </div>
            </div>
        </div>
        
        <div class="col-md-3 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <h6 class="text-muted mb-1"><?php echo date('Y'); ?> Net</h6>
                            <h4 class="<?php echo ($yearSummary['net_profit'] ?? 0) >= 0 ? 'text-success' : 'text-danger'; ?> mb-0">
                                <?php echo formatCurrency(abs($yearSummary['net_profit'] ?? 0)); ?>
                            </h4>
                        </div>
                        <div class="bg-info bg-opacity-10 p-2 rounded">
                            <i class="bi bi-calendar text-info fs-4"></i>
                        </div>
                    </div>
                    <small class="text-muted">Year to date</small>
                </div>
            </div>
        </div>
    </div>

    <!-- Monthly Trend Chart -->
    <?php if (!empty($monthlySummary)): ?>
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom">
                    <h5 class="mb-0">
                        <i class="bi bi-graph-up"></i> Monthly Trend (Last 6 Months)
                    </h5>
                </div>
                <div class="card-body">
                    <div style="position: relative; height: 300px;">
                        <canvas id="monthlyChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Category Breakdown -->
    <div class="row mb-4">
        <!-- Income Breakdown -->
        <div class="col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-arrow-up-circle"></i> Income by Category
                    </h5>
                    <small>Last 3 months</small>
                </div>
                <div class="card-body">
                    <?php if (!empty($incomeBreakdown)): ?>
                        <div style="position: relative; height: 250px;" class="mb-3">
                            <canvas id="incomeChart"></canvas>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-sm mb-0">
                                <tbody>
                                    <?php 
                                    $totalIncome = array_sum(array_column($incomeBreakdown, 'total'));
                                    foreach ($incomeBreakdown as $item): 
                                        $percentage = $totalIncome > 0 ? ($item['total'] / $totalIncome * 100) : 0;
                                    ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['category']); ?></td>
                                            <td class="text-end"><?php echo formatCurrency($item['total']); ?></td>
                                            <td class="text-end" style="width: 80px;">
                                                <small class="text-muted"><?php echo number_format($percentage, 1); ?>%</small>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot class="table-light">
                                    <tr>
                                        <th>Total</th>
                                        <th class="text-end"><?php echo formatCurrency($totalIncome); ?></th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="bi bi-inbox text-muted" style="font-size: 3rem;"></i>
                            <p class="text-muted mt-3">No income data available</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Expense Breakdown -->
        <div class="col-md-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0">
                        <i class="bi bi-arrow-down-circle"></i> Expenses by Category
                    </h5>
                    <small>Last 3 months</small>
                </div>
                <div class="card-body">
                    <?php if (!empty($expenseBreakdown)): ?>
                        <div style="position: relative; height: 250px;" class="mb-3">
                            <canvas id="expenseChart"></canvas>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-sm mb-0">
                                <tbody>
                                    <?php 
                                    $totalExpense = array_sum(array_column($expenseBreakdown, 'total'));
                                    foreach ($expenseBreakdown as $item): 
                                        $percentage = $totalExpense > 0 ? ($item['total'] / $totalExpense * 100) : 0;
                                    ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['category']); ?></td>
                                            <td class="text-end"><?php echo formatCurrency($item['total']); ?></td>
                                            <td class="text-end" style="width: 80px;">
                                                <small class="text-muted"><?php echo number_format($percentage, 1); ?>%</small>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot class="table-light">
                                    <tr>
                                        <th>Total</th>
                                        <th class="text-end"><?php echo formatCurrency($totalExpense); ?></th>
                                        <th></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="bi bi-inbox text-muted" style="font-size: 3rem;"></i>
                            <p class="text-muted mt-3">No expense data available</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="row">
        <div class="col-12">
            <div class="card border-0 shadow-sm">
                <div class="card-body text-center p-4">
                    <h5 class="mb-3">Need more detailed reports?</h5>
                    <div class="d-flex gap-2 justify-content-center flex-wrap">
                        <a href="<?php echo APP_URL; ?>/farm/transactions.php" class="btn btn-primary">
                            <i class="bi bi-list-ul"></i> View All Transactions
                        </a>
                        <a href="<?php echo APP_URL; ?>/farm/add-transaction.php" class="btn btn-success">
                            <i class="bi bi-plus-circle"></i> Add Transaction
                        </a>
                        <a href="<?php echo APP_URL; ?>/farm/" class="btn btn-outline-secondary">
                            <i class="bi bi-house"></i> Farm Dashboard
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Include Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

<script>
// Chart.js default configuration
Chart.defaults.font.family = '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
Chart.defaults.font.size = 12;
Chart.defaults.color = '#6c757d';

<?php if (!empty($monthlySummary)): ?>
// Monthly Trend Chart
const monthlyData = <?php echo json_encode(array_reverse($monthlySummary)); ?>;
const monthlyCtx = document.getElementById('monthlyChart');

if (monthlyCtx) {
    new Chart(monthlyCtx, {
        type: 'line',
        data: {
            labels: monthlyData.map(d => d.month),
            datasets: [
                {
                    label: 'Income',
                    data: monthlyData.map(d => parseFloat(d.income) || 0),
                    borderColor: '#10b981',
                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    pointRadius: 4,
                    pointHoverRadius: 6
                },
                {
                    label: 'Expenses',
                    data: monthlyData.map(d => parseFloat(d.expenses) || 0),
                    borderColor: '#ef4444',
                    backgroundColor: 'rgba(239, 68, 68, 0.1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    pointRadius: 4,
                    pointHoverRadius: 6
                },
                {
                    label: 'Net Profit',
                    data: monthlyData.map(d => parseFloat(d.profit) || 0),
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'top',
                    align: 'end',
                    labels: {
                        usePointStyle: true,
                        padding: 15,
                        font: {
                            size: 12
                        }
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    borderColor: '#fff',
                    borderWidth: 1,
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            label += 'UGX ' + context.parsed.y.toLocaleString();
                            return label;
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        callback: function(value) {
                            return 'UGX ' + value.toLocaleString();
                        }
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            },
            interaction: {
                intersect: false,
                mode: 'index'
            }
        }
    });
}
<?php endif; ?>

<?php if (!empty($incomeBreakdown)): ?>
// Income Pie Chart
const incomeCtx = document.getElementById('incomeChart');
if (incomeCtx) {
    new Chart(incomeCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode(array_column($incomeBreakdown, 'category')); ?>,
            datasets: [{
                data: <?php echo json_encode(array_column($incomeBreakdown, 'total')); ?>,
                backgroundColor: [
                    '#10b981', '#059669', '#047857', '#065f46', '#064e3b',
                    '#6ee7b7', '#34d399', '#10b981', '#059669', '#047857'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed || 0;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((value / total) * 100).toFixed(1);
                            return label + ': UGX ' + value.toLocaleString() + ' (' + percentage + '%)';
                        }
                    }
                }
            }
        }
    });
}
<?php endif; ?>

<?php if (!empty($expenseBreakdown)): ?>
// Expense Pie Chart
const expenseCtx = document.getElementById('expenseChart');
if (expenseCtx) {
    new Chart(expenseCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode(array_column($expenseBreakdown, 'category')); ?>,
            datasets: [{
                data: <?php echo json_encode(array_column($expenseBreakdown, 'total')); ?>,
                backgroundColor: [
                    '#ef4444', '#dc2626', '#b91c1c', '#991b1b', '#7f1d1d',
                    '#fca5a5', '#f87171', '#ef4444', '#dc2626', '#b91c1c'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed || 0;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((value / total) * 100).toFixed(1);
                            return label + ': UGX ' + value.toLocaleString() + ' (' + percentage + '%)';
                        }
                    }
                }
            }
        }
    });
}
<?php endif; ?>
</script>

<style>
@media print {
    .btn, nav, .card-header, footer { display: none !important; }
    .card { border: 1px solid #ddd !important; page-break-inside: avoid; }
    .row { page-break-inside: avoid; }
}
</style>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>