<?php
$page_title = 'تقرير إغلاق الشهر';
$finance_active = 'month_report';
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/finance_bootstrap.php';
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

$month = $_GET['month'] ?? date('Y-m');
$parts = explode('-', $month);
$y = isset($parts[0]) ? (int)$parts[0] : (int)date('Y');
$m = isset($parts[1]) ? (int)$parts[1] : (int)date('m');
if ($m < 1 || $m > 12) $m = (int)date('m');
$start = sprintf('%04d-%02d-01', $y, $m);
$end   = date('Y-m-t', strtotime($start));
$snapshot = null;
$stmt = $conn->prepare("SELECT totals_json, closed_at, closed_by, archived_at FROM month_closings WHERE year=? AND month=? LIMIT 1");
$stmt->bind_param('ii', $y, $m); $stmt->execute(); $res = $stmt->get_result(); $row = $res ? $res->fetch_assoc() : null; $stmt->close();
$closed_at = $row['closed_at'] ?? null; $closed_by = $row['closed_by'] ?? null; $archived_at = $row['archived_at'] ?? null;
if (!empty($row['totals_json'])) $snapshot = json_decode($row['totals_json'], true);
if (!$snapshot) {
  $income = 0.0; $expenses = 0.0; $inv_total = null; $inv_paid = null; $inv_unpaid_cnt = null; $inv_cnt = null;
  $res1 = $conn->query("SELECT COALESCE(SUM(amount),0) AS s FROM payments WHERE DATE(COALESCE(paid_at, created_at)) BETWEEN '{$start}' AND '{$end}'"); if ($res1 && ($r1=$res1->fetch_assoc())) $income = (float)$r1['s'];
  $res2 = $conn->query("SELECT COALESCE(SUM(amount),0) AS s FROM expenses WHERE DATE(COALESCE(spent_at, expense_date)) BETWEEN '{$start}' AND '{$end}' AND COALESCE(expense_status,'POSTED')='POSTED'"); if ($res2 && ($r2=$res2->fetch_assoc())) $expenses = (float)$r2['s'];
  if (finance_table_exists($conn,'invoices')) {
    $total_col = finance_pick_col($conn,'invoices',['amount','total_amount','total','price','invoice_total']);
    $date_col  = finance_pick_col($conn,'invoices',['created_at','invoice_date','date','issued_at']);
    if ($total_col && $date_col) { $res3 = $conn->query("SELECT COALESCE(SUM({$total_col}),0) AS t, COUNT(*) AS c FROM invoices WHERE DATE({$date_col}) BETWEEN '{$start}' AND '{$end}'"); if ($res3 && ($r3=$res3->fetch_assoc())) { $inv_total=(float)$r3['t']; $inv_cnt=(int)$r3['c']; }}
    $status_col = finance_pick_col($conn,'invoices',['payment_status','status']);
    if ($status_col && $date_col) { $res4 = $conn->query("SELECT COUNT(*) AS c FROM invoices WHERE DATE({$date_col}) BETWEEN '{$start}' AND '{$end}' AND {$status_col} IN ('unpaid','partial','غير مدفوع','مدفوع جزئياً')"); if ($res4 && ($r4=$res4->fetch_assoc())) $inv_unpaid_cnt=(int)$r4['c']; }
    $paid_col = finance_pick_col($conn,'invoices',['paid_amount']);
    if ($paid_col && $date_col) { $res5 = $conn->query("SELECT COALESCE(SUM({$paid_col}),0) AS s FROM invoices WHERE DATE({$date_col}) BETWEEN '{$start}' AND '{$end}'"); if ($res5 && ($r5=$res5->fetch_assoc())) $inv_paid=(float)$r5['s']; }
  }
  $snapshot = ['month'=>sprintf('%04d-%02d',$y,$m),'start'=>$start,'end'=>$end,'income'=>$income,'expenses'=>$expenses,'net'=>$income-$expenses,'invoices_total'=>$inv_total,'invoices_paid'=>$inv_paid,'invoices_count'=>$inv_cnt,'invoices_unpaid_count'=>$inv_unpaid_cnt];
}
$payments=[]; $rp=$conn->query("SELECT id, invoice_id, amount, method, COALESCE(reference, ref) AS ref, COALESCE(paid_at, created_at) AS paid_at FROM payments WHERE DATE(COALESCE(paid_at, created_at)) BETWEEN '{$start}' AND '{$end}' ORDER BY paid_at ASC, id ASC"); if($rp) while($r=$rp->fetch_assoc()) $payments[]=$r;
$expenses_rows=[]; $re=$conn->query("SELECT id, COALESCE(title, category) AS title, category, amount, COALESCE(spent_at, expense_date) AS spent_at, note FROM expenses WHERE DATE(COALESCE(spent_at, expense_date)) BETWEEN '{$start}' AND '{$end}' AND COALESCE(expense_status,'POSTED')='POSTED' ORDER BY spent_at ASC, id ASC"); if($re) while($r=$re->fetch_assoc()) $expenses_rows[]=$r;
function money($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">تقرير إغلاق الشهر — <?= h($snapshot['month'] ?? $month) ?></h1><div class="fin-report-sub">الفترة: <?= h($start) ?> — <?= h($end) ?><?= $closed_at ? ' — تم الإغلاق: '.h($closed_at) : '' ?><?= $closed_by ? ' — بواسطة '.h($closed_by) : '' ?><?= $archived_at ? ' — آخر أرشفة: '.h($archived_at) : '' ?></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_month_close.php?month=<?= h($month) ?>">رجوع</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"><?= money($snapshot['income'] ?? 0) ?></div></div>
      <div class="fin-kpi"><div class="t">المصاريف</div><div class="v"><?= money($snapshot['expenses'] ?? 0) ?></div></div>
      <div class="fin-kpi"><div class="t">الصافي</div><div class="v"><?= money($snapshot['net'] ?? 0) ?></div></div>
      <div class="fin-kpi"><div class="t">عدد الفواتير</div><div class="v"><?= (int)($snapshot['invoices_count'] ?? 0) ?></div></div>
      <div class="fin-kpi"><div class="t">إجمالي الفواتير</div><div class="v"><?= $snapshot['invoices_total']===null?'—':money($snapshot['invoices_total']) ?></div></div>
      <div class="fin-kpi"><div class="t">إجمالي المدفوع على الفواتير</div><div class="v"><?= $snapshot['invoices_paid']===null?'—':money($snapshot['invoices_paid']) ?></div></div>
      <div class="fin-kpi"><div class="t">غير مدفوع/جزئي</div><div class="v"><?= $snapshot['invoices_unpaid_count']===null?'—':(int)$snapshot['invoices_unpaid_count'] ?></div></div>
      <div class="fin-kpi"><div class="t">عدد الدفعات</div><div class="v"><?= count($payments) ?></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($payments)): ?><tr><td colspan="6" class="text-center fin-empty">لا يوجد دفعات.</td></tr><?php else: foreach($payments as $r): ?><tr><td><?= (int)$r['id'] ?></td><td><?= (int)$r['invoice_id'] ?></td><td><?= money($r['amount']) ?></td><td><?= h($r['method']) ?></td><td><?= h($r['ref']) ?></td><td><?= h($r['paid_at']) ?></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($expenses_rows)): ?><tr><td colspan="6" class="text-center fin-empty">لا يوجد مصاريف.</td></tr><?php else: foreach($expenses_rows as $r): ?><tr><td><?= (int)$r['id'] ?></td><td><?= h($r['spent_at']) ?></td><td><?= h($r['category']) ?></td><td><?= h($r['title']) ?></td><td><?= money($r['amount']) ?></td><td><?= h($r['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, 'monthly_finance_report', (string)$month); ?>
<?php include __DIR__ . '/footer.php'; ?>
