<?php
require_once __DIR__ . '/_report_common.php';
[$from,$to] = get_range();

$stmt = $pdo->prepare("
  SELECT
    a.code, a.name, a.type,
    SUM(jl.debit) AS debits,
    SUM(jl.credit) AS credits,
    CASE
      WHEN a.type='REVENUE' THEN SUM(jl.credit - jl.debit)
      ELSE SUM(jl.debit - jl.credit)
    END AS net_amount
  FROM journal_lines jl
  JOIN journal_entries je ON je.id=jl.entry_id
  JOIN accounts a ON a.id=jl.account_id
  WHERE jl.company_id=? AND je.status='POSTED' AND je.entry_date BETWEEN ? AND ?
    AND a.type IN ('REVENUE','EXPENSE')
  GROUP BY a.id
  ORDER BY a.type, a.code
");
$stmt->execute([$cid,$from,$to]);
$rows = $stmt->fetchAll();

$rev=0; $exp=0;
foreach($rows as $r){
  if($r['type']==='REVENUE') $rev += (float)$r['net_amount'];
  else $exp += (float)$r['net_amount'];
}
$profit = $rev - $exp;

render_layout("الأرباح والخسائر", "الرئيسية <span class='mx-1'>/</span> التقارير <span class='mx-1'>/</span> الأرباح والخسائر", function() use ($rows,$from,$to,$rev,$exp,$profit) {
?>
<div class="row g-3 mt-3">
  <div class="col-12 col-xl-4">
    <div class="card cardx p-3">
      <div class="fw-bold">ملخص</div>
      <div class="text-secondary small">للفترة المختارة</div>
      <div class="mt-3">
        <div class="d-flex justify-content-between"><span class="text-secondary">إجمالي الإيرادات</span><span class="fw-semibold"><?= number_format($rev,2) ?></span></div>
        <div class="d-flex justify-content-between mt-2"><span class="text-secondary">إجمالي المصروفات</span><span class="fw-semibold"><?= number_format($exp,2) ?></span></div>
        <hr>
        <div class="d-flex justify-content-between"><span class="fw-bold">صافي الربح</span><span class="fw-bold"><?= number_format($profit,2) ?></span></div>
      </div>
      <form class="row g-2 align-items-end mt-3" method="get">
        <div class="col-6">
          <label class="form-label small text-secondary">من</label>
          <?= render_date_input('from', $from) ?>
        </div>
        <div class="col-6">
          <label class="form-label small text-secondary">إلى</label>
          <?= render_date_input('to', $to) ?>
        </div>
        <div class="col-12">
          <button class="btn btn-dark w-100"><i class="bi bi-funnel"></i> تطبيق</button>
        </div>
      </form>
    </div>
  </div>

  <div class="col-12 col-xl-8">
    <div class="card cardx">
      <div class="p-3 d-flex align-items-center justify-content-between">
        <div>
          <div class="fw-bold">تفاصيل الإيرادات والمصروفات</div>
          <div class="text-secondary small">حسب الحسابات</div>
        </div>
      </div>
      <div class="table-responsive px-3 pb-3">
        <table class="table align-middle mb-0">
          <thead>
            <tr class="text-secondary small">
              <th>النوع</th>
              <th>الكود</th>
              <th>الحساب</th>
              <th class="text-end">الصافي</th>
            </tr>
          </thead>
          <tbody>
            <?php if(!$rows): ?>
              <tr><td colspan="4" class="text-center text-secondary py-4">لا توجد بيانات</td></tr>
            <?php else: foreach($rows as $r): ?>
              <tr>
                <td>
                  <?php if($r['type']==='REVENUE'): ?>
                    <span class="badge bg-success-subtle text-success border border-success-subtle">إيراد</span>
                  <?php else: ?>
                    <span class="badge bg-danger-subtle text-danger border border-danger-subtle">مصروف</span>
                  <?php endif; ?>
                </td>
                <td class="text-secondary"><?= h($r['code']) ?></td>
                <td class="fw-semibold"><?= h($r['name']) ?></td>
                <td class="text-end fw-semibold"><?= number_format((float)$r['net_amount'],2) ?></td>
              </tr>
            <?php endforeach; endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php }); ?>
