<?php
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.php';
require_login();

$pdo = db();
$cid = (int)($_SESSION['company_id'] ?? 0);
$uid = (int)($_SESSION['user_id'] ?? 0);

$err = '';
$ok  = '';

function ensure_backups_table(PDO $pdo): void {
  $pdo->exec("
    CREATE TABLE IF NOT EXISTS backups (
      id INT AUTO_INCREMENT PRIMARY KEY,
      company_id INT NOT NULL,
      file_name VARCHAR(255) NOT NULL,
      original_name VARCHAR(255) NULL,
      file_size BIGINT NOT NULL DEFAULT 0,
      notes VARCHAR(255) NULL,
      created_by INT NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      restored_at DATETIME NULL,
      restored_by INT NULL,
      restore_count INT NOT NULL DEFAULT 0,
      INDEX idx_backups_company (company_id),
      INDEX idx_backups_created_at (created_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  ");

  $cols = table_columns($pdo, 'backups');
  if (!in_array('restored_at', $cols, true)) {
    $pdo->exec("ALTER TABLE backups ADD COLUMN restored_at DATETIME NULL AFTER created_at");
  }
  if (!in_array('restored_by', $cols, true)) {
    $pdo->exec("ALTER TABLE backups ADD COLUMN restored_by INT NULL AFTER restored_at");
  }
  if (!in_array('restore_count', $cols, true)) {
    $pdo->exec("ALTER TABLE backups ADD COLUMN restore_count INT NOT NULL DEFAULT 0 AFTER restored_by");
  }
}

function backup_storage_root(): string { return dirname(__DIR__) . '/storage/backups'; }
function company_backup_dir(int $companyId): string { return backup_storage_root() . '/company_' . $companyId; }
function project_root(): string { return dirname(__DIR__); }

function ensure_backup_dirs(int $companyId): string {
  $root = backup_storage_root();
  if (!is_dir($root)) mkdir($root, 0775, true);
  $companyDir = company_backup_dir($companyId);
  if (!is_dir($companyDir)) mkdir($companyDir, 0775, true);
  $htaccess = $root . '/.htaccess';
  if (!file_exists($htaccess)) @file_put_contents($htaccess, "Deny from all\n");
  $index = $root . '/index.php';
  if (!file_exists($index)) @file_put_contents($index, "<?php http_response_code(403); exit;");
  return $companyDir;
}

function table_columns(PDO $pdo, string $table): array {
  $cols = [];
  $st = $pdo->query("SHOW COLUMNS FROM `{$table}`");
  while ($row = $st->fetch(PDO::FETCH_ASSOC)) $cols[] = $row['Field'];
  return $cols;
}

function db_list_tables_local(PDO $pdo): array {
  $tables = [];
  foreach ($pdo->query("SHOW TABLES") as $row) $tables[] = array_values($row)[0];
  return $tables;
}

function table_exists(array $tables, string $table): bool {
  return in_array($table, $tables, true);
}

function normalize_rel_path(string $path): string {
  $path = str_replace('\\', '/', $path);
  $path = preg_replace('#/+#', '/', $path);
  $path = ltrim($path, '/');
  $path = str_replace(['../', '..\\'], '', $path);
  return $path;
}

function path_to_abs(string $relativePath): string {
  return project_root() . '/' . normalize_rel_path($relativePath);
}

function add_table_rows(PDO $pdo, array &$payload, string $table, string $whereSql, array $params = []): void {
  $st = $pdo->prepare("SELECT * FROM `{$table}` {$whereSql}");
  $st->execute($params);
  $rows = $st->fetchAll(PDO::FETCH_ASSOC);
  if ($rows) $payload['data'][$table] = $rows;
}

function fetch_single_company(PDO $pdo, int $companyId): ?array {
  $st = $pdo->prepare("SELECT * FROM `companies` WHERE id = ? LIMIT 1");
  $st->execute([$companyId]);
  $row = $st->fetch(PDO::FETCH_ASSOC);
  return $row ?: null;
}

function collect_company_file_candidates(array $companyRow, int $companyId): array {
  $files = [];
  if (!empty($companyRow['logo_path'])) {
    $files[] = normalize_rel_path((string)$companyRow['logo_path']);
  }

  $uploadsDir = project_root() . '/uploads/company';
  if (is_dir($uploadsDir)) {
    $patterns = [
      $uploadsDir . '/company_' . $companyId . '_*',
      $uploadsDir . '/company_' . $companyId . '.*',
    ];
    foreach ($patterns as $pattern) {
      foreach (glob($pattern) ?: [] as $fullPath) {
        $rel = ltrim(str_replace(project_root(), '', str_replace('\\', '/', $fullPath)), '/');
        $files[] = normalize_rel_path($rel);
      }
    }
  }

  return array_values(array_unique(array_filter($files)));
}

function collect_company_files_payload(array $companyRow, int $companyId): array {
  $result = [];
  foreach (collect_company_file_candidates($companyRow, $companyId) as $relPath) {
    $absPath = path_to_abs($relPath);
    if (!is_file($absPath)) continue;
    $content = file_get_contents($absPath);
    if ($content === false) continue;
    $result[] = [
      'path' => $relPath,
      'size' => filesize($absPath) ?: 0,
      'mime' => function_exists('mime_content_type') ? (@mime_content_type($absPath) ?: 'application/octet-stream') : 'application/octet-stream',
      'content_b64' => base64_encode($content),
    ];
  }
  return $result;
}

function build_company_backup_payload(PDO $pdo, int $companyId, int $userId): array {
  $tables = db_list_tables_local($pdo);
  $payload = [
    'meta' => [
      'app' => 'ERP_Lite',
      'type' => 'company_backup',
      'company_id' => $companyId,
      'created_by' => $userId,
      'created_at' => date('Y-m-d H:i:s'),
      'format_version' => 2,
    ],
    'data' => [],
    'files' => [],
  ];

  $companyRow = fetch_single_company($pdo, $companyId);
  if (!$companyRow) throw new RuntimeException('تعذر العثور على بيانات الشركة الحالية.');

  $payload['data']['companies'] = [$companyRow];
  $payload['files'] = collect_company_files_payload($companyRow, $companyId);

  if (table_exists($tables, 'users')) {
    add_table_rows($pdo, $payload, 'users', 'WHERE company_id = ?', [$companyId]);
  }

  foreach ($tables as $table) {
    if (in_array($table, ['backups', 'audit_logs', 'booking_items', 'invoice_lines', 'financial_event_lines', 'cash_tx_journal_map'], true)) continue;
    if (in_array($table, ['companies', 'users'], true)) continue;
    $columns = table_columns($pdo, $table);
    if (in_array('company_id', $columns, true)) {
      add_table_rows($pdo, $payload, $table, 'WHERE company_id = ?', [$companyId]);
    }
  }

  if (table_exists($tables, 'booking_items') && !empty($payload['data']['bookings'])) {
    $ids = array_values(array_filter(array_unique(array_map(fn($r) => (int)$r['id'], $payload['data']['bookings']))));
    if ($ids) {
      $ph = implode(',', array_fill(0, count($ids), '?'));
      add_table_rows($pdo, $payload, 'booking_items', "WHERE booking_id IN ({$ph})", $ids);
    }
  }

  if (table_exists($tables, 'invoice_lines') && !empty($payload['data']['invoices'])) {
    $ids = array_values(array_filter(array_unique(array_map(fn($r) => (int)$r['id'], $payload['data']['invoices']))));
    if ($ids) {
      $ph = implode(',', array_fill(0, count($ids), '?'));
      add_table_rows($pdo, $payload, 'invoice_lines', "WHERE invoice_id IN ({$ph})", $ids);
    }
  }

  if (table_exists($tables, 'financial_event_lines') && !empty($payload['data']['financial_events'])) {
    $ids = array_values(array_filter(array_unique(array_map(fn($r) => (int)$r['id'], $payload['data']['financial_events']))));
    if ($ids) {
      $ph = implode(',', array_fill(0, count($ids), '?'));
      add_table_rows($pdo, $payload, 'financial_event_lines', "WHERE event_id IN ({$ph})", $ids);
    }
  }

  if (table_exists($tables, 'cash_tx_journal_map') && !empty($payload['data']['cash_transactions'])) {
    $ids = array_values(array_filter(array_unique(array_map(fn($r) => (int)$r['id'], $payload['data']['cash_transactions']))));
    if ($ids) {
      $ph = implode(',', array_fill(0, count($ids), '?'));
      add_table_rows($pdo, $payload, 'cash_tx_journal_map', "WHERE cash_tx_id IN ({$ph})", $ids);
    }
  }

  return $payload;
}

function create_company_backup(PDO $pdo, int $companyId, int $userId): array {
  $dir = ensure_backup_dirs($companyId);
  $payload = build_company_backup_payload($pdo, $companyId, $userId);

  $stamp = date('Ymd_His');
  $random = bin2hex(random_bytes(4));
  $fileName = "company_backup_{$companyId}_{$stamp}_{$random}.json";
  $fullPath = $dir . '/' . $fileName;

  $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
  if ($json === false) throw new RuntimeException('تعذر إنشاء ملف النسخة الاحتياطية.');
  if (file_put_contents($fullPath, $json) === false) throw new RuntimeException('تعذر حفظ ملف النسخة الاحتياطية.');

  $size = filesize($fullPath) ?: 0;
  $st = $pdo->prepare("INSERT INTO backups (company_id, file_name, original_name, file_size, notes, created_by) VALUES (?, ?, ?, ?, ?, ?)");
  $st->execute([$companyId, $fileName, $fileName, $size, 'نسخة احتياطية شاملة لبيانات الشركة والملفات المرتبطة', $userId]);

  return [
    'backup_id' => (int)$pdo->lastInsertId(),
    'file_name' => $fileName,
    'file_size' => $size,
  ];
}

function delete_company_uploaded_files(int $companyId): void {
  $uploadsDir = project_root() . '/uploads/company';
  if (!is_dir($uploadsDir)) return;
  foreach ([$uploadsDir . '/company_' . $companyId . '_*', $uploadsDir . '/company_' . $companyId . '.*'] as $pattern) {
    foreach (glob($pattern) ?: [] as $file) {
      if (is_file($file)) @unlink($file);
    }
  }
}

function restore_company_files(array $files): void {
  foreach ($files as $file) {
    if (!is_array($file)) continue;
    $relPath = normalize_rel_path((string)($file['path'] ?? ''));
    $contentB64 = (string)($file['content_b64'] ?? '');
    if ($relPath === '' || $contentB64 === '') continue;
    $absPath = path_to_abs($relPath);
    $dir = dirname($absPath);
    if (!is_dir($dir)) mkdir($dir, 0775, true);
    $binary = base64_decode($contentB64, true);
    if ($binary === false) continue;
    file_put_contents($absPath, $binary);
  }
}

function delete_company_existing_data(PDO $pdo, int $companyId, array $tables): void {
  if (table_exists($tables, 'booking_items') && table_exists($tables, 'bookings')) {
    $pdo->prepare("DELETE bi FROM `booking_items` bi INNER JOIN `bookings` b ON b.id = bi.booking_id WHERE b.company_id = ?")->execute([$companyId]);
  }
  if (table_exists($tables, 'invoice_lines') && table_exists($tables, 'invoices')) {
    $pdo->prepare("DELETE il FROM `invoice_lines` il INNER JOIN `invoices` i ON i.id = il.invoice_id WHERE i.company_id = ?")->execute([$companyId]);
  }
  if (table_exists($tables, 'financial_event_lines') && table_exists($tables, 'financial_events')) {
    $pdo->prepare("DELETE fel FROM `financial_event_lines` fel INNER JOIN `financial_events` fe ON fe.id = fel.event_id WHERE fe.company_id = ?")->execute([$companyId]);
  }
  if (table_exists($tables, 'cash_tx_journal_map') && table_exists($tables, 'cash_transactions')) {
    $pdo->prepare("DELETE cjm FROM `cash_tx_journal_map` cjm INNER JOIN `cash_transactions` ct ON ct.id = cjm.cash_tx_id WHERE ct.company_id = ?")->execute([$companyId]);
  }

  foreach ($tables as $table) {
    if (in_array($table, ['backups', 'audit_logs', 'booking_items', 'invoice_lines', 'financial_event_lines', 'cash_tx_journal_map'], true)) continue;
    $columns = table_columns($pdo, $table);
    if ($table === 'users' && in_array('company_id', $columns, true)) {
      $pdo->prepare("DELETE FROM `users` WHERE company_id = ?")->execute([$companyId]);
      continue;
    }
    if ($table === 'companies' && in_array('id', $columns, true)) {
      $pdo->prepare("DELETE FROM `companies` WHERE id = ?")->execute([$companyId]);
      continue;
    }
    if (in_array('company_id', $columns, true)) {
      $pdo->prepare("DELETE FROM `{$table}` WHERE company_id = ?")->execute([$companyId]);
    }
  }
}

function insert_rows(PDO $pdo, string $table, array $rows): void {
  foreach ($rows as $row) {
    if (!is_array($row) || !$row) continue;
    $cols = array_keys($row);
    $placeholders = implode(',', array_fill(0, count($cols), '?'));
    $quotedCols = '`' . implode('`,`', $cols) . '`';
    $sql = "INSERT INTO `{$table}` ({$quotedCols}) VALUES ({$placeholders})";
    $st = $pdo->prepare($sql);
    $st->execute(array_values($row));
  }
}

function restore_company_backup(PDO $pdo, int $companyId, string $filePath): void {
  if (!is_file($filePath)) throw new RuntimeException('ملف النسخة الاحتياطية غير موجود.');

  $json = file_get_contents($filePath);
  if ($json === false || trim($json) === '') throw new RuntimeException('تعذر قراءة ملف النسخة الاحتياطية.');

  $payload = json_decode($json, true);
  if (!is_array($payload) || empty($payload['data']) || !is_array($payload['data'])) {
    throw new RuntimeException('ملف النسخة الاحتياطية غير صالح.');
  }

  $backupCompanyId = (int)($payload['meta']['company_id'] ?? 0);
  if ($backupCompanyId !== $companyId) throw new RuntimeException('هذه النسخة الاحتياطية تخص شركة أخرى ولا يمكن استعادتها هنا.');

  $tables = db_list_tables_local($pdo);
  $restoreOrder = ['companies','users','accounts','customers','suppliers','services','employees','attendance','missions','employee_advances','employee_advance_settlements','employee_advance_transfers','payroll_runs','payroll_lines','vehicles','vehicle_plate_history','vehicle_contracts','vehicle_operation_contracts','vehicle_daily_logs','vehicle_maintenance_schedules','vehicle_sales','hotel_hotels','hotel_rooms','hotel_bookings','hotel_receipts','bookings','booking_items','invoices','invoice_lines','payments','cash_transactions','journal_entries','journal_lines','financial_events','financial_event_lines','cash_tx_journal_map'];

  $pdo->exec("SET FOREIGN_KEY_CHECKS=0");
  $pdo->beginTransaction();
  try {
    delete_company_existing_data($pdo, $companyId, $tables);
    delete_company_uploaded_files($companyId);
    foreach ($restoreOrder as $table) {
      if (!isset($payload['data'][$table]) || !table_exists($tables, $table)) continue;
      insert_rows($pdo, $table, $payload['data'][$table]);
    }
    foreach ($payload['data'] as $table => $rows) {
      if (in_array($table, $restoreOrder, true)) continue;
      if (!table_exists($tables, $table)) continue;
      insert_rows($pdo, $table, $rows);
    }
    if (!empty($payload['files']) && is_array($payload['files'])) {
      restore_company_files($payload['files']);
    }
    $pdo->commit();
  } catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    throw $e;
  } finally {
    $pdo->exec("SET FOREIGN_KEY_CHECKS=1");
  }
}

function get_company_backup_row(PDO $pdo, int $backupId, int $companyId): ?array {
  $st = $pdo->prepare("SELECT * FROM backups WHERE id = ? AND company_id = ? LIMIT 1");
  $st->execute([$backupId, $companyId]);
  $row = $st->fetch(PDO::FETCH_ASSOC);
  return $row ?: null;
}

function mark_backup_as_restored(PDO $pdo, int $backupId, int $companyId, int $userId): void {
  $st = $pdo->prepare("UPDATE backups SET restored_at = NOW(), restored_by = ?, restore_count = COALESCE(restore_count, 0) + 1 WHERE id = ? AND company_id = ?");
  $st->execute([$userId, $backupId, $companyId]);
}

function format_bytes_ar(int $bytes): string {
  if ($bytes >= 1024 * 1024 * 1024) return number_format($bytes / (1024 * 1024 * 1024), 2) . ' GB';
  if ($bytes >= 1024 * 1024) return number_format($bytes / (1024 * 1024), 2) . ' MB';
  if ($bytes >= 1024) return number_format($bytes / 1024, 2) . ' KB';
  return $bytes . ' B';
}

ensure_backups_table($pdo);
ensure_audit_tables($pdo);
ensure_backup_dirs($cid);

if (isset($_GET['download_id'])) {
  $backupId = (int)$_GET['download_id'];
  $row = get_company_backup_row($pdo, $backupId, $cid);
  if (!$row) { http_response_code(404); exit('Backup not found'); }
  $filePath = company_backup_dir($cid) . '/' . $row['file_name'];
  if (!is_file($filePath)) { http_response_code(404); exit('File not found'); }

  audit_log($pdo, [
    'company_id' => $cid,
    'user_id' => $uid,
    'module' => 'backup',
    'action' => 'DOWNLOAD',
    'entity_type' => 'backup',
    'entity_id' => (string)$backupId,
    'description' => 'تحميل نسخة احتياطية',
  ]);

  header('Content-Description: File Transfer');
  header('Content-Type: application/json; charset=utf-8');
  header('Content-Disposition: attachment; filename="' . basename($row['original_name'] ?: $row['file_name']) . '"');
  header('Content-Length: ' . filesize($filePath));
  header('Cache-Control: no-store, no-cache, must-revalidate');
  header('Pragma: no-cache');
  readfile($filePath);
  exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = trim($_POST['action'] ?? '');
  try {
    if ($action === 'create_backup') {
      $created = create_company_backup($pdo, $cid, $uid);
      audit_log($pdo, [
        'company_id' => $cid,
        'user_id' => $uid,
        'module' => 'backup',
        'action' => 'CREATE',
        'entity_type' => 'backup',
        'entity_id' => (string)$created['backup_id'],
        'description' => 'إنشاء نسخة احتياطية داخلية جديدة',
      ]);
      $ok = 'تم إنشاء النسخة الاحتياطية الشاملة وحفظها داخل النظام بنجاح.';
    } elseif ($action === 'restore_backup') {
      $backupId = (int)($_POST['backup_id'] ?? 0);
      $row = get_company_backup_row($pdo, $backupId, $cid);
      if (!$row) throw new RuntimeException('النسخة الاحتياطية غير موجودة.');
      $filePath = company_backup_dir($cid) . '/' . $row['file_name'];
      restore_company_backup($pdo, $cid, $filePath);
      mark_backup_as_restored($pdo, $backupId, $cid, $uid);
      audit_log($pdo, [
        'company_id' => $cid,
        'user_id' => $uid,
        'module' => 'backup',
        'action' => 'RESTORE',
        'entity_type' => 'backup',
        'entity_id' => (string)$backupId,
        'description' => 'استعادة نسخة احتياطية للشركة',
      ]);
      $ok = 'تمت استعادة نسخة الشركة بنجاح.';
    } elseif ($action === 'delete_backup') {
      $backupId = (int)($_POST['backup_id'] ?? 0);
      $row = get_company_backup_row($pdo, $backupId, $cid);
      if (!$row) throw new RuntimeException('النسخة الاحتياطية غير موجودة.');
      $filePath = company_backup_dir($cid) . '/' . $row['file_name'];
      if (is_file($filePath)) @unlink($filePath);
      $st = $pdo->prepare("DELETE FROM backups WHERE id = ? AND company_id = ?");
      $st->execute([$backupId, $cid]);
      audit_log($pdo, [
        'company_id' => $cid,
        'user_id' => $uid,
        'module' => 'backup',
        'action' => 'DELETE',
        'entity_type' => 'backup',
        'entity_id' => (string)$backupId,
        'description' => 'حذف نسخة احتياطية',
      ]);
      $ok = 'تم حذف النسخة الاحتياطية بنجاح.';
    }
  } catch (Throwable $e) {
    $err = $e->getMessage();
  }
}

$st = $pdo->prepare("SELECT b.*, uc.name AS created_by_name, ur.name AS restored_by_name FROM backups b LEFT JOIN users uc ON uc.id = b.created_by LEFT JOIN users ur ON ur.id = b.restored_by WHERE b.company_id = ? ORDER BY b.id DESC");
$st->execute([$cid]);
$backups = $st->fetchAll(PDO::FETCH_ASSOC);

render_layout('إدارة قاعدة البيانات', "الرئيسية <span class='mx-1'>/</span> الإعدادات <span class='mx-1'>/</span> إدارة قاعدة البيانات", function() use ($backups, $err, $ok, $cid) {
?>
<div class="row g-3 mt-3">
  <div class="col-12">
    <?php if ($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>
    <?php if ($ok): ?><div class="alert alert-success"><?= h($ok) ?></div><?php endif; ?>
  </div>
  <div class="col-12 col-xl-4">
    <div class="card cardx p-3 p-md-4 h-100">
      <div class="d-flex align-items-center justify-content-between mb-3">
        <div>
          <div class="fw-bold fs-5">نسخة احتياطية جديدة</div>
          <div class="small text-secondary mt-1">سيتم حفظ نسخة شاملة لبيانات الشركة الحالية فقط مع الملفات المرتبطة بها.</div>
        </div>
        <div class="fs-2 text-dark"><i class="bi bi-database-add"></i></div>
      </div>
      <div class="border rounded-4 p-3 bg-light small mb-3">
        <div><strong>الشركة الحالية:</strong> #<?= (int)$cid ?></div>
        <div class="mt-1 text-secondary">لن يتم تضمين بيانات أي شركة أخرى.</div>
      </div>
      <form method="post">
        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="create_backup">
        <button class="btn btn-dark w-100"><i class="bi bi-plus-circle"></i> إنشاء نسخة احتياطية</button>
      </form>
    </div>
  </div>
  <div class="col-12 col-xl-8">
    <div class="card cardx p-3 p-md-4 h-100">
      <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
        <div>
          <div class="fw-bold fs-5">النسخ الاحتياطية المحفوظة</div>
          <div class="small text-secondary mt-1">يمكنك تحميل النسخة أو استعادتها أو حذفها داخل حدود الشركة الحالية فقط.</div>
        </div>
        <span class="badge text-bg-dark rounded-pill">العدد: <?= count($backups) ?></span>
      </div>
      <?php if (!$backups): ?>
        <div class="alert alert-light border mb-0">لا توجد نسخ احتياطية محفوظة لهذه الشركة حتى الآن.</div>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table align-middle table-bordered table-hover mb-0">
            <thead class="table-light">
              <tr>
                <th style="width:70px">#</th>
                <th>اسم الملف</th>
                <th style="width:120px">الحجم</th>
                <th style="width:170px">تاريخ الإنشاء</th>
                <th style="width:130px">أنشأها</th>
                <th style="width:120px">حالة الاستعادة</th>
                <th style="width:170px">آخر استعادة</th>
                <th style="width:120px">بواسطة</th>
                <th style="width:90px">المرات</th>
                <th style="width:290px">الإجراءات</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($backups as $row): ?>
                <tr>
                  <td><?= (int)$row['id'] ?></td>
                  <td>
                    <div class="fw-semibold"><?= h($row['original_name'] ?: $row['file_name']) ?></div>
                    <div class="small text-secondary"><?= h($row['notes'] ?? '') ?></div>
                  </td>
                  <td><?= h(format_bytes_ar((int)$row['file_size'])) ?></td>
                  <td><?= h($row['created_at']) ?></td>
                  <td><?= h($row['created_by_name'] ?: ('مستخدم #' . (int)$row['created_by'])) ?></td>
                  <td><?php if (!empty($row['restored_at'])): ?><span class="badge text-bg-success">تمت</span><?php else: ?><span class="badge text-bg-secondary">لم تتم</span><?php endif; ?></td>
                  <td><?= h($row['restored_at'] ?: '-') ?></td>
                  <td><?= h($row['restored_by_name'] ?: (!empty($row['restored_by']) ? ('مستخدم #' . (int)$row['restored_by']) : '-')) ?></td>
                  <td><?= (int)($row['restore_count'] ?? 0) ?></td>
                  <td>
                    <div class="d-flex flex-wrap gap-2">
                      <a class="btn btn-sm btn-outline-primary" href="<?= url('/settings/database.php?download_id=' . (int)$row['id']) ?>"><i class="bi bi-download"></i> تحميل</a>
                      <form method="post" onsubmit="return confirm('سيتم استعادة بيانات هذه الشركة من النسخة المحددة. هل أنت متأكد؟');">
                        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                        <input type="hidden" name="action" value="restore_backup">
                        <input type="hidden" name="backup_id" value="<?= (int)$row['id'] ?>">
                        <button class="btn btn-sm btn-outline-success"><i class="bi bi-arrow-counterclockwise"></i> استعادة</button>
                      </form>
                      <form method="post" onsubmit="return confirm('سيتم حذف ملف النسخة الاحتياطية نهائيًا. هل أنت متأكد؟');">
                        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                        <input type="hidden" name="action" value="delete_backup">
                        <input type="hidden" name="backup_id" value="<?= (int)$row['id'] ?>">
                        <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i> حذف</button>
                      </form>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
  <div class="col-12">
    <div class="card cardx p-3 p-md-4">
      <div class="fw-bold mb-2">ملاحظات مهمة</div>
      <ul class="mb-0">
        <li>النسخة الاحتياطية تشمل بيانات <strong>الشركة الحالية فقط</strong>.</li>
        <li>تشمل الجداول الرئيسية والجداول الفرعية المرتبطة بها.</li>
        <li>تشمل ملفات الشركة المرتبطة مثل اللوجو داخل <code>uploads/company</code>.</li>
        <li>النسخ يتم حفظها داخل المسار: <code>storage/backups/company_<?= (int)$cid ?></code></li>
        <li>الاستعادة لن تؤثر على بيانات أي شركة أخرى داخل النظام.</li>
      </ul>
    </div>
  </div>
</div>
<?php });
