<?php
// admin/api/subscriber_quick_view.php
// Returns minimal subscriber details + current month invoice due status.

@ini_set('display_errors', '0');
@ini_set('log_errors', '0');
error_reporting(0);

if (session_status() === PHP_SESSION_NONE) { @session_start(); }
header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/../auth.php';
require_once __DIR__ . '/../db_bootstrap.php';
require_once __DIR__ . '/../super_admin_guard.php';
require_once __DIR__ . '/../subscriber_view_data_lib.php';

function out_json(array $arr, int $code = 200): void {
  http_response_code($code);
  echo json_encode($arr, JSON_UNESCAPED_UNICODE);
  exit;
}

require_login();
$conn = ensure_db(true);

// require super admin confirmation (via session)
if (!super_admin_ok()) {
  out_json(['ok' => false, 'message' => 'تأكيد السوبر أدمن مطلوب'], 403);
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) out_json(['ok' => false, 'message' => 'id مطلوب'], 400);

$viewData = function_exists('subscriber_view_load') ? subscriber_view_load($conn, $id, true, false) : null;
if (!$viewData) out_json(['ok' => false, 'message' => 'المشترك غير موجود'], 404);
$s = $viewData['row'];
$identity = $viewData['identity'];
$runtime = $viewData['runtime'];
$ppp_user = (string)($identity['ppp_username'] ?? '');
$ppp_pass = (string)($identity['ppp_password'] ?? '');

$cycle = date('Y-m');

// Determine due invoice: for current month prefer remaining_amount>0 or payment_status/status
$due = [
  'has_due' => false,
  'cycle_month' => $cycle,
  'amount' => 0,
  'remaining' => 0,
  'status' => '',
  'payment_status' => ''
];

try {
  $q = "SELECT id, amount, remaining_amount, status, payment_status, cycle_month
        FROM invoices
        WHERE subscriber_id=".(int)$id." AND (cycle_month='".$conn->real_escape_string($cycle)."' OR cycle_month IS NULL OR cycle_month='')
        ORDER BY id DESC LIMIT 5";
  $inv = @$conn->query($q);
  if ($inv) {
    while($i = $inv->fetch_assoc()) {
      $status = (string)($i['status'] ?? '');
      $ps     = (string)($i['payment_status'] ?? '');
      $rem    = (float)($i['remaining_amount'] ?? 0);
      $amt    = (float)($i['amount'] ?? 0);

      $isDue = false;
      if ($rem > 0.0001) $isDue = true;
      if (mb_strpos($status, 'غير') !== false) $isDue = true;
      if (strtolower($ps) === 'unpaid') $isDue = true;

      if ($isDue) {
        $due['has_due'] = true;
        $due['cycle_month'] = (string)($i['cycle_month'] ?? $cycle);
        $due['amount'] = $amt;
        $due['remaining'] = $rem;
        $due['status'] = $status;
        $due['payment_status'] = $ps;
        break;
      }
    }
  }
} catch(Throwable $e) {}

out_json([
  'ok' => true,
  'subscriber' => [
    'id' => (int)($s['id'] ?? 0),
    'full_name' => (string)($s['full_name'] ?? ''),
    'username' => (string)($s['username'] ?? ''),
    'ppp_username' => $ppp_user,
    'ppp_password' => $ppp_pass,
    'is_online' => !empty($runtime['is_online']) ? 1 : 0,
    'status' => (string)($identity['status'] ?? ($s['status'] ?? '')),
  ],
  'due' => $due,
]);
