<?php ob_start(); ?>
<div class="container-fluid py-4">
    <!-- Profitability Summary -->
    <div class="row mb-4">
        <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
            <div class="card">
                <div class="card-body p-3">
                    <div class="row">
                        <div class="col-8">
                            <div class="numbers">
                                <p class="text-sm mb-0 text-capitalize font-weight-bold">Revenue</p>
                                <h5 class="font-weight-bolder mb-0"><?= formatCurrency((float)($summary['revenue'] ?? 0), $project['currency'] ?? DEFAULT_CURRENCY) ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
            <div class="card">
                <div class="card-body p-3">
                    <div class="row">
                        <div class="col-8">
                            <div class="numbers">
                                <p class="text-sm mb-0 text-capitalize font-weight-bold">Total Budget</p>
                                <h5 class="font-weight-bolder mb-0"><?= formatCurrency((float)($summary['total_budget'] ?? 0), $project['currency'] ?? DEFAULT_CURRENCY) ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-sm-6 mb-xl-0 mb-4">
            <div class="card">
                <div class="card-body p-3">
                    <div class="row">
                        <div class="col-8">
                            <div class="numbers">
                                <p class="text-sm mb-0 text-capitalize font-weight-bold">Total Actual</p>
                                <h5 class="font-weight-bolder mb-0 text-<?= ($summary['total_actual'] > $summary['total_budget']) ? 'danger' : 'success' ?>">
                                    <?= formatCurrency((float)($summary['total_actual'] ?? 0), $project['currency'] ?? DEFAULT_CURRENCY) ?>
                                </h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-xl-3 col-sm-6">
            <div class="card">
                <div class="card-body p-3">
                    <div class="row">
                        <div class="col-8">
                            <div class="numbers">
                                <p class="text-sm mb-0 text-capitalize font-weight-bold">Margin</p>
                                <h5 class="font-weight-bolder mb-0">
                                    <?= number_format($summary['margin_percent'] ?? 0, 2) ?>%
                                </h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Chart & Actions -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <div class="card h-100">
                <div class="card-header pb-0">
                    <h6>Budget vs Actual</h6>
                </div>
                <div class="card-body p-3">
                    <div class="chart">
                        <canvas id="budgetChart" class="chart-canvas" height="300"></canvas>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header pb-0">
                    <h6>Actions</h6>
                </div>
                <div class="card-body p-3 d-flex flex-column gap-3">
                    <button class="btn btn-primary w-100" data-bs-toggle="modal" data-bs-target="#addBudgetItemModal">Add Budget Item</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Budget Table -->
    <div class="card">
        <div class="card-header pb-0">
            <h6>Budget Line Items</h6>
        </div>
        <div class="card-body px-0 pt-0 pb-2">
            <div class="table-responsive p-0">
                <table class="table align-items-center mb-0">
                    <thead>
                        <tr>
                            <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Category</th>
                            <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">Item</th>
                            <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Qty / Unit / Rate</th>
                            <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Budget</th>
                            <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Actual</th>
                            <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Variance</th>
                            <th class="text-secondary opacity-7"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(!empty($budgetItems)): ?>
                            <?php foreach($budgetItems as $item):
                                $budget = (float)$item['total_budget'];
                                $actual = (float)$item['total_actual'];
                                $variance = $budget - $actual;
                                $variancePercent = $budget > 0 ? ($actual / $budget) * 100 : 0;
                            ?>
                            <tr>
                                <td>
                                    <div class="d-flex px-3 py-1">
                                        <h6 class="mb-0 text-sm"><?= htmlspecialchars($item['category']) ?></h6>
                                    </div>
                                </td>
                                <td>
                                    <p class="text-xs font-weight-bold mb-0"><?= htmlspecialchars($item['item_name']) ?></p>
                                </td>
                                <td class="align-middle text-center text-sm">
                                    <span class="text-xs font-weight-bold"><?= htmlspecialchars($item['quantity']) ?> <?= htmlspecialchars($item['unit']) ?> @ <?= formatCurrency((float)$item['unit_rate'], $project['currency'] ?? DEFAULT_CURRENCY) ?></span>
                                </td>
                                <td class="align-middle text-center text-sm">
                                    <span class="text-xs font-weight-bold"><?= formatCurrency($budget, $project['currency'] ?? DEFAULT_CURRENCY) ?></span>
                                </td>
                                <td class="align-middle text-center text-sm">
                                    <span class="text-xs font-weight-bold"><?= formatCurrency($actual, $project['currency'] ?? DEFAULT_CURRENCY) ?></span>
                                </td>
                                <td class="align-middle text-center">
                                    <div class="d-flex align-items-center justify-content-center">
                                        <span class="me-2 text-xs font-weight-bold <?= $variance < 0 ? 'text-danger' : 'text-success' ?>">
                                            <?= formatCurrency(abs($variance), $project['currency'] ?? DEFAULT_CURRENCY) ?>
                                        </span>
                                        <div>
                                            <div class="progress">
                                                <div class="progress-bar bg-<?= $variancePercent > 100 ? 'danger' : 'info' ?>" role="progressbar" aria-valuenow="<?= $variancePercent ?>" aria-valuemin="0" aria-valuemax="100" style="width: <?= min($variancePercent, 100) ?>%;"></div>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                                <td class="align-middle">
                                    <form action="<?= APP_URL ?>/finance/budgets/item/<?= $item['id'] ?>/delete" method="POST" onsubmit="return confirm('Remove this budget item?');" class="d-inline">
                                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">
                                        <button type="submit" class="btn btn-link text-danger mb-0 p-0">Delete</button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center py-4">No budget items added yet.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Item Modal -->
<div class="modal fade" id="addBudgetItemModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="<?= APP_URL ?>/finance/budgets/<?= $project_id ?>/item" method="POST">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?? '' ?>">
                <div class="modal-header">
                    <h5 class="modal-title">Add Budget Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label>Category</label>
                        <select name="category" class="form-control" required>
                            <option value="Labor">Labor</option>
                            <option value="Materials">Materials</option>
                            <option value="Equipment">Equipment</option>
                            <option value="Subcontractor">Subcontractor</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label>Item Name</label>
                        <input type="text" name="item_name" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-4 mb-3">
                            <label>Unit</label>
                            <input type="text" name="unit" class="form-control" placeholder="e.g. hrs, pcs" required>
                        </div>
                        <div class="col-4 mb-3">
                            <label>Qty</label>
                            <input type="number" name="quantity" id="qtyInput" class="form-control" step="0.01" required>
                        </div>
                        <div class="col-4 mb-3">
                            <label>Rate (<?= htmlspecialchars(CURRENCIES[$project['currency'] ?? DEFAULT_CURRENCY] ?? DEFAULT_CURRENCY) ?>)</label>
                            <input type="number" name="unit_rate" id="rateInput" class="form-control" step="0.01" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label>Total Budget (<?= htmlspecialchars(CURRENCIES[$project['currency'] ?? DEFAULT_CURRENCY] ?? DEFAULT_CURRENCY) ?>)</label>
                        <input type="number" id="budgetTotal" class="form-control" readonly>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" class="btn btn-primary">Add Item</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Auto calculate total budget in modal
    const qtyInput = document.getElementById('qtyInput');
    const rateInput = document.getElementById('rateInput');
    const budgetTotal = document.getElementById('budgetTotal');

    function calcTotal() {
        const qty = parseFloat(qtyInput.value) || 0;
        const rate = parseFloat(rateInput.value) || 0;
        budgetTotal.value = (qty * rate).toFixed(2);
    }

    qtyInput.addEventListener('input', calcTotal);
    rateInput.addEventListener('input', calcTotal);

    // Render Chart
    const ctx = document.getElementById('budgetChart').getContext('2d');
    
    const labels = <?= json_encode(array_keys($categoryBreakdown ?? [])) ?>;
    const dataBudget = <?= json_encode(array_values($categoryBreakdown ?? [])) ?>;
    const dataActual = <?= json_encode(array_values($categoryActuals ?? [])) ?>;

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: 'Budget',
                    data: dataBudget,
                    backgroundColor: 'rgba(54, 162, 235, 0.5)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 1
                },
                {
                    label: 'Actual',
                    data: dataActual,
                    backgroundColor: 'rgba(255, 99, 132, 0.5)',
                    borderColor: 'rgba(255, 99, 132, 1)',
                    borderWidth: 1
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: { beginAtZero: true }
            }
        }
    });
});
</script>
<?php
$content = ob_get_clean();
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>

