<?php
$page_title = 'تقرير المعتمدين';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidAgentsReport = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidAgentsReport) $UA_PAGE_CSS = ['assets/css/android_agents_report.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';

require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/agent_service.php';

require_login();
if (function_exists('require_perm')) require_perm('can_manage_agents');

$conn = ensure_db(true);

// Ensure dependent tables (best-effort)
@include_once __DIR__ . '/shop_lib.php';
@include_once __DIR__ . '/vouchers_lib.php';
@include_once __DIR__ . '/finance_bootstrap.php';
@include_once __DIR__ . '/finance_payment_lib.php';
if (function_exists('ensure_shop_tables')) {
  try { ensure_shop_tables($conn); } catch (Throwable $e) {}
}
if (function_exists('finance_ensure_payments_table')) {
  try { finance_ensure_payments_table($conn); } catch (Throwable $e) {}
}
ua_agent_schema_migrate($conn);

// Date filters
$today = date('Y-m-d');
$from = $_GET['from'] ?? $today;
$to   = $_GET['to']   ?? $today;

// sanitize dates (YYYY-MM-DD)
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = $today;
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) $to = $today;

// Summary query per agent
$sql = "
SELECT
  a.id,
  a.name,
  a.username,
  a.phone,
  a.balance_cached AS balance,
  COALESCE(ss.sales_cnt,0)  AS sales_cnt,
  COALESCE(ss.sales_sum,0)  AS sales_sum,
  COALESCE(pm.pay_sum,0)    AS pay_sum,
  COALESCE(dr.reset_cnt,0)  AS reset_cnt,
  COALESCE(tp.topup_sum,0)  AS topup_sum
FROM agents a
LEFT JOIN (
  SELECT agent_id, COUNT(*) sales_cnt, COALESCE(SUM(net_total),0) sales_sum
  FROM shop_sales
  WHERE agent_id IS NOT NULL AND DATE(created_at) BETWEEN ? AND ?
  GROUP BY agent_id
) ss ON ss.agent_id = a.id
LEFT JOIN (
  SELECT agent_id, COALESCE(SUM(amount),0) pay_sum
  FROM payments
  WHERE agent_id IS NOT NULL AND payment_status='POSTED' AND DATE(COALESCE(paid_at, created_at)) BETWEEN ? AND ?
  GROUP BY agent_id
) pm ON pm.agent_id = a.id
LEFT JOIN (
  SELECT agent_id, COUNT(*) reset_cnt
  FROM agent_activity_log
  WHERE event_type='DEVICE_RESET' AND status='SUCCESS' AND DATE(occurred_at) BETWEEN ? AND ?
  GROUP BY agent_id
) dr ON dr.agent_id = a.id
LEFT JOIN (
  SELECT agent_id, COALESCE(SUM(amount),0) topup_sum
  FROM agent_ledger_entries
  WHERE direction='CREDIT' AND entry_type IN ('AGENT_RECEIPT','ADMIN_ADJUSTMENT') AND status IN ('POSTED','REVERSED') AND DATE(occurred_at) BETWEEN ? AND ?
  GROUP BY agent_id
) tp ON tp.agent_id = a.id
ORDER BY a.id DESC
";

$rows = [];
$stmt = $conn->prepare($sql);
if ($stmt) {
  $stmt->bind_param('ssssssss', $from, $to, $from, $to, $from, $to, $from, $to);
  $stmt->execute();
  $res = $stmt->get_result();
  if ($res) {
    while ($r = $res->fetch_assoc()) $rows[] = $r;
  }
  $stmt->close();
}

// Totals
$tot_sales_cnt = 0; $tot_sales_sum = 0.0; $tot_pay_sum = 0.0; $tot_reset = 0; $tot_topup = 0.0;
foreach ($rows as $r) {
  $tot_sales_cnt += (int)($r['sales_cnt'] ?? 0);
  $tot_sales_sum += (float)($r['sales_sum'] ?? 0);
  $tot_pay_sum   += (float)($r['pay_sum'] ?? 0);
  $tot_reset     += (int)($r['reset_cnt'] ?? 0);
  $tot_topup     += (float)($r['topup_sum'] ?? 0);
}
if ($uaAndroidAgentsReport) { require __DIR__ . '/android_agents_report.php'; include __DIR__ . '/footer.php'; return; }
?>

<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid">
      <div class="d-flex align-items-center justify-content-between">
        <h1 class="mb-0">تقرير المعتمدين</h1>
        <a class="btn btn-outline-secondary" href="agents.php">رجوع للمعتمدين</a>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">

      <div class="card">
        <div class="card-body">
          <form method="get" class="row ua-u-gap-075">
            <div class="col-md-3">
              <label>من</label>
              <input class="form-control" type="date" name="from" value="<?= h($from) ?>">
            </div>
            <div class="col-md-3">
              <label>إلى</label>
              <input class="form-control" type="date" name="to" value="<?= h($to) ?>">
            </div>
            <div class="col-md-3 d-flex align-items-end">
              <button class="btn btn-primary w-100">تطبيق</button>
            </div>
            <div class="col-md-3 d-flex align-items-end">
              <a class="btn btn-outline-secondary w-100" href="agents_report.php">اليوم</a>
            </div>
          </form>
        </div>
      </div>

      <div class="row">
        <div class="col-md-3"><div class="small-box bg-info"><div class="inner"><h3><?= (int)$tot_sales_cnt ?></h3><p>عدد المبيعات</p></div><div class="icon"><i class="fas fa-receipt"></i></div></div></div>
        <div class="col-md-3"><div class="small-box bg-success"><div class="inner"><h3><?= number_format($tot_sales_sum,2) ?></h3><p>إجمالي المبيعات</p></div><div class="icon"><i class="fas fa-coins"></i></div></div></div>
        <div class="col-md-3"><div class="small-box bg-warning"><div class="inner"><h3><?= number_format($tot_pay_sum,2) ?></h3><p>إجمالي المقبوضات</p></div><div class="icon"><i class="fas fa-cash-register"></i></div></div></div>
        <div class="col-md-3"><div class="small-box bg-danger"><div class="inner"><h3><?= (int)$tot_reset ?></h3><p>عمليات تبديل جهاز</p></div><div class="icon"><i class="fas fa-mobile-alt"></i></div></div></div>
      </div>

      <div class="card">
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>#</th>
                  <th>المعتمد</th>
                  <th>اسم المستخدم</th>
                  <th>الهاتف</th>
                  <th>الرصيد</th>
                  <th>مبيعات (عدد)</th>
                  <th>مبيعات (إجمالي)</th>
                  <th>مقبوضات</th>
                  <th>المقبوض والتسويات الدائنة</th>
                  <th>تبديل جهاز</th>
                  <th>تفاصيل</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach($rows as $r){ ?>
                  <tr>
                    <td><?= (int)$r['id'] ?></td>
                    <td><?= h($r['name']) ?></td>
                    <td><?= h($r['username'] ?? '-') ?></td>
                    <td><?= h($r['phone'] ?? '-') ?></td>
                    <td><?= number_format((float)($r['balance'] ?? 0),2) ?></td>
                    <td><?= (int)($r['sales_cnt'] ?? 0) ?></td>
                    <td><?= number_format((float)($r['sales_sum'] ?? 0),2) ?></td>
                    <td><?= number_format((float)($r['pay_sum'] ?? 0),2) ?></td>
                    <td><?= number_format((float)($r['topup_sum'] ?? 0),2) ?></td>
                    <td><?= (int)($r['reset_cnt'] ?? 0) ?></td>
                    <td>
                      <a class="btn btn-sm btn-outline-primary" href="agents_report_view.php?agent_id=<?= (int)$r['id'] ?>&from=<?= h($from) ?>&to=<?= h($to) ?>">عرض</a>
                    </td>
                  </tr>
                <?php } ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>
  </section>
</div>

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