<?php
$page_title = 'الأرصدة اليومية وإغلاق الصناديق';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidDailyBalances = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidDailyBalances) $UA_PAGE_CSS = ['assets/css/android_finance_daily_balances.css'];
require_once __DIR__ . '/finance_bootstrap.php';
require_login('login.php');
if (function_exists('require_perm')) require_perm('can_view_reports');

$day = trim((string)($_GET['day'] ?? date('Y-m-d')));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $day) || strtotime($day) === false) $day = date('Y-m-d');
$selected = trim((string)($_GET['account'] ?? 'all'));
$msg = '';

finance_daily_auto_close($conn);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'close_day') {
  if (function_exists('ua_csrf_verify') && !ua_csrf_verify()) {
    $msg = 'تعذر التحقق من الطلب.';
  } else {
    $actor = (string)($_SESSION['admin_username'] ?? $_SESSION['admin_user'] ?? 'admin');
    $result = finance_daily_close_day($conn, $day, 'MANUAL', $actor);
    $msg = !empty($result['ok']) ? 'تم تثبيت الرصيد النهائي لصناديق هذا اليوم.' : 'تعذر إغلاق اليوم.';
  }
}

$allRows = finance_daily_view($conn, $day);
$rows = $selected === 'all' ? $allRows : array_values(array_filter($allRows, static fn($row) => $row['account_key'] === $selected));
$totals = ['opening'=>0.0,'income'=>0.0,'expenses'=>0.0,'net'=>0.0,'final'=>0.0];
foreach ($rows as $row) foreach (array_keys($totals) as $field) $totals[$field] += (float)$row[$field];
$typeLabels = ['main'=>'رئيسية','branch'=>'فرعية','agent'=>'مندوب'];
$finance_active = 'cashbox'; $finance_group = 'summary';

require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
if ($uaAndroidDailyBalances) { require __DIR__ . '/android_finance_daily_balances.php'; require __DIR__ . '/footer.php'; return; }
?>
<div class="content-wrapper ua-extracted-page">
  <section class="content"><div class="container-fluid">
    <?php include __DIR__ . '/finance_tabs.php'; ?>
    <?php if($msg): ?><div class="alert alert-info"><?= h($msg) ?></div><?php endif; ?>
    <div class="card"><div class="card-header"><h3 class="card-title">الأرصدة اليومية وإغلاق الصناديق</h3></div><div class="card-body">
      <form method="get" class="form-row align-items-end mb-3">
        <div class="col-md-3"><label>اليوم</label><input class="form-control" type="date" name="day" value="<?= h($day) ?>"></div>
        <div class="col-md-5"><label>الصندوق</label><select class="form-control" name="account"><option value="all">جميع النسخ</option><?php foreach($allRows as $row): ?><option value="<?= h($row['account_key']) ?>" <?= $selected===$row['account_key']?'selected':'' ?>><?= h($row['account_name']) ?> — <?= h($typeLabels[$row['account_type']] ?? $row['account_type']) ?></option><?php endforeach; ?></select></div>
        <div class="col-md-2"><button class="btn btn-primary btn-block">عرض</button></div>
      </form>
      <div class="row mb-3">
        <?php foreach(['opening'=>'رصيد البداية','income'=>'مقبوضات اليوم','expenses'=>'مصروفات اليوم','net'=>'صافي اليوم','final'=>'الرقم النهائي'] as $field=>$label): ?>
          <div class="col"><div class="small text-muted"><?= h($label) ?></div><div class="h4" dir="ltr"><?= number_format($totals[$field],2) ?></div></div>
        <?php endforeach; ?>
      </div>
      <div class="table-responsive"><table class="table table-bordered table-hover"><thead><tr><th>النسخة / الصندوق</th><th>النوع</th><th>البداية</th><th>المقبوضات</th><th>المصروفات</th><th>الصافي</th><th>الرقم النهائي</th><th>الحالة</th></tr></thead><tbody>
      <?php foreach($rows as $row): ?><tr><td><strong><?= h($row['account_name']) ?></strong><small class="d-block text-muted" dir="ltr"><?= h($row['account_ref']) ?></small></td><td><?= h($typeLabels[$row['account_type']] ?? $row['account_type']) ?></td><td><?= number_format($row['opening'],2) ?></td><td class="text-success"><?= number_format($row['income'],2) ?></td><td class="text-danger"><?= number_format($row['expenses'],2) ?></td><td><?= number_format($row['net'],2) ?></td><td><strong><?= number_format($row['final'],2) ?></strong></td><td><span class="badge badge-<?= $row['closed']?'danger':'success' ?>"><?= $row['closed']?'مغلق':'مباشر' ?></span></td></tr><?php endforeach; ?>
      <?php if(!$rows): ?><tr><td colspan="8" class="text-center text-muted">لا توجد صناديق مطابقة.</td></tr><?php endif; ?>
      </tbody></table></div>
      <?php if($day <= date('Y-m-d') && array_filter($allRows, static fn($row)=>!$row['closed'])): ?><form method="post" class="mt-3"><?php if(function_exists('ua_csrf_field'))ua_csrf_field(); ?><input type="hidden" name="action" value="close_day"><button class="btn btn-danger" onclick="return confirm('تثبيت الرقم النهائي وإغلاق صناديق هذا اليوم؟')"><i class="fa fa-lock"></i> إغلاق اليوم الآن</button></form><?php endif; ?>
      <p class="text-muted mt-3 mb-0">تُغلق الأيام السابقة تلقائياً، ويصبح الرقم النهائي لكل نسخة هو رصيد بداية يومها التالي.</p>
    </div></div>
  </div></section>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
