<?php
$page_title = 'الصندوق اليومي | Cashbox';
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/finance_bootstrap.php';

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

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

// Normalize day
$ts = strtotime($day);
if ($ts === false) { $day = date('Y-m-d'); $ts = time(); }
$day = date('Y-m-d', $ts);

// Compute totals for day
$in_total = 0.0; $out_total=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($in_total); $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($out_total); $stmt->fetch(); $stmt->close();

// Load row
$row = ['opening_balance'=>0.0,'closing_balance'=>null,'closed_at'=>null,'closed_by'=>null,'totals_json'=>null];
$stmt = $conn->prepare("SELECT opening_balance, closing_balance, closed_at, closed_by, totals_json FROM cashbox_daily WHERE day=?");
$stmt->bind_param('s',$day); $stmt->execute();
$res = $stmt->get_result();
if ($res && $res->num_rows) { $row = $res->fetch_assoc() ?: $row; }
$stmt->close();

$opening_balance = isset($row['opening_balance']) ? (float)$row['opening_balance'] : 0.0;
$expected = $opening_balance + (float)$in_total - (float)$out_total;
$is_closed = !empty($row['closed_at']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  $day_post = $_POST['day'] ?? $day;
  if ($day_post !== $day) { $day = $day_post; }

  if ($action === 'save_opening') {
    if ($is_closed) {
      $err = 'اليوم مُقفل. لا يمكن تعديل رصيد الافتتاح بعد الإقفال.';
    } else {
      $opening = (float)($_POST['opening_balance'] ?? 0);
      $stmt = $conn->prepare("INSERT INTO cashbox_daily(day, opening_balance, created_at) VALUES(?,?,NOW()) ON DUPLICATE KEY UPDATE opening_balance=VALUES(opening_balance)");
      $stmt->bind_param('sd', $day, $opening);
      if (@$stmt->execute()) $msg='تم حفظ رصيد الافتتاح'; else $err='فشل حفظ رصيد الافتتاح: ' . $stmt->error;
      $stmt->close();
    }
    header('Location: finance_cashbox.php?day=' . urlencode($day) . '&saved=1');
    exit;
  }

  if ($action === 'close_day') {
    if ($is_closed) {
      $err = 'تم إقفال هذا اليوم مسبقًا.';
    } else {
      $closing = (float)($_POST['closing_balance'] ?? 0);
      $by = $_SESSION['admin_username'] ?? ($_SESSION['admin_user'] ?? 'admin');

      // Refresh totals before snapshot (best-effort)
      $in = 0.0; $out=0.0; $opening = $opening_balance;
      $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($in); $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($out); $stmt->fetch(); $stmt->close();

      $expected_now = (float)$opening + (float)$in - (float)$out;
      $diff = (float)$closing - (float)$expected_now;

      $snapshot = [
        'day' => $day,
        'opening' => (float)$opening,
        'income' => (float)$in,
        'expenses' => (float)$out,
        'expected' => (float)$expected_now,
        'closing' => (float)$closing,
        'diff' => (float)$diff,
      ];
      $json = json_encode($snapshot, JSON_UNESCAPED_UNICODE);

      $stmt = $conn->prepare("INSERT INTO cashbox_daily(day, opening_balance, closing_balance, closed_by, closed_at, archived_at, totals_json, created_at)
        VALUES(?,?,?,?,NOW(),NOW(),?,NOW())
        ON DUPLICATE KEY UPDATE closing_balance=VALUES(closing_balance), closed_by=VALUES(closed_by), closed_at=VALUES(closed_at), archived_at=VALUES(archived_at), totals_json=VALUES(totals_json)");
      $stmt->bind_param('sddss', $day, $opening, $closing, $by, $json);
      if (@$stmt->execute()) {
        $msg='تم إقفال اليوم بنجاح.';
      } else {
        $err='فشل إقفال اليوم: ' . $stmt->error;
      }
      $stmt->close();
    }
    header('Location: finance_cashbox.php?day=' . urlencode($day) . '&closed=1');
    exit;
  }

  if ($action === 'open_day') {
    // reopen
    $stmt = $conn->prepare("UPDATE cashbox_daily SET closing_balance=NULL, closed_at=NULL, closed_by=NULL, archived_at=NULL, totals_json=NULL WHERE day=?");
    $stmt->bind_param('s',$day);
    if (@$stmt->execute()) $msg='تم فتح اليوم (إلغاء الإقفال).'; else $err='فشل فتح اليوم: ' . $stmt->error;
    $stmt->close();
    header('Location: finance_cashbox.php?day=' . urlencode($day) . '&opened=1');
    exit;
  }
}

// Reload row after actions (simple)
$row = ['opening_balance'=>0.0,'closing_balance'=>null,'closed_at'=>null,'closed_by'=>null,'totals_json'=>null];
$stmt = $conn->prepare("SELECT opening_balance, closing_balance, closed_at, closed_by, totals_json FROM cashbox_daily WHERE day=?");
$stmt->bind_param('s',$day); $stmt->execute();
$res = $stmt->get_result();
if ($res && $res->num_rows) { $row = $res->fetch_assoc() ?: $row; }
$stmt->close();

$opening_balance = isset($row['opening_balance']) ? (float)$row['opening_balance'] : 0.0;
$closing_balance = $row['closing_balance'];
$is_closed = !empty($row['closed_at']);

// Recompute totals for display
$in_total = 0.0; $out_total=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($in_total); $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($out_total); $stmt->fetch(); $stmt->close();
$expected = $opening_balance + $in_total - $out_total;

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

$finance_active = 'cashbox';
$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 class="form-inline ua-u-flex-wrap-gap10" method="get">
            <label>اليوم</label>
            <input type="date" name="day" value="<?= h($day) ?>" class="form-control">
            <button class="btn btn-primary">عرض</button>
            <a class="btn btn-outline-dark" href="finance_day_report.php?day=<?= h($day) ?>" 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_day">
                <input type="hidden" name="day" value="<?= h($day) ?>">
                <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_day">
                <input type="hidden" name="day" value="<?= h($day) ?>">
                <button class="btn btn-success" onclick="return confirm('فتح اليوم (إلغاء الإقفال)؟');">فتح اليوم</button>
              </form>
            <?php endif; ?>
          </div>

          <hr>

          <div class="row">
            <div class="col-md-3"><div class="small text-muted">مقبوضات اليوم</div><div class="h4"><?= number_format($in_total,2) ?></div></div>
            <div class="col-md-3"><div class="small text-muted">مصاريف اليوم</div><div class="h4"><?= number_format($out_total,2) ?></div></div>
            <div class="col-md-3"><div class="small text-muted">الرصيد المتوقع</div><div class="h4"><?= number_format($expected,2) ?></div></div>
            <div class="col-md-3"><div class="small text-muted">رصيد الإقفال</div><div class="h4"><?= number_format((float)($closing_balance ?? 0),2) ?></div></div>
          </div>

          <hr>

          <div class="row">
            <div class="col-md-6">
              <form method="post">
                <input type="hidden" name="action" value="save_opening">
                <input type="hidden" name="day" value="<?= h($day) ?>">
                <div class="form-group">
                  <label>رصيد الافتتاح</label>
                  <input type="number" step="0.01" name="opening_balance" class="form-control" value="<?= h((string)$opening_balance) ?>" <?= $is_closed ? 'readonly' : '' ?>>
                </div>
                <button class="btn btn-success" <?= $is_closed ? 'disabled' : '' ?>>حفظ الافتتاح</button>
              </form>
            </div>

            <div class="col-md-6">
              <?php if(!$is_closed): ?>
              <form method="post">
                <input type="hidden" name="action" value="close_day">
                <input type="hidden" name="day" value="<?= h($day) ?>">
                <div class="form-group">
                  <label>رصيد الإقفال</label>
                  <input type="number" step="0.01" name="closing_balance" class="form-control" value="">
                </div>
                <button class="btn btn-danger">إقفال اليوم</button>
              </form>
              <?php else: ?>
                <div class="small text-muted">مقفول بتاريخ: <?= h($row['closed_at']) ?><?= $row['closed_by'] ? ' — بواسطة: '.h($row['closed_by']) : '' ?></div>
              <?php endif; ?>
            </div>
          </div>

          <div class="mt-3 ua-u-op-80">
            <small>ملاحظة: عند إقفال اليوم، يتم قفل إدخال المصاريف والدفعات بتاريخ هذا اليوم (قفل يومي للصندوق).</small>
          </div>
        </div>
      </div>

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