<?php

require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/db_schema_helpers.php';

function ua_agent_backup_sql(mysqli $conn, string $targetFile): array {
  $tables = [
    'agents',
    'agent_transactions',
    'agent_ledger_entries',
    'agent_activity_log',
    'agent_sync_events',
    'agent_sync_nonces',
    'payments',
    'invoices',
    'subscribers',
    'shop_sales',
    'ua_link_requests',
  ];
  $handle = @fopen($targetFile, 'wb');
  if (!$handle) return ['ok'=>false,'error'=>'تعذر إنشاء ملف النسخة الاحتياطية.'];

  fwrite($handle, "-- Agents module recovery backup\n");
  fwrite($handle, "-- Generated: " . date('Y-m-d H:i:s') . "\n");
  fwrite($handle, "SET NAMES utf8mb4;\nSET FOREIGN_KEY_CHECKS=0;\n\n");
  $exported = [];

  foreach ($tables as $table) {
    if (!table_exists($conn, $table)) continue;
    $createRs = $conn->query("SHOW CREATE TABLE `{$table}`");
    if (!$createRs || !($create = $createRs->fetch_assoc())) continue;
    $createSql = (string)($create['Create Table'] ?? array_values($create)[1] ?? '');
    fwrite($handle, "-- Table: {$table}\nDROP TABLE IF EXISTS `{$table}`;\n{$createSql};\n\n");

    $rows = $conn->query("SELECT * FROM `{$table}`");
    $rowCount = 0;
    if ($rows) while ($row = $rows->fetch_assoc()) {
      $columns = array_map(static fn($column) => '`' . str_replace('`', '', (string)$column) . '`', array_keys($row));
      $values = [];
      foreach ($row as $value) {
        $values[] = $value === null ? 'NULL' : "'" . $conn->real_escape_string((string)$value) . "'";
      }
      fwrite($handle, "INSERT INTO `{$table}` (" . implode(',', $columns) . ") VALUES (" . implode(',', $values) . ");\n");
      $rowCount++;
    }
    fwrite($handle, "\n");
    $exported[$table] = $rowCount;
  }

  fwrite($handle, "SET FOREIGN_KEY_CHECKS=1;\n");
  fclose($handle);
  return ['ok'=>true,'file'=>$targetFile,'tables'=>$exported,'bytes'=>(int)filesize($targetFile),'error'=>''];
}

if (PHP_SAPI === 'cli' && realpath((string)($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
  $conn = ensure_db(true);
  $directory = __DIR__ . DIRECTORY_SEPARATOR . 'backups';
  if (!is_dir($directory)) @mkdir($directory, 0775, true);
  $target = $argv[1] ?? ($directory . DIRECTORY_SEPARATOR . 'agents_module_' . date('Ymd_His') . '.sql');
  $result = ua_agent_backup_sql($conn, $target);
  echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . PHP_EOL;
  exit($result['ok'] ? 0 : 1);
}
