<?php
require_once __DIR__ . '/app/helpers.php';
require_once __DIR__ . '/app/db.php';
require_once __DIR__ . '/app/layout.php';
require_login();

$pdo = db();
$cid = (int)$_SESSION['company_id'];

// KPI: revenue and expense this month, cash balance, tx count
$firstDay = date('Y-m-01');
$lastDay  = date('Y-m-t');

$stmt = $pdo->prepare("
  SELECT
    SUM(CASE WHEN a.type='REVENUE' THEN (jl.credit - jl.debit) ELSE 0 END) AS rev,
    SUM(CASE WHEN a.type='EXPENSE' THEN (jl.debit - jl.credit) ELSE 0 END) AS exp
  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 ?
");
$stmt->execute([$cid,$firstDay,$lastDay]);
$k = $stmt->fetch() ?: ['rev'=>0,'exp'=>0];

$stmt = $pdo->prepare("
  SELECT SUM(jl.debit - jl.credit) AS bal
  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 a.is_cash=1
");
$stmt->execute([$cid]);
$cashBal = (float)($stmt->fetch()['bal'] ?? 0);

$stmt = $pdo->prepare("SELECT COUNT(*) AS c FROM cash_transactions WHERE company_id=? AND tx_date BETWEEN ? AND ?");
$stmt->execute([$cid,$firstDay,$lastDay]);
$txCount = (int)($stmt->fetch()['c'] ?? 0);

// last 6 months chart
$labels = [];
$revSeries = [];
$expSeries = [];
for ($i=5; $i>=0; $i--) {
  $d = new DateTime("first day of -$i month");
  $from = $d->format('Y-m-01');
  $to = $d->format('Y-m-t');
  $labels[] = $d->format('m/Y');
  $stmt->execute([$cid,$from,$to]); # reuse revenue/expense stmt? we can't; create new stmt quickly
}
$stmt2 = $pdo->prepare("
  SELECT
    SUM(CASE WHEN a.type='REVENUE' THEN (jl.credit - jl.debit) ELSE 0 END) AS rev,
    SUM(CASE WHEN a.type='EXPENSE' THEN (jl.debit - jl.credit) ELSE 0 END) AS exp
  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 ?
");
for ($i=5; $i>=0; $i--) {
  $d = new DateTime("first day of -$i month");
  $from = $d->format('Y-m-01');
  $to = $d->format('Y-m-t');
  $stmt2->execute([$cid,$from,$to]);
  $row = $stmt2->fetch() ?: ['rev'=>0,'exp'=>0];
  $revSeries[] = (float)$row['rev'];
  $expSeries[] = (float)$row['exp'];
}

// last cash tx
$stmt = $pdo->prepare("
  SELECT ct.*, a1.code AS cash_code, a1.name AS cash_name, a2.code AS cnt_code, a2.name AS cnt_name
  FROM cash_transactions ct
  JOIN accounts a1 ON a1.id=ct.cash_account_id
  JOIN accounts a2 ON a2.id=ct.counter_account_id
  WHERE ct.company_id=?
  ORDER BY ct.id DESC
  LIMIT 10
");
$stmt->execute([$cid]);
$lastTx = $stmt->fetchAll();

render_layout("لوحة التحكم", "الرئيسية <span class='mx-1'>/</span> لوحة التحكم", function() use ($k,$cashBal,$txCount,$labels,$revSeries,$expSeries,$lastTx) {
?>
<div class="row g-3 mt-2">
  <div class="col-12 col-md-6 col-xl-3">
    <div class="card cardx p-3 h-100">
      <div class="d-flex align-items-center justify-content-between">
        <div>
          <div class="text-secondary small">إيرادات الشهر</div>
          <div class="fs-3 fw-bold mt-1"><?= number_format((float)$k['rev'], 2) ?></div>
          <div class="small text-secondary mt-1">حسب القيود اليومية</div>
        </div>
        <div class="rounded-4 p-3" style="background: rgba(15,23,42,.08);">
          <i class="bi bi-cash-stack fs-3"></i>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="card cardx p-3 h-100">
      <div class="d-flex align-items-center justify-content-between">
        <div>
          <div class="text-secondary small">مصروفات الشهر</div>
          <div class="fs-3 fw-bold mt-1"><?= number_format((float)$k['exp'], 2) ?></div>
          <div class="small text-secondary mt-1">حسب القيود اليومية</div>
        </div>
        <div class="rounded-4 p-3" style="background: rgba(15,23,42,.08);">
          <i class="bi bi-receipt fs-3"></i>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="card cardx p-3 h-100">
      <div class="d-flex align-items-center justify-content-between">
        <div>
          <div class="text-secondary small">رصيد النقدية</div>
          <div class="fs-3 fw-bold mt-1"><?= number_format((float)$cashBal, 2) ?></div>
          <div class="small text-secondary mt-1">صندوق + بنوك</div>
        </div>
        <div class="rounded-4 p-3" style="background: rgba(15,23,42,.08);">
          <i class="bi bi-wallet2 fs-3"></i>
        </div>
      </div>
    </div>
  </div>

  <div class="col-12 col-md-6 col-xl-3">
    <div class="card cardx p-3 h-100">
      <div class="d-flex align-items-center justify-content-between">
        <div>
          <div class="text-secondary small">حركات الشهر</div>
          <div class="fs-3 fw-bold mt-1"><?= (int)$txCount ?></div>
          <div class="small text-secondary mt-1">وارد/منصرف</div>
        </div>
        <div class="rounded-4 p-3" style="background: rgba(15,23,42,.08);">
          <i class="bi bi-arrow-left-right fs-3"></i>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row g-3 mt-1">
  <div class="col-12 col-xl-8">
    <div class="card cardx p-3 h-100">
      <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
        <div>
          <div class="fw-bold">الإيرادات والمصروفات</div>
          <div class="text-secondary small">آخر 6 شهور</div>
        </div>
      </div>
      <div class="mt-3" style="height: 300px;">
        <canvas id="revExpChart"></canvas>
      </div>
    </div>
  </div>

  <div class="col-12 col-xl-4">
    <div class="card cardx p-3 h-100">
      <div class="d-flex align-items-center justify-content-between">
        <div>
          <div class="fw-bold">اختصارات</div>
          <div class="text-secondary small">إجراءات سريعة</div>
        </div>
        <i class="bi bi-lightning-charge fs-4"></i>
      </div>

      <div class="mt-3 d-grid gap-2">
        <a class="btn btn-dark w-100" href="<?= url('/cash/create.php') ?>"><i class="bi bi-plus-lg"></i> إضافة وارد/منصرف</a>
        <a class="btn btn-outline-secondary w-100" href="<?= url('/reports/trial_balance.php') ?>"><i class="bi bi-clipboard-data"></i> ميزان مراجعة</a>
        <a class="btn btn-outline-secondary w-100" href="<?= url('/reports/pl.php') ?>"><i class="bi bi-graph-up"></i> أرباح وخسائر</a>
      </div>
    </div>
  </div>
</div>

<div class="card cardx mt-3">
  <div class="p-3 d-flex align-items-center justify-content-between flex-wrap gap-2">
    <div>
      <div class="fw-bold">آخر الحركات</div>
      <div class="text-secondary small">آخر 10 وارد/منصرف</div>
    </div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary btn-sm" href="<?= url('/cash/index.php') ?>"><i class="bi bi-list"></i> عرض الكل</a>
    </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>الحساب النقدي</th>
          <th>الحساب المقابل</th>
          <th class="text-end">المبلغ</th>
        </tr>
      </thead>
      <tbody>
        <?php if(!$lastTx): ?>
          <tr><td colspan="6" class="text-center text-secondary py-4">لا توجد بيانات بعد</td></tr>
        <?php else: foreach($lastTx as $t): ?>
          <tr>
            <td class="text-secondary"><?= (int)$t['id'] ?></td>
            <td class="text-secondary"><?= h($t['tx_date']) ?></td>
            <td>
              <?php if($t['tx_type']==='IN'): ?>
                <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="small"><?= h($t['cash_code'].' - '.$t['cash_name']) ?></td>
            <td class="small"><?= h($t['cnt_code'].' - '.$t['cnt_name']) ?></td>
            <td class="text-end fw-semibold"><?= number_format((float)$t['amount'], 2) ?></td>
          </tr>
        <?php endforeach; endif; ?>
      </tbody>
    </table>
  </div>
</div>

<script>
const ctx = document.getElementById('revExpChart');
if (ctx) {
  new Chart(ctx, {
    type: 'line',
    data: {
      labels: <?= json_encode($labels, JSON_UNESCAPED_UNICODE) ?>,
      datasets: [
        { label: 'إيرادات', data: <?= json_encode($revSeries) ?>, tension: .35 },
        { label: 'مصروفات', data: <?= json_encode($expSeries) ?>, tension: .35 }
      ]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      interaction: { mode: 'index', intersect: false },
      plugins: { legend: { position: 'top' } },
      scales: { y: { beginAtZero: true } }
    }
  });
}
</script>
<?php }); ?>
