<?php
$page_title = 'تفاصيل تقرير المعتمد';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidAgentsReportView = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidAgentsReportView) $UA_PAGE_CSS = ['assets/css/android_agents_report_view.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);
ua_agent_schema_migrate($conn);

@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('finance_ensure_payments_table')) {
  try { finance_ensure_payments_table($conn); } catch (Throwable $e) {}
}

$today = date('Y-m-d');
$from = $_GET['from'] ?? $today;
$to   = $_GET['to']   ?? $today;
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) $from = $today;
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) $to = $today;

$agent_id = (int)($_GET['agent_id'] ?? 0);
if ($agent_id <= 0) {
  echo '<div class="content-wrapper ua-extracted-page"><section class="content"><div class="container-fluid"><div class="alert alert-danger">معتمد غير صالح</div></div></section></div>';
  include __DIR__ . '/footer.php';
  exit;
}

$agent = null;
$stmt = $conn->prepare('SELECT * FROM agents WHERE id=? LIMIT 1');
if ($stmt) {
  $stmt->bind_param('i', $agent_id);
  $stmt->execute();
  $res = $stmt->get_result();
  $agent = $res ? $res->fetch_assoc() : null;
  $stmt->close();
}
if (!$agent) {
  echo '<div class="content-wrapper"><section class="content"><div class="container-fluid"><div class="alert alert-danger">المعتمد غير موجود</div></div></section></div>';
  include __DIR__ . '/footer.php';
  exit;
}

// Sales list
$sales = [];
$stmt = $conn->prepare("SELECT id, customer_name, net_total, status, created_at FROM shop_sales WHERE agent_id=? AND DATE(created_at) BETWEEN ? AND ? ORDER BY id DESC LIMIT 200");
if ($stmt) {
  $stmt->bind_param('iss', $agent_id, $from, $to);
  $stmt->execute();
  $res = $stmt->get_result();
  if ($res) while ($row = $res->fetch_assoc()) $sales[] = $row;
  $stmt->close();
}

// Payments list (best-effort join on reference)
$payments = [];
$pay_sql = "SELECT p.id, p.invoice_id, p.amount, p.method, COALESCE(p.reference,p.ref) AS refx, p.note, COALESCE(p.paid_at,p.created_at) AS paid_at
            FROM payments p
            WHERE p.agent_id=? AND p.payment_status='POSTED' AND DATE(COALESCE(p.paid_at,p.created_at)) BETWEEN ? AND ?
            ORDER BY p.id DESC LIMIT 300";
$stmt = $conn->prepare($pay_sql);
if ($stmt) {
  $stmt->bind_param('iss', $agent_id, $from, $to);
  $stmt->execute();
  $res = $stmt->get_result();
  if ($res) while ($row = $res->fetch_assoc()) $payments[] = $row;
  $stmt->close();
}

// Agent ledger
$tx = [];
$stmt = $conn->prepare("SELECT id,entry_type AS type,direction,amount,description AS note,occurred_at AS created_at,balance_after,status FROM agent_ledger_entries WHERE agent_id=? AND DATE(occurred_at) BETWEEN ? AND ? ORDER BY id DESC LIMIT 300");
if ($stmt) {
  $stmt->bind_param('iss', $agent_id, $from, $to);
  $stmt->execute();
  $res = $stmt->get_result();
  if ($res) while ($row = $res->fetch_assoc()) $tx[] = $row;
  $stmt->close();
}

// Totals
$sales_sum = 0.0; foreach($sales as $s) $sales_sum += (float)($s['net_total'] ?? 0);
$pay_sum = 0.0; foreach($payments as $p) $pay_sum += (float)($p['amount'] ?? 0);
$reset_cnt = 0; $topup_sum = 0.0;
foreach($tx as $t){
  if(($t['direction'] ?? '')==='CREDIT' && in_array(($t['type'] ?? ''), ['AGENT_RECEIPT','ADMIN_ADJUSTMENT'], true)) $topup_sum += (float)($t['amount'] ?? 0);
}
$resetStmt = $conn->prepare("SELECT COUNT(*) c FROM agent_activity_log WHERE agent_id=? AND event_type='DEVICE_RESET' AND status='SUCCESS' AND DATE(occurred_at) BETWEEN ? AND ?");
if ($resetStmt) {
  $resetStmt->bind_param('iss', $agent_id, $from, $to);
  $resetStmt->execute();
  $resetResult = $resetStmt->get_result();
  if ($resetResult && ($resetRow = $resetResult->fetch_assoc())) $reset_cnt = (int)$resetRow['c'];
  $resetStmt->close();
}
if ($uaAndroidAgentsReportView) { require __DIR__ . '/android_agents_report_view.php'; include __DIR__ . '/footer.php'; return; }
?>

<div class="content-wrapper">
  <section class="content-header">
    <div class="container-fluid">
      <div class="d-flex align-items-center justify-content-between">
        <div>
          <h1 class="mb-0">تفاصيل المعتمد: <?= h($agent['name']) ?></h1>
          <div class="text-muted"><?= h($agent['username'] ?? '') ?> <?= $agent['phone'] ? ' | ' . h($agent['phone']) : '' ?></div>
        </div>
        <div class="d-flex ua-u-gap-half">
          <a class="btn btn-outline-secondary" href="agents_report.php?from=<?= h($from) ?>&to=<?= h($to) ?>">رجوع للتقرير</a>
          <a class="btn btn-outline-secondary" href="agents.php">المعتمدين</a>
        </div>
      </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">
            <input type="hidden" name="agent_id" value="<?= (int)$agent_id ?>">
            <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>
          </form>
        </div>
      </div>

      <div class="row">
        <div class="col-md-3"><div class="small-box bg-info"><div class="inner"><h3><?= count($sales) ?></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($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($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)$reset_cnt ?></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">
          <h5 class="mb-3">فواتير البيع (آخر 200)</h5>
          <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></tr></thead>
              <tbody>
                <?php foreach($sales as $s){ ?>
                  <tr>
                    <td><?= (int)$s['id'] ?></td>
                    <td><?= h($s['customer_name'] ?? '-') ?></td>
                    <td><?= number_format((float)($s['net_total'] ?? 0),2) ?></td>
                    <td><?= h($s['status'] ?? '-') ?></td>
                    <td><?= h($s['created_at'] ?? '-') ?></td>
                    <td><a class="btn btn-sm btn-outline-primary" href="sales_view.php?id=<?= (int)$s['id'] ?>">عرض</a></td>
                  </tr>
                <?php } ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body">
          <h5 class="mb-3">المدفوعات المرتبطة (آخر 300)</h5>
          <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></tr></thead>
              <tbody>
                <?php foreach($payments as $p){ ?>
                  <tr>
                    <td><?= (int)$p['id'] ?></td>
                    <td><?= number_format((float)($p['amount'] ?? 0),2) ?></td>
                    <td><?= h($p['method'] ?? '-') ?></td>
                    <td><?= h($p['refx'] ?? '-') ?></td>
                    <td><?= h($p['note'] ?? '-') ?></td>
                    <td><?= h($p['paid_at'] ?? '-') ?></td>
                    <td><a class="btn btn-sm btn-outline-secondary" href="finance_payments.php?payment_id=<?= (int)$p['id'] ?>">فتح</a></td>
                  </tr>
                <?php } ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body">
          <div class="d-flex align-items-center justify-content-between">
            <h5 class="mb-3">سجل عمليات المعتمد (آخر 300)</h5>
            <div class="text-muted">المقبوض والتسويات الدائنة خلال الفترة: <?= number_format($topup_sum,2) ?></div>
          </div>
          <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></tr></thead>
              <tbody>
                <?php foreach($tx as $t){ ?>
                  <tr>
                    <td><?= (int)$t['id'] ?></td>
                    <td><?= h($t['type'] ?? '-') ?></td>
                    <td><?= h($t['direction'] ?? '-') ?></td>
                    <td><?= number_format((float)($t['amount'] ?? 0),2) ?></td>
                    <td><?= number_format((float)($t['balance_after'] ?? 0),2) ?></td>
                    <td><?= h($t['note'] ?? '-') ?></td>
                    <td><?= h($t['created_at'] ?? '-') ?></td>
                  </tr>
                <?php } ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

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

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