<?php
$page_title = 'تقرير إقفال اليوم';
$finance_active = 'day_report';
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/finance_bootstrap.php';
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

$day = $_GET['day'] ?? date('Y-m-d');
$ts = strtotime($day);
if ($ts === false) { $day = date('Y-m-d'); $ts = time(); }
$day = date('Y-m-d', $ts);

$snap = null;
$stmt = $conn->prepare("SELECT totals_json, closed_at, closed_by, opening_balance, closing_balance FROM cashbox_daily WHERE day=? LIMIT 1");
$stmt->bind_param('s',$day);
$stmt->execute();
$res = $stmt->get_result();
$row = $res && $res->num_rows ? ($res->fetch_assoc() ?: null) : null;
$stmt->close();

if ($row && !empty($row['totals_json'])) {
  $j = json_decode($row['totals_json'], true);
  if (is_array($j)) $snap = $j;
}
if (!$snap) {
  $opening = $row ? (float)($row['opening_balance'] ?? 0) : 0.0;
  $closing = $row ? (float)($row['closing_balance'] ?? 0) : 0.0;
  $income = 0.0; $expenses = 0.0;
  $stmt = $conn->prepare("SELECT COALESCE(SUM(amount),0) s FROM payments WHERE DATE(COALESCE(paid_at, created_at))=?");
  $stmt->bind_param('s',$day); $stmt->execute(); $stmt->bind_result($income); $stmt->fetch(); $stmt->close();
  $stmt = $conn->prepare("SELECT COALESCE(SUM(amount),0) s FROM expenses WHERE DATE(COALESCE(spent_at, expense_date))=? AND COALESCE(expense_status,'POSTED')='POSTED'");
  $stmt->bind_param('s',$day); $stmt->execute(); $stmt->bind_result($expenses); $stmt->fetch(); $stmt->close();
  $expected = $opening + $income - $expenses;
  $snap = ['day'=>$day,'opening'=>$opening,'income'=>$income,'expenses'=>$expenses,'expected'=>$expected,'closing'=>$closing,'diff'=>$closing-$expected];
}
$closed_at = $row['closed_at'] ?? null;
$closed_by = $row['closed_by'] ?? null;
$payments = [];
$res = $conn->query("SELECT id, invoice_id, amount, method, COALESCE(reference, ref) AS reference, note, COALESCE(paid_at, created_at) AS dt FROM payments WHERE DATE(COALESCE(paid_at, created_at))='{$day}' ORDER BY dt ASC");
if ($res) while($r=$res->fetch_assoc()) $payments[]=$r;
$exp = [];
$res = $conn->query("SELECT id, COALESCE(title, category) AS title, category, amount, COALESCE(spent_at, expense_date) AS d, note FROM expenses WHERE DATE(COALESCE(spent_at, expense_date))='{$day}' AND COALESCE(expense_status,'POSTED')='POSTED' ORDER BY d ASC, id ASC");
if ($res) while($r=$res->fetch_assoc()) $exp[]=$r;
function fm($v){ return number_format((float)$v, 2); }
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content"><div class="container-fluid"><?php include __DIR__ . '/finance_tabs.php'; ?></div></section>
  <section class="content-header"><div class="container-fluid"><div class="fin-report-head"><div><h1 class="fin-report-title">تقرير إقفال اليوم</h1><div class="fin-report-sub">اليوم: <?= h($day) ?><?= $closed_at ? ' — مقفول بتاريخ: '.h($closed_at) : '' ?><?= $closed_by ? ' — بواسطة: '.h($closed_by) : '' ?></div></div><div class="fin-actions"><a class="fin-btn fin-btn--primary" href="#" onclick="window.print();return false;">طباعة / حفظ PDF</a><a class="fin-btn" href="finance_cashbox.php?day=<?= h($day) ?>">عودة للصندوق</a></div></div></div></section>
  <section class="content"><div class="container-fluid">
    <div class="fin-kpis">
      <div class="fin-kpi"><div class="t">رصيد الافتتاح</div><div class="v"><?= fm($snap['opening']) ?></div></div>
      <div class="fin-kpi"><div class="t">مقبوضات</div><div class="v"><?= fm($snap['income']) ?></div></div>
      <div class="fin-kpi"><div class="t">مصاريف</div><div class="v"><?= fm($snap['expenses']) ?></div></div>
      <div class="fin-kpi"><div class="t">الرصيد المتوقع</div><div class="v"><?= fm($snap['expected']) ?></div></div>
      <div class="fin-kpi"><div class="t">رصيد الإقفال</div><div class="v"><?= fm($snap['closing']) ?></div></div>
      <div class="fin-kpi"><div class="t">الفرق</div><div class="v"><?= fm($snap['diff']) ?></div></div>
    </div>
    <div class="card fin-card mb-4"><div class="card-header">تفاصيل المقبوضات</div><div class="card-body p-0"><div class="table-responsive"><table class="table mb-0"><thead><tr><th>#</th><th>الوقت</th><th>فاتورة</th><th>المبلغ</th><th>الطريقة</th><th>مرجع</th><th>ملاحظة</th></tr></thead><tbody><?php if(empty($payments)): ?><tr><td colspan="7" class="text-center fin-empty">لا يوجد</td></tr><?php else: foreach($payments as $p): ?><tr><td><?= (int)$p['id'] ?></td><td><?= h($p['dt']) ?></td><td><?= h((string)$p['invoice_id']) ?></td><td><?= fm($p['amount']) ?></td><td><?= h((string)$p['method']) ?></td><td><?= h((string)$p['reference']) ?></td><td><?= h((string)$p['note']) ?></td></tr><?php endforeach; endif; ?></tbody></table></div></div></div>
    <div class="card fin-card mb-4"><div class="card-header">تفاصيل المصاريف</div><div class="card-body p-0"><div class="table-responsive"><table class="table mb-0"><thead><tr><th>#</th><th>التاريخ</th><th>التصنيف</th><th>العنوان</th><th>المبلغ</th><th>ملاحظة</th></tr></thead><tbody><?php if(empty($exp)): ?><tr><td colspan="6" class="text-center fin-empty">لا يوجد</td></tr><?php else: foreach($exp as $e): ?><tr><td><?= (int)$e['id'] ?></td><td><?= h($e['d']) ?></td><td><?= h((string)$e['category']) ?></td><td><?= h((string)$e['title']) ?></td><td><?= fm($e['amount']) ?></td><td><?= h((string)$e['note']) ?></td></tr><?php endforeach; endif; ?></tbody></table></div></div></div>
  </div></section>
</div>
<?php require_once __DIR__ . '/output_devices_lib.php'; ua_output_print_bootstrap($conn, 'daily_finance_report', (string)$day); ?>
<?php include __DIR__ . '/footer.php'; ?>
