<?php $this->start('body');
    $p          = $this->data['p'];
    $totals     = $this->data['totals']     ?? [];
    $planned    = $this->data['planned']    ?? [];
    $byAccount  = $this->data['by_account'] ?? [];
    $lines      = $this->data['lines']      ?? [];
    $from       = $this->v('from');
    $to         = $this->v('to');

    $rev  = (float)$totals['revenue'];
    $cog  = (float)$totals['cogs'];
    $opx  = (float)$totals['opex'];
    $gm   = (float)$totals['gross_margin'];
    $nm   = (float)$totals['net_margin'];
    $mgnPct = $rev > 0 ? ($gm / $rev) * 100 : 0;
    $netPct = $rev > 0 ? ($nm / $rev) * 100 : 0;

    $planRev  = (float)$planned['revenue'];
    $planCog  = (float)$planned['cog'];
    $planGm   = (float)$planned['gross_margin'];
    $planMgn  = $planRev > 0 ? ($planGm / $planRev) * 100 : 0;
    $revVar   = $rev - $planRev;      // actual − planned
    $cogVar   = $cog - $planCog;
    $gmVar    = $gm  - $planGm;
    $mgnVar   = $mgnPct - $planMgn;

    $marginColor = function (float $pct): string {
        if ($pct < 0)  return '#ef4444';
        if ($pct < 20) return '#f59e0b';
        if ($pct < 30) return '#3b82f6';
        return '#22c55e';
    };
?>

<div class="d-flex align-items-center justify-content-between mb-3">
    <div>
        <h5 class="mb-0" style="font-weight:600;"><i class="fas fa-chart-pie me-2 text-muted"></i><?= htmlspecialchars($p['project_no']); ?> · P&amp;L</h5>
        <div class="text-muted" style="font-size:.72rem;">
            <?= htmlspecialchars($p['project_name']); ?> · <?= htmlspecialchars($p['project_customer']); ?>
            · <span style="text-transform:capitalize;"><?= htmlspecialchars($p['project_type']); ?></span>
        </div>
    </div>
    <div>
        <a href="<?= PROOT; ?>ProjectPnl" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left me-1"></i> All projects</a>
        <a href="<?= PROOT; ?>Projects/view/<?= (int)$p['c0d']; ?>" class="btn btn-sm btn-outline-secondary"><i class="fas fa-project-diagram me-1"></i> Open project</a>
    </div>
</div>

<form method="get" action="<?= PROOT; ?>ProjectPnl/view/<?= (int)$p['c0d']; ?>" class="card border-0 shadow-sm mb-3">
    <div class="card-body p-2">
        <div class="row g-2 align-items-end">
            <div class="col-md-4"><label class="form-label">From</label><input type="date" name="from" value="<?= htmlspecialchars($from); ?>" class="form-control form-control-sm"></div>
            <div class="col-md-4"><label class="form-label">To</label>  <input type="date" name="to"   value="<?= htmlspecialchars($to); ?>"   class="form-control form-control-sm"></div>
            <div class="col-md-4 text-end"><button type="submit" class="btn btn-sm btn-outline-secondary"><i class="fas fa-filter me-1"></i>Apply</button></div>
        </div>
    </div>
</form>

<div class="row g-3 mb-3">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm h-100"><div class="card-body p-3">
            <div class="text-muted small">Revenue</div>
            <div style="font-weight:700;font-size:1.4rem;color:#3b82f6;"><?= htmlspecialchars($p['currency']); ?> <?= number_format($rev); ?></div>
            <div class="text-muted small mt-1">Planned <?= number_format($planRev); ?><?php if ($planRev > 0): ?> · Variance <span style="color:<?= $revVar>=0?'#22c55e':'#ef4444'; ?>;"><?= $revVar>=0?'+':''; ?><?= number_format($revVar); ?></span><?php endif; ?></div>
        </div></div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm h-100"><div class="card-body p-3">
            <div class="text-muted small">CoGS (direct costs)</div>
            <div style="font-weight:700;font-size:1.4rem;color:#ef4444;"><?= htmlspecialchars($p['currency']); ?> <?= number_format($cog); ?></div>
            <div class="text-muted small mt-1">Planned <?= number_format($planCog); ?><?php if ($planCog > 0): ?> · Variance <span style="color:<?= $cogVar<=0?'#22c55e':'#ef4444'; ?>;"><?= $cogVar>=0?'+':''; ?><?= number_format($cogVar); ?></span><?php endif; ?></div>
        </div></div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm h-100"><div class="card-body p-3">
            <div class="text-muted small">OpEx (indirect)</div>
            <div style="font-weight:700;font-size:1.4rem;color:#f59e0b;"><?= htmlspecialchars($p['currency']); ?> <?= number_format($opx); ?></div>
            <div class="text-muted small mt-1">non-COGS expenses</div>
        </div></div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm h-100" style="border-left:4px solid <?= $marginColor($mgnPct); ?> !important;"><div class="card-body p-3">
            <div class="text-muted small">Gross margin</div>
            <div style="font-weight:700;font-size:1.6rem;color:<?= $marginColor($mgnPct); ?>;"><?= number_format($mgnPct, 1); ?>%</div>
            <div class="text-muted small mt-1"><?= htmlspecialchars($p['currency']); ?> <?= number_format($gm); ?> · Planned <?= number_format($planMgn, 1); ?>%<?php if ($planRev > 0 && $rev > 0): ?> · <span style="color:<?= $mgnVar>=0?'#22c55e':'#ef4444'; ?>;"><?= $mgnVar>=0?'+':''; ?><?= number_format($mgnVar, 1); ?>pp</span><?php endif; ?></div>
        </div></div>
    </div>
</div>

<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white d-flex align-items-center justify-content-between">
        <strong>Net margin (after OpEx)</strong>
        <div>
            <span style="font-weight:700;font-size:1.15rem;color:<?= $marginColor($netPct); ?>;"><?= number_format($netPct, 1); ?>%</span>
            <span class="text-muted ms-2"><?= htmlspecialchars($p['currency']); ?> <?= number_format($nm); ?></span>
        </div>
    </div>
    <div class="card-body p-3">
        <?php $gmBar = $rev > 0 ? min(100, max(0, $mgnPct)) : 0; ?>
        <div class="d-flex align-items-center gap-2">
            <div class="progress flex-grow-1" style="height:10px;">
                <div class="progress-bar" role="progressbar" style="width:<?= $gmBar; ?>%;background:<?= $marginColor($mgnPct); ?>;"></div>
            </div>
            <div class="text-muted small" style="width:120px;">Gross <?= number_format($mgnPct, 1); ?>%</div>
        </div>
    </div>
</div>

<?php if (!empty($byAccount)): ?>
<div class="card border-0 shadow-sm mb-3">
    <div class="card-header bg-white"><strong>Per account breakdown</strong></div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>Account</th><th>Type</th><th class="text-end">Debits</th><th class="text-end">Credits</th><th class="text-end">Amount to P&amp;L</th></tr>
            </thead>
            <tbody>
                <?php foreach ($byAccount as $a):
                    $isRev = ($a['account_type'] === 'REVENUE');
                    $pnlAmt = $isRev ? (float)$a['credits'] : (float)$a['debits'];
                    $badge = $isRev ? 'bg-info text-white' : ($a['account_code'][0] === '5' ? 'bg-danger' : 'bg-warning text-dark');
                    $label = $isRev ? 'Revenue' : ($a['account_code'][0] === '5' ? 'CoGS' : 'OpEx');
                ?>
                    <tr>
                        <td><code class="text-body"><?= htmlspecialchars($a['account_code']); ?></code> · <?= htmlspecialchars($a['account_name']); ?></td>
                        <td><span class="badge <?= $badge; ?>"><?= htmlspecialchars($label); ?></span></td>
                        <td class="text-end text-muted"><?= (float)$a['debits']  > 0 ? number_format((float)$a['debits'])  : '—'; ?></td>
                        <td class="text-end text-muted"><?= (float)$a['credits'] > 0 ? number_format((float)$a['credits']) : '—'; ?></td>
                        <td class="text-end" style="font-weight:600;color:<?= $isRev?'#3b82f6':'#ef4444'; ?>;"><?= number_format($pnlAmt); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-header bg-white"><strong>P&amp;L journal lines · <?= count($lines); ?></strong></div>
    <div class="table-responsive">
        <table class="table table-sm mb-0 align-middle">
            <thead class="table-light">
                <tr><th>Date</th><th>JE #</th><th>Source</th><th>Ref</th><th>Account</th><th>Narrative</th><th class="text-end">Debit</th><th class="text-end">Credit</th></tr>
            </thead>
            <tbody>
                <?php foreach ($lines as $ln): ?>
                    <tr>
                        <td class="text-muted small"><?= htmlspecialchars($ln['entry_date']); ?></td>
                        <td><a href="<?= PROOT; ?>Journals/view/1" class="text-decoration-none"><strong><?= htmlspecialchars($ln['je_no']); ?></strong></a></td>
                        <td><span class="badge bg-light text-muted" style="text-transform:capitalize;"><?= htmlspecialchars(strtolower($ln['source_type'])); ?></span></td>
                        <td class="text-muted small"><?= htmlspecialchars($ln['source_ref']); ?></td>
                        <td><code class="text-body"><?= htmlspecialchars($ln['account_code']); ?></code> · <?= htmlspecialchars($ln['account_name']); ?></td>
                        <td class="text-muted small"><?= htmlspecialchars($ln['line_narr'] ?: $ln['je_narr']); ?></td>
                        <td class="text-end"><?= (float)$ln['debit']  > 0 ? number_format((float)$ln['debit'])  : '—'; ?></td>
                        <td class="text-end"><?= (float)$ln['credit'] > 0 ? number_format((float)$ln['credit']) : '—'; ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($lines)): ?><tr><td colspan="8" class="text-center text-muted py-3">No P&L activity in this period.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php $this->end(); ?>
