<?php
require_once __DIR__ . '/../config/config.php';
require_permission('accounting.reports_view');

$from = $_GET['from'] ?? date('Y-01-01');
$to = $_GET['to'] ?? date('Y-m-d');

$accounts = get_chart_of_accounts($pdo);
$byType = [];
foreach ($accounts as $a) {
    if ($a['statement'] !== 'income_statement') continue;
    // period activity: balance "as of $to" minus balance "as of the day before $from" = movement within period
    $asOfTo = get_account_balance($pdo, $a['id'], $a['normal_balance'], $to);
    $asOfBeforeFrom = get_account_balance($pdo, $a['id'], $a['normal_balance'], date('Y-m-d', strtotime($from . ' -1 day')));
    $movement = $asOfTo - $asOfBeforeFrom;
    if (abs($movement) < 0.005) continue;
    $byType[$a['type_name']]['accounts'][] = ['account' => $a, 'amount' => $movement];
    $byType[$a['type_name']]['total'] = ($byType[$a['type_name']]['total'] ?? 0) + $movement;
}

$revenue = $byType['Revenue']['total'] ?? 0;
$costOfSales = $byType['Cost of Sales']['total'] ?? 0;
$grossProfit = $revenue - $costOfSales;

$otherIncome = $byType['Other Income']['total'] ?? 0;
$adminExpense = $byType['Administrative Expense']['total'] ?? 0;
$otherExpense = $byType['Other Expense']['total'] ?? 0;
$gainLossOnSale = $byType['Profit/Loss on Sale of Non-Current Asset']['total'] ?? 0;

$netProfit = $grossProfit + $otherIncome + $gainLossOnSale - $adminExpense - $otherExpense;

function render_section($title, $data, $sign = 1) {
    if (empty($data['accounts'])) return;
    echo '<div class="mb-5"><p class="text-sm font-semibold text-slate-600 mb-2">' . e($title) . '</p><div class="space-y-1">';
    foreach ($data['accounts'] as $row) {
        echo '<div class="flex justify-between text-sm px-2"><span class="text-slate-500">' . e($row['account']['description']) . '</span><span>₦' . number_format($row['amount'],2) . '</span></div>';
    }
    echo '</div><div class="flex justify-between text-sm font-semibold border-t border-slate-100 mt-1 pt-1 px-2"><span>Total ' . e($title) . '</span><span>₦' . number_format($data['total'],2) . '</span></div></div>';
}

$pageTitle = 'Income Statement';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Income Statement (Profit &amp; Loss)</h1>

<form method="GET" class="flex flex-wrap items-end gap-3 mb-6 bg-white rounded-xl shadow-sm border border-slate-200 p-4">
  <div>
    <label class="text-xs text-slate-500 block mb-1">From</label>
    <input type="date" name="from" value="<?= e($from) ?>" class="border border-slate-300 rounded-lg px-3 py-2 text-sm">
  </div>
  <div>
    <label class="text-xs text-slate-500 block mb-1">To</label>
    <input type="date" name="to" value="<?= e($to) ?>" class="border border-slate-300 rounded-lg px-3 py-2 text-sm">
  </div>
  <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg">View</button>
</form>

<div class="bg-white rounded-xl shadow-sm border border-slate-200 p-6 max-w-2xl">
  <p class="text-xs text-slate-400 mb-4"><?= date('M j, Y', strtotime($from)) ?> to <?= date('M j, Y', strtotime($to)) ?></p>

  <?php render_section('Revenue', $byType['Revenue'] ?? ['accounts'=>[],'total'=>0]); ?>
  <?php render_section('Cost of Sales', $byType['Cost of Sales'] ?? ['accounts'=>[],'total'=>0]); ?>

  <div class="flex justify-between text-base font-bold border-t-2 border-slate-800 py-2 px-2 mb-5">
    <span>Gross Profit</span><span>₦<?= number_format($grossProfit,2) ?></span>
  </div>

  <?php render_section('Other Income', $byType['Other Income'] ?? ['accounts'=>[],'total'=>0]); ?>
  <?php render_section('Profit/Loss on Sale of Non-Current Asset', $byType['Profit/Loss on Sale of Non-Current Asset'] ?? ['accounts'=>[],'total'=>0]); ?>
  <?php render_section('Administrative Expense', $byType['Administrative Expense'] ?? ['accounts'=>[],'total'=>0]); ?>
  <?php render_section('Other Expense', $byType['Other Expense'] ?? ['accounts'=>[],'total'=>0]); ?>

  <div class="flex justify-between text-lg font-bold border-t-2 border-slate-800 py-2 px-2 <?= $netProfit < 0 ? 'text-red-600' : 'text-emerald-700' ?>">
    <span>Net Profit / (Loss)</span><span>₦<?= number_format($netProfit,2) ?></span>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
