<?php
// admin/accounts/reports.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

// Get date filters
$year = isset($_GET['year']) ? intval($_GET['year']) : date('Y');
$month = isset($_GET['month']) ? intval($_GET['month']) : date('m');

// Get financial data for selected month
$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM income WHERE YEAR(payment_date) = ? AND MONTH(payment_date) = ?");
$stmt->execute([$year, $month]);
$monthly_income = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM expenses WHERE YEAR(expense_date) = ? AND MONTH(expense_date) = ?");
$stmt->execute([$year, $month]);
$monthly_expenses = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM po_payments WHERE YEAR(payment_date) = ? AND MONTH(payment_date) = ?");
$stmt->execute([$year, $month]);
$monthly_po_payments = $stmt->fetch()['total'];

$profit = $monthly_income - ($monthly_expenses + $monthly_po_payments);

// Get monthly data for chart
$monthly_data = [];
$month_names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

for ($m = 1; $m <= 12; $m++) {
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM income WHERE YEAR(payment_date) = ? AND MONTH(payment_date) = ?");
    $stmt->execute([$year, $m]);
    $income = $stmt->fetch()['total'];
    
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM expenses WHERE YEAR(expense_date) = ? AND MONTH(expense_date) = ?");
    $stmt->execute([$year, $m]);
    $expenses = $stmt->fetch()['total'];
    
    $monthly_data[] = [
        'month' => $month_names[$m - 1],
        'income' => $income,
        'expenses' => $expenses,
        'profit' => $income - $expenses
    ];
}

// Get yearly summary
$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM income WHERE YEAR(payment_date) = ?");
$stmt->execute([$year]);
$yearly_income = $stmt->fetch()['total'];

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount), 0) as total FROM expenses WHERE YEAR(expense_date) = ?");
$stmt->execute([$year]);
$yearly_expenses = $stmt->fetch()['total'];

$yearly_profit = $yearly_income - $yearly_expenses;

include '../header.php';
?>

<style>
/* ===== Reports Page Styles ===== */
.account-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 20px;
    padding: 12px 15px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
}

.account-nav a {
    padding: 6px 14px;
    border-radius: 6px;
    color: #64748b;
    text-decoration: none;
    font-size: 13px;
    transition: all 0.3s ease;
    white-space: nowrap;
}

.account-nav a:hover,
.account-nav a.active {
    background: #047dc3;
    color: #fff;
}

.stat-card {
    background: #fff;
    border-radius: 12px;
    padding: 18px 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    text-align: center;
    height: 100%;
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.stat-card .stat-icon {
    font-size: 28px;
    margin-bottom: 8px;
}

.stat-card .stat-number {
    font-size: 22px;
    font-weight: 700;
}

.stat-card .stat-label {
    font-size: 13px;
    color: #64748b;
    margin-top: 2px;
}

.stat-card .stat-number.text-success { color: #22c55e; }
.stat-card .stat-number.text-danger { color: #ef4444; }
.stat-card .stat-number.text-warning { color: #f59e0b; }
.stat-card .stat-number.text-primary { color: #047dc3; }

.chart-container {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    margin-top: 20px;
}

.chart-container .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
    gap: 10px;
}

.chart-container .chart-header h5 {
    font-weight: 600;
    color: #1e293b;
    margin: 0;
}

.chart-container .chart-header .filter-group {
    display: flex;
    gap: 10px;
    align-items: center;
}

.chart-container .chart-header .filter-group select {
    padding: 6px 12px;
    border: 2px solid #e2e8f0;
    border-radius: 8px;
    font-size: 13px;
    background: #fff;
    cursor: pointer;
}

.chart-container .chart-header .filter-group select:focus {
    border-color: #047dc3;
    outline: none;
}

.chart-wrapper {
    position: relative;
    height: 350px;
}

/* Table Styles */
.table-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    margin-top: 20px;
}

.table-card .table-title {
    font-weight: 600;
    margin-bottom: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f1f5f9;
}

.table-responsive {
    overflow-x: auto;
}

.table {
    min-width: 600px;
    width: 100%;
}

.table th {
    background: #f8fafc;
    font-weight: 600;
    color: #475569;
    padding: 10px 12px;
    border-bottom: 2px solid #e2e8f0;
}

.table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f1f5f9;
}

.table tbody tr:hover {
    background: #f8fafc;
}

/* Responsive */
@media (max-width: 768px) {
    .chart-container .chart-header {
        flex-direction: column;
        align-items: stretch;
    }
    
    .chart-container .chart-header .filter-group {
        flex-wrap: wrap;
    }
    
    .chart-wrapper {
        height: 250px;
    }
    
    .stat-card .stat-number {
        font-size: 18px;
    }
}

@media (max-width: 480px) {
    .chart-wrapper {
        height: 200px;
    }
    
    .stat-card {
        padding: 14px;
    }
    
    .stat-card .stat-number {
        font-size: 16px;
    }
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4 flex-wrap gap-2">
        <h2><i class="fa-solid fa-chart-bar me-2"></i> Financial Reports</h2>
        <div class="d-flex gap-2">
            <button onclick="window.print()" class="btn btn-secondary">
                <i class="fa-solid fa-print"></i> Print
            </button>
            <button onclick="exportReport()" class="btn btn-success">
                <i class="fa-solid fa-file-export"></i> Export
            </button>
        </div>
    </div>
    
    <!-- Navigation -->
    <div class="account-nav">
        <a href="dashboard.php"><i class="fa-solid fa-chart-pie"></i> Dashboard</a>
        <a href="income.php"><i class="fa-solid fa-arrow-down"></i> Income</a>
        <a href="expenses.php"><i class="fa-solid fa-arrow-up"></i> Expenses</a>
        <a href="invoices.php"><i class="fa-solid fa-file-invoice"></i> Invoices</a>
        <a href="purchase-orders.php"><i class="fa-solid fa-file-purchase"></i> Purchase Orders</a>
        <a href="vendors.php"><i class="fa-solid fa-building"></i> Vendors</a>
        <a href="po-payments.php"><i class="fa-solid fa-hand-holding-dollar"></i> PO Payments</a>
        <a href="reports.php" class="active"><i class="fa-solid fa-chart-bar"></i> Reports</a>
    </div>
    
    <!-- Yearly Summary Stats -->
    <div class="row g-4 mb-4">
        <div class="col-lg-3 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-success"><i class="fa-solid fa-arrow-down"></i></div>
                <div class="stat-number text-success"><?php echo number_format($yearly_income); ?> TK</div>
                <div class="stat-label">Yearly Income (<?php echo $year; ?>)</div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-danger"><i class="fa-solid fa-arrow-up"></i></div>
                <div class="stat-number text-danger"><?php echo number_format($yearly_expenses); ?> TK</div>
                <div class="stat-label">Yearly Expenses (<?php echo $year; ?>)</div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-primary"><i class="fa-solid fa-coins"></i></div>
                <div class="stat-number text-<?php echo $yearly_profit >= 0 ? 'success' : 'danger'; ?>">
                    <?php echo number_format($yearly_profit); ?> TK
                </div>
                <div class="stat-label">Yearly Profit (<?php echo $year; ?>)</div>
            </div>
        </div>
        <div class="col-lg-3 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-warning"><i class="fa-solid fa-calendar"></i></div>
                <div class="stat-number text-warning"><?php echo date('F Y', mktime(0,0,0,$month,1,$year)); ?></div>
                <div class="stat-label">Current Month</div>
            </div>
        </div>
    </div>
    
    <!-- Monthly Stats -->
    <div class="row g-4 mb-4">
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-success"><i class="fa-solid fa-arrow-down"></i></div>
                <div class="stat-number text-success"><?php echo number_format($monthly_income); ?> TK</div>
                <div class="stat-label">Monthly Income</div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-danger"><i class="fa-solid fa-arrow-up"></i></div>
                <div class="stat-number text-danger"><?php echo number_format($monthly_expenses); ?> TK</div>
                <div class="stat-label">Monthly Expenses</div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-primary"><i class="fa-solid fa-coins"></i></div>
                <div class="stat-number text-<?php echo $profit >= 0 ? 'success' : 'danger'; ?>">
                    <?php echo number_format($profit); ?> TK
                </div>
                <div class="stat-label">Monthly Profit</div>
            </div>
        </div>
    </div>
    
    <!-- Chart -->
    <div class="chart-container">
        <div class="chart-header">
            <h5><i class="fa-solid fa-chart-line me-2"></i> Monthly Comparison - <?php echo $year; ?></h5>
            <div class="filter-group">
                <select id="yearSelect" onchange="updateYear()">
                    <?php for ($y = date('Y'); $y >= date('Y')-5; $y--): ?>
                    <option value="<?php echo $y; ?>" <?php echo $y == $year ? 'selected' : ''; ?>><?php echo $y; ?></option>
                    <?php endfor; ?>
                </select>
                <select id="monthSelect" onchange="updateMonth()">
                    <?php for ($m = 1; $m <= 12; $m++): ?>
                    <option value="<?php echo $m; ?>" <?php echo $m == $month ? 'selected' : ''; ?>><?php echo date('M', mktime(0,0,0,$m,1,2000)); ?></option>
                    <?php endfor; ?>
                </select>
                <button onclick="applyFilters()" class="btn btn-primary btn-sm">
                    <i class="fa-solid fa-filter"></i> Apply
                </button>
            </div>
        </div>
        <div class="chart-wrapper">
            <canvas id="monthlyChart"></canvas>
        </div>
    </div>
    
    <!-- Monthly Data Table -->
    <div class="table-card">
        <div class="table-title">
            <i class="fa-solid fa-table me-2"></i> Monthly Breakdown - <?php echo $year; ?>
        </div>
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Month</th>
                        <th class="text-end">Income</th>
                        <th class="text-end">Expenses</th>
                        <th class="text-end">Profit/Loss</th>
                        <th class="text-end">Margin %</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($monthly_data as $data): ?>
                    <tr>
                        <td><strong><?php echo $data['month']; ?></strong></td>
                        <td class="text-end text-success"><?php echo number_format($data['income']); ?> TK</td>
                        <td class="text-end text-danger"><?php echo number_format($data['expenses']); ?> TK</td>
                        <td class="text-end <?php echo $data['profit'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                            <?php echo number_format($data['profit']); ?> TK
                        </td>
                        <td class="text-end">
                            <?php 
                            if ($data['income'] > 0) {
                                $margin = ($data['profit'] / $data['income']) * 100;
                                echo number_format($margin, 1) . '%';
                            } else {
                                echo '0%';
                            }
                            ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="fw-bold">
                        <td>TOTAL</td>
                        <td class="text-end text-success"><?php echo number_format($yearly_income); ?> TK</td>
                        <td class="text-end text-danger"><?php echo number_format($yearly_expenses); ?> TK</td>
                        <td class="text-end <?php echo $yearly_profit >= 0 ? 'text-success' : 'text-danger'; ?>">
                            <?php echo number_format($yearly_profit); ?> TK
                        </td>
                        <td class="text-end">
                            <?php 
                            if ($yearly_income > 0) {
                                $yearly_margin = ($yearly_profit / $yearly_income) * 100;
                                echo number_format($yearly_margin, 1) . '%';
                            } else {
                                echo '0%';
                            }
                            ?>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// ========================================
// CHART DATA
// ========================================
var monthlyData = <?php echo json_encode($monthly_data); ?>;
var chartInstance = null;

// ========================================
// INITIALIZE CHART
// ========================================
function initChart() {
    var ctx = document.getElementById('monthlyChart').getContext('2d');
    
    if (chartInstance) {
        chartInstance.destroy();
    }
    
    chartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: monthlyData.map(function(d) { return d.month; }),
            datasets: [
                {
                    label: 'Income',
                    data: monthlyData.map(function(d) { return d.income; }),
                    backgroundColor: 'rgba(34, 197, 94, 0.7)',
                    borderColor: '#22c55e',
                    borderWidth: 2,
                    borderRadius: 4
                },
                {
                    label: 'Expenses',
                    data: monthlyData.map(function(d) { return d.expenses; }),
                    backgroundColor: 'rgba(239, 68, 68, 0.7)',
                    borderColor: '#ef4444',
                    borderWidth: 2,
                    borderRadius: 4
                },
                {
                    label: 'Profit',
                    data: monthlyData.map(function(d) { return d.profit; }),
                    backgroundColor: 'rgba(4, 125, 195, 0.7)',
                    borderColor: '#047dc3',
                    borderWidth: 2,
                    borderRadius: 4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        padding: 20,
                        font: {
                            size: 12,
                            weight: '500'
                        }
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            var label = context.dataset.label || '';
                            var value = context.raw || 0;
                            return label + ': ' + value.toLocaleString() + ' TK';
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return value.toLocaleString() + ' TK';
                        },
                        font: {
                            size: 11
                        }
                    },
                    grid: {
                        color: 'rgba(0,0,0,0.05)'
                    }
                },
                x: {
                    grid: {
                        display: false
                    }
                }
            },
            animation: {
                duration: 1000,
                easing: 'easeInOutQuart'
            }
        }
    });
}

// ========================================
// UPDATE YEAR
// ========================================
function updateYear() {
    var year = document.getElementById('yearSelect').value;
    window.location.href = 'reports.php?year=' + year + '&month=' + document.getElementById('monthSelect').value;
}

// ========================================
// UPDATE MONTH
// ========================================
function updateMonth() {
    var month = document.getElementById('monthSelect').value;
    window.location.href = 'reports.php?year=' + document.getElementById('yearSelect').value + '&month=' + month;
}

// ========================================
// APPLY FILTERS
// ========================================
function applyFilters() {
    var year = document.getElementById('yearSelect').value;
    var month = document.getElementById('monthSelect').value;
    window.location.href = 'reports.php?year=' + year + '&month=' + month;
}

// ========================================
// EXPORT REPORT
// ========================================
function exportReport() {
    var year = document.getElementById('yearSelect').value;
    var month = document.getElementById('monthSelect').value;
    window.open('export-report.php?year=' + year + '&month=' + month, '_blank');
}

// ========================================
// INIT ON PAGE LOAD
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    initChart();
    
    // Update chart on window resize
    var resizeTimer;
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function() {
            if (chartInstance) {
                chartInstance.resize();
            }
        }, 250);
    });
});
</script>

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