<?php

require_once dirname(__DIR__) . '/db_bootstrap.php';
require_once dirname(__DIR__) . '/agent_schema.php';

$conn = ensure_db(true);
ua_agent_schema_migrate($conn);
$username = 'acceptance.portal.customer';
$usernameEsc = $conn->real_escape_string($username);
$subscriberRs = $conn->query("SELECT id FROM subscribers WHERE username='{$usernameEsc}' LIMIT 1");
if ($subscriberRs && $subscriberRs->num_rows) {
  $subscriberId = (int)$subscriberRs->fetch_assoc()['id'];
} else {
  $sql = "INSERT INTO subscribers
    (username,password_plain,full_name,father_name,mother_name,phone,speed,package,status,notes,speed_state,base_speed,current_speed,package_name,speed_name,address_area,national_id,is_deleted,ppp_username,ppp_password,ppp_profile,ppp_rate_limit,used_gb,sector_id,vlan_id,provision_status,mt_disabled,pppoe_profile,created_by_type,created_by_id)
    VALUES
    ('acceptance.portal.customer','acceptance','مشترك قبول بوابة المعتمد','اختبار','قبول','0999111111','اختبار','قبول','متوقف','سجل اختبار تشغيلي لبوابة المعتمد','ORIGINAL','اختبار','اختبار','باقة القبول','سرعة القبول','مركز الاختبار','PORTAL-ACC-20260619',0,'','','','',0,1,1,'pending_payment',1,'','admin',1)";
  if (!$conn->query($sql)) {
    fwrite(STDERR, $conn->error . PHP_EOL);
    exit(1);
  }
  $subscriberId = (int)$conn->insert_id;
}

$marker = 'AGENT_PORTAL_ACCEPTANCE_20260619';
$markerEsc = $conn->real_escape_string($marker);
$invoiceRs = $conn->query("SELECT id,status,payment_status FROM invoices WHERE subscriber_id={$subscriberId} AND notes='{$markerEsc}' ORDER BY id DESC LIMIT 1");
if ($invoiceRs && $invoiceRs->num_rows) {
  $invoice = $invoiceRs->fetch_assoc();
  $invoiceId = (int)$invoice['id'];
} else {
  $cycle = date('Y-m');
  $stmt = $conn->prepare("INSERT INTO invoices (subscriber_id,amount,status,cycle_month,invoice_type,notes,paid_amount,remaining_amount,payment_status,created_at,updated_at) VALUES (?,120,'غير مدفوع',?,'ACCEPTANCE',?,0,120,'unpaid',NOW(),NOW())");
  $stmt->bind_param('iss', $subscriberId,$cycle,$marker);
  if (!$stmt->execute()) {
    fwrite(STDERR, $stmt->error . PHP_EOL);
    exit(1);
  }
  $invoiceId = (int)$stmt->insert_id;
  $stmt->close();
}

echo json_encode([
  'ok'=>true,
  'subscriber_id'=>$subscriberId,
  'invoice_id'=>$invoiceId,
  'search_term'=>'مشترك قبول بوابة المعتمد',
  'amount'=>120,
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
