<?php
$page_title = 'إغلاق الشهر | Month Close';
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/finance_bootstrap.php';

$msg=''; $err='';

$month = $_GET['month'] ?? date('Y-m');

// Normalize to year/month integers
$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'); }

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
	  $month = $_POST['month'] ?? $month;
	  $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'); }

  if ($action === 'close_month') {
    $stmt = $conn->prepare("INSERT INTO month_closings (year, month, closed_at, closed_by) VALUES (?, ?, NOW(), ?) ON DUPLICATE KEY UPDATE closed_at=VALUES(closed_at), closed_by=VALUES(closed_by)");
    $by = $_SESSION['admin_username'] ?? ($_SESSION['admin_user'] ?? 'admin');
    $stmt->bind_param('iis', $y, $m, $by);
    if (@$stmt->execute()) {
      $msg = 'تم إغلاق الشهر بنجاح.';
      // Archive month totals snapshot (for reporting/printing)
      $start = sprintf('%04d-%02d-01', $y, $m);
      $end   = date('Y-m-t', strtotime($start));
      // Payments (income)
      $income = 0.0;
      $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'];
      // Expenses
      $expenses = 0.0;
      $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'];

      // Invoices totals (best-effort if invoices table exists)
      $inv_total = null; $inv_paid = null; $inv_unpaid_cnt = null; $inv_cnt = null;
      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) {
          $q = "SELECT COALESCE(SUM({$total_col}),0) AS t, COUNT(*) AS c FROM invoices WHERE DATE({$date_col}) BETWEEN '{$start}' AND '{$end}'";
          $res3 = $conn->query($q);
          if ($res3 && ($r3=$res3->fetch_assoc())) { $inv_total = (float)$r3['t']; $inv_cnt = (int)$r3['c']; }
        }
        // unpaid count if status/payment_status exists
        $status_col = finance_pick_col($conn,'invoices',['payment_status','status']);
        if ($status_col && $date_col) {
          $q = "SELECT COUNT(*) AS c FROM invoices WHERE DATE({$date_col}) BETWEEN '{$start}' AND '{$end}' AND {$status_col} IN ('unpaid','partial')";
          $res4 = $conn->query($q);
          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) {
          $q = "SELECT COALESCE(SUM({$paid_col}),0) AS s FROM invoices WHERE DATE({$date_col}) BETWEEN '{$start}' AND '{$end}'";
          $res5 = $conn->query($q);
          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,
      ];
      $json = $conn->real_escape_string(json_encode($snapshot, JSON_UNESCAPED_UNICODE));
      @$conn->query("UPDATE month_closings SET archived_at=NOW(), totals_json='{$json}' WHERE year={$y} AND month={$m} LIMIT 1");
    } else {
      $err = 'فشل إغلاق الشهر: ' . $stmt->error;
    }
    $stmt->close();
  }

  if ($action === 'open_month') {
    $stmt = $conn->prepare("DELETE FROM month_closings WHERE year=? AND month=?");
    $stmt->bind_param('ii', $y, $m);
    if (@$stmt->execute()) {
      $msg = 'تم فتح الشهر (إلغاء الإغلاق).';
    } else {
      $err = 'فشل فتح الشهر: ' . $stmt->error;
    }
    $stmt->close();
  }
}

// status
$is_closed = finance_is_month_closed($conn, $y, $m);

include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

$finance_active = 'close';
$finance_group = 'summary';
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6"><h1><?= h($page_title) ?></h1></div>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      
      <?php include __DIR__ . '/finance_tabs.php'; ?>
<?php if($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
      <?php if($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>

      <div class="card">
        <div class="card-body">
          <form method="get" class="form-inline ua-u-flex-wrap-gap10">
            <label>الشهر (YYYY-MM)</label>
            <input type="month" name="month" class="form-control" value="<?= h($month) ?>">
            <button class="btn btn-primary">عرض</button>
            <a class="btn btn-outline-secondary" href="finance_reports.php?start=<?= h($month.'-01') ?>&end=<?= h(date('Y-m-t', strtotime($month.'-01'))) ?>">فتح التقارير</a>
            <a class="btn btn-outline-dark" href="finance_month_report.php?month=<?= h($month) ?>" target="_blank">تقرير الإغلاق / طباعة PDF</a>
          </form>

          <hr>

          <div class="d-flex ua-u-flex-wrap-center-10">
            <span class="badge badge-<?= $is_closed ? 'danger' : 'success' ?> ua-u-fs-14">
              <?= $is_closed ? 'مغلق | Closed' : 'مفتوح | Open' ?>
            </span>

            <?php if(!$is_closed): ?>
              <form class="ua-u-inline" method="post">
                <input type="hidden" name="action" value="close_month">
                <input type="hidden" name="month" value="<?= h($month) ?>">
                <button class="btn btn-danger" onclick="return confirm('تأكيد إغلاق الشهر؟');">إغلاق الشهر</button>
              </form>
            <?php else: ?>
              <form class="ua-u-inline" method="post">
                <input type="hidden" name="action" value="open_month">
                <input type="hidden" name="month" value="<?= h($month) ?>">
                <button class="btn btn-success" onclick="return confirm('فتح الشهر (إلغاء الإغلاق)؟');">فتح الشهر</button>
              </form>
            <?php endif; ?>
          </div>

          <div class="mt-3 ua-u-op-80">
            <small>ملاحظة: إغلاق الشهر يمنع تعديل/تسجيل دفعات على فواتير ذلك الشهر (عند تفعيل شرط الإغلاق ضمن صفحات الدفع).</small>
          </div>
        </div>
      </div>

    </div>
  </section>
</div>
<?php include __DIR__ . '/footer.php'; ?>
