<?php
$page_title = 'تحديث الإصدار';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/update_manager.php';

$ROOT = realpath(__DIR__ . '/..') ?: dirname(__DIR__);
$ADMIN = __DIR__;
$UPDATES = upd_path_join($ADMIN, 'updates');
$BACKUPS = upd_path_join($UPDATES, 'backups');
$TMP = upd_path_join($UPDATES, 'tmp');
$PACKAGES = upd_path_join($UPDATES, 'packages');
$LOCK_FILE = upd_path_join($UPDATES, 'update.lock');

foreach ([$UPDATES, $BACKUPS, $TMP, $PACKAGES] as $dir) {
    upd_ensure_dir($dir);
}

$currentInfo = upd_read_version_info($ADMIN);
$currentVersion = (string)($currentInfo['version'] ?? '0.0.0');
$currentBuild = (string)($currentInfo['build'] ?? '');
$currentName = (string)($currentInfo['name'] ?? '');
$currentUser = $_SESSION['admin_username'] ?? $_SESSION['admin_user'] ?? 'admin';

if (empty($_SESSION['update_csrf'])) {
    $_SESSION['update_csrf'] = bin2hex(random_bytes(16));
}
$csrf = $_SESSION['update_csrf'];

$errors = [];
$success = [];
$info = [];
$packagePreview = null;
$installReport = null;

function upd_has_active_lock(string $lockFile): bool {
    if (!is_file($lockFile)) return false;
    $data = json_decode((string)@file_get_contents($lockFile), true);
    if (!is_array($data)) return false;
    $started = strtotime((string)($data['started_at'] ?? '')) ?: 0;
    if ($started > 0 && $started < time() - 3600) {
        @unlink($lockFile);
        return false;
    }
    return true;
}

function upd_create_lock(string $lockFile, string $user): void {
    $payload = [
        'user' => $user,
        'started_at' => date('Y-m-d H:i:s'),
        'pid' => getmypid(),
    ];
    @file_put_contents($lockFile, json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
}

function upd_release_lock(string $lockFile): void {
    @unlink($lockFile);
}

function upd_force_release_stale_lock(string $lockFile, int $maxAgeSeconds = 900): bool {
    if (!is_file($lockFile)) return true;
    $data = json_decode((string)@file_get_contents($lockFile), true);
    $started = is_array($data) ? (strtotime((string)($data['started_at'] ?? '')) ?: 0) : 0;
    if ($started > 0 && $started < time() - $maxAgeSeconds) {
        @unlink($lockFile);
        return true;
    }
    return false;
}

$__updLockHeld = false;
register_shutdown_function(function () use ($LOCK_FILE, &$__updLockHeld) {
    $last = error_get_last();
    if ($__updLockHeld || ($last && in_array((int)($last['type'] ?? 0), [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true))) {
        @unlink($LOCK_FILE);
    }
});

function upd_is_post(): bool {
    return ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST';
}

function upd_verify_csrf(string $token): bool {
    return hash_equals((string)($_SESSION['update_csrf'] ?? ''), $token);
}

function upd_list_backups_ui(string $backupsDir): array {
    $rows = [];
    if (!is_dir($backupsDir)) return $rows;
    foreach (scandir($backupsDir) ?: [] as $name) {
        if ($name === '.' || $name === '..') continue;
        $full = upd_path_join($backupsDir, $name);
        if (!is_dir($full)) continue;
        $metaFile = upd_path_join($full, 'backup_meta.json');
        $meta = [];
        if (is_file($metaFile)) {
            $meta = json_decode((string)@file_get_contents($metaFile), true) ?: [];
        }
        $rows[] = [
            'name' => $name,
            'path' => $full,
            'time' => $meta['time'] ?? date('Y-m-d H:i:s', filemtime($full) ?: time()),
            'from_version' => $meta['from_version'] ?? '',
            'package_version' => $meta['package_version'] ?? '',
            'package_name' => $meta['package_name'] ?? '',
            'db_backup' => is_file(upd_path_join($full, 'database_backup.sql')),
        ];
    }
    usort($rows, static function($a, $b) {
        return strcmp($b['name'], $a['name']);
    });
    return $rows;
}

function upd_save_backup_meta(string $backupDir, array $meta): void {
    @file_put_contents(upd_path_join($backupDir, 'backup_meta.json'), json_encode($meta, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT));
}

function upd_preflight_summary(string $adminDir, string $updatesDir, string $backupsDir, string $tmpDir): array {
    $checks = [];
    $writableIssues = upd_collect_writable_issues([
        'مجلد admin' => $adminDir,
        'مجلد updates' => $updatesDir,
        'مجلد backups' => $backupsDir,
        'مجلد tmp' => $tmpDir,
        'ملف version.php' => upd_path_join($adminDir, 'version.php'),
    ]);
    $checks[] = ['label' => 'ZipArchive', 'ok' => class_exists('ZipArchive'), 'note' => class_exists('ZipArchive') ? 'متاح' : 'غير متاح'];
    $checks[] = ['label' => 'صلاحيات الكتابة', 'ok' => empty($writableIssues), 'note' => empty($writableIssues) ? 'جاهز' : implode(' | ', $writableIssues)];
    $db = upd_connect_db();
    $checks[] = ['label' => 'قاعدة البيانات', 'ok' => $db instanceof mysqli && !$db->connect_errno, 'note' => ($db instanceof mysqli && !$db->connect_errno) ? 'الاتصال متاح' : 'غير متاحة أو غير مهيأة'];
    return $checks;
}

if (upd_is_post()) {
    $action = (string)($_POST['action'] ?? '');
    $postedToken = (string)($_POST['csrf'] ?? '');
    if (!upd_verify_csrf($postedToken)) {
        $errors[] = 'انتهت الجلسة أو رمز الحماية غير صالح.';
    } elseif (in_array($action, ['inspect', 'install', 'restore'], true) && upd_has_active_lock($LOCK_FILE) && $action !== 'restore') {
        if (!upd_force_release_stale_lock($LOCK_FILE, 900) && upd_has_active_lock($LOCK_FILE)) {
            $errors[] = 'يوجد تحديث جارٍ حاليًا أو لم يتم تحرير القفل بعد.';
        }
    } elseif ($action === 'inspect' || $action === 'install') {
        if (empty($_FILES['package_zip']['tmp_name']) || !is_uploaded_file($_FILES['package_zip']['tmp_name'])) {
            $errors[] = 'اختر ملف ZIP أولًا.';
        } else {
            $name = (string)($_FILES['package_zip']['name'] ?? 'update.zip');
            if (!preg_match('/\.zip$/i', $name)) {
                $errors[] = 'الملف يجب أن يكون بصيغة ZIP.';
            } else {
                $incoming = upd_path_join($PACKAGES, date('Ymd_His') . '_' . preg_replace('/[^A-Za-z0-9._-]/', '_', basename($name)));
                if (!@move_uploaded_file($_FILES['package_zip']['tmp_name'], $incoming)) {
                    $errors[] = 'فشل حفظ ملف الحزمة على السيرفر.';
                } else {
                    try {
                        [$manifest, $sourceRoot] = upd_read_package_info($incoming, $TMP, $ADMIN);
                        $packagePreview = [
                            'file_name' => basename($incoming),
                            'saved_path' => $incoming,
                            'manifest' => $manifest,
                            'source_root' => $sourceRoot,
                            'files_count' => count((array)($manifest['files'] ?? [])),
                        ];

                        $info[] = 'تم فحص الحزمة بنجاح.';
                        if ($action === 'install') {
                            upd_create_lock($LOCK_FILE, $currentUser);
                            $__updLockHeld = true;
                            $backupDir = upd_backup_directory($ADMIN, $BACKUPS);
                            $dbBackup = upd_backup_db_if_possible($backupDir);
                            upd_save_backup_meta($backupDir, [
                                'time' => date('Y-m-d H:i:s'),
                                'user' => $currentUser,
                                'from_version' => $currentVersion,
                                'package_version' => $manifest['version'],
                                'package_name' => $manifest['name'],
                                'package_file' => basename($incoming),
                                'db_backup' => $dbBackup,
                            ]);

                            if (($manifest['target'] ?? 'admin') !== 'admin') {
                                throw new RuntimeException('هذه الصفحة تقبل فقط حزم target=admin.');
                            }
                            if (!empty($manifest['min_supported_version']) && upd_compare_versions($currentVersion, (string)$manifest['min_supported_version']) < 0) {
                                throw new RuntimeException('الحزمة تتطلب حدًا أدنى من الإصدار: ' . $manifest['min_supported_version']);
                            }
                            if ($manifest['version'] !== '' && upd_compare_versions($manifest['version'], $currentVersion) < 0) {
                                throw new RuntimeException('إصدار الحزمة أقدم من الإصدار الحالي.');
                            }

                            $appliedFiles = [];
                            try {
                                upd_apply_package($sourceRoot, $ADMIN, $manifest, $backupDir, $appliedFiles);

                                $db = upd_connect_db();
                                $migrationsRun = [];
                                if (!empty($manifest['migrations'])) {
                                    if (!($db instanceof mysqli) || $db->connect_errno) {
                                        throw new RuntimeException('الحزمة تحتوي migrations لكن اتصال قاعدة البيانات غير متاح.');
                                    }
                                    foreach ((array)$manifest['migrations'] as $migrationRel) {
                                        $migrationRel = ltrim(str_replace('\\', '/', trim((string)$migrationRel)), '/');
                                        if (!upd_validate_rel_path($migrationRel)) {
                                            throw new RuntimeException('مسار migration غير آمن: ' . $migrationRel);
                                        }
                                        $migrationFile = upd_path_join($sourceRoot, $migrationRel);
                                        if (!is_file($migrationFile)) {
                                            throw new RuntimeException('ملف migration غير موجود: ' . $migrationRel);
                                        }
                                        upd_run_sql_file($db, $migrationFile);
                                        $migrationsRun[] = $migrationRel;
                                    }
                                }

                                $versionWrite = upd_write_version_info($ADMIN, [
                                    'version' => $manifest['version'] ?: $currentVersion,
                                    'build' => date('Y-m-d H:i:s'),
                                    'name' => $manifest['name'] ?: ($currentName ?: 'Updated Release'),
                                ]);
                                if (!$versionWrite) {
                                    throw new RuntimeException('فشل تحديث ملف version.php بعد التثبيت.');
                                }

                                $installReport = [
                                    'backup' => basename($backupDir),
                                    'db_backup' => $dbBackup,
                                    'files' => $appliedFiles,
                                    'migrations' => $migrationsRun,
                                ];
                                $success[] = 'تم تثبيت التحديث بنجاح.';
                                upd_log_append($UPDATES, [
                                    'type' => 'install',
                                    'by' => $currentUser,
                                    'from_version' => $currentVersion,
                                    'to_version' => $manifest['version'] ?: $currentVersion,
                                    'package_name' => $manifest['name'],
                                    'package_file' => basename($incoming),
                                    'backup' => basename($backupDir),
                                    'files_count' => count($appliedFiles),
                                    'migrations_count' => count($migrationsRun),
                                    'db_backup' => $dbBackup['ok'] ?? false,
                                ]);
                                $currentInfo = upd_read_version_info($ADMIN);
                                $currentVersion = (string)($currentInfo['version'] ?? $currentVersion);
                                $currentBuild = (string)($currentInfo['build'] ?? $currentBuild);
                                $currentName = (string)($currentInfo['name'] ?? $currentName);
                            } catch (Throwable $inner) {
                                upd_rcopy(upd_path_join($backupDir, 'admin_snapshot'), $ADMIN);
                                $errors[] = 'فشل التثبيت وتمت محاولة الاسترجاع تلقائيًا: ' . $inner->getMessage();
                                upd_log_append($UPDATES, [
                                    'type' => 'install_failed',
                                    'by' => $currentUser,
                                    'from_version' => $currentVersion,
                                    'to_version' => $manifest['version'] ?: '',
                                    'package_name' => $manifest['name'],
                                    'package_file' => basename($incoming),
                                    'backup' => basename($backupDir),
                                    'error' => $inner->getMessage(),
                                ]);
                            }
                            upd_release_lock($LOCK_FILE);
                        }
                    } catch (Throwable $e) {
                        $errors[] = $e->getMessage();
                        upd_release_lock($LOCK_FILE);
                        $__updLockHeld = false;
                    } finally {
                        upd_rrmdir($TMP);
                    }
                }
            }
        }
    } elseif ($action === 'restore') {
        $backup = preg_replace('/[^A-Za-z0-9_.:-]/', '', (string)($_POST['backup_name'] ?? ''));
        $restoreDb = !empty($_POST['restore_db']);
        if ($backup === '') {
            $errors[] = 'اختر نسخة احتياطية للاسترجاع.';
        } else {
            $src = upd_path_join($BACKUPS, $backup);
            if (!is_dir($src)) {
                $errors[] = 'النسخة الاحتياطية المحددة غير موجودة.';
            } else {
                try {
                    $preRestore = upd_backup_directory($ADMIN, $BACKUPS);
                    upd_save_backup_meta($preRestore, [
                        'time' => date('Y-m-d H:i:s'),
                        'user' => $currentUser,
                        'from_version' => $currentVersion,
                        'package_version' => 'pre-restore',
                        'package_name' => 'Automatic pre-restore snapshot',
                    ]);
                    upd_rcopy_filtered(upd_path_join($src, 'admin_snapshot'), $ADMIN, ['updates']);
                    if ($restoreDb) {
                        $dbFile = upd_path_join($src, 'database_backup.sql');
                        if (is_file($dbFile)) {
                            $db = upd_connect_db();
                            if (!($db instanceof mysqli) || $db->connect_errno) {
                                throw new RuntimeException('تعذر الاتصال بقاعدة البيانات لتنفيذ استرجاع SQL.');
                            }
                            upd_run_sql_file($db, $dbFile);
                        } else {
                            $info[] = 'هذه النسخة لا تحتوي نسخة SQL لقاعدة البيانات.';
                        }
                    }
                    $success[] = 'تم استرجاع النسخة الاحتياطية بنجاح.';
                    upd_log_append($UPDATES, [
                        'type' => 'restore',
                        'by' => $currentUser,
                        'from_version' => $currentVersion,
                        'to_version' => upd_read_version_info($ADMIN)['version'] ?? $currentVersion,
                        'backup' => $backup,
                        'restore_db' => $restoreDb,
                    ]);
                    $currentInfo = upd_read_version_info($ADMIN);
                    $currentVersion = (string)($currentInfo['version'] ?? $currentVersion);
                    $currentBuild = (string)($currentInfo['build'] ?? $currentBuild);
                    $currentName = (string)($currentInfo['name'] ?? $currentName);
                } catch (Throwable $e) {
                    $errors[] = 'فشل الاسترجاع: ' . $e->getMessage();
                }
            }
        }
    }
}

$checks = upd_preflight_summary($ADMIN, $UPDATES, $BACKUPS, $TMP);
$backups = upd_list_backups_ui($BACKUPS);
$logRows = upd_log_read($UPDATES, 60);
$lockActive = upd_has_active_lock($LOCK_FILE);
$lockInfo = $lockActive ? json_decode((string)@file_get_contents($LOCK_FILE), true) : null;

$toastItems = [];
foreach ($errors as $msg) { $toastItems[] = ['type' => 'error', 'message' => (string)$msg]; }
foreach ($success as $msg) { $toastItems[] = ['type' => 'success', 'message' => (string)$msg]; }
foreach ($info as $msg) { $toastItems[] = ['type' => 'info', 'message' => (string)$msg]; }

$UA_FORCE_DESIGN_V2 = true;
$uaAndroidUpdateVersion = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidUpdateVersion) $UA_PAGE_CSS = ['assets/css/android_update_version.css'];
require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
if ($uaAndroidUpdateVersion) { require __DIR__ . '/android_update_version.php'; require_once __DIR__ . '/footer.php'; return; }
?>
<div class="content-wrapper ua-extracted-page">
<section class="content-header">
  <div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
      <div>
        <h1 class="ua-u-m0">مركز تحديث النظام</h1>
              </div>
      <div class="text-left ua-u-minw-260">
        <div><b>الإصدار الحالي:</b> <?= h($currentVersion) ?></div>
        <div><b>البناء:</b> <?= h($currentBuild !== '' ? $currentBuild : '—') ?></div>
        <div><b>الاسم:</b> <?= h($currentName !== '' ? $currentName : '—') ?></div>
      </div>
    </div>
  </div>
</section>

<section class="content">
<div class="container-fluid">

<div id="upToastWrap" class="ua-feedback-stack up-toast-wrap" aria-live="polite" aria-atomic="true"></div>
<div id="upConfirmOverlay" class="up-confirm-overlay" aria-hidden="true">
  <div class="up-confirm-box">
    <div class="up-confirm-title" id="upConfirmTitle">تأكيد العملية</div>
    <div class="up-confirm-text" id="upConfirmText">سيتم تنفيذ العملية المطلوبة. هل تريد المتابعة؟</div>
    <div class="up-confirm-actions">
      <button type="button" class="btn btn-light" id="upConfirmCancel">إلغاء</button>
      <button type="button" class="btn btn-primary" id="upConfirmOk">متابعة</button>
    </div>
  </div>
</div>


<div class="up-grid mb-3">
  <div class="up-stat"><div class="small text-muted">الحالة</div><div><span class="up-badge <?= $lockActive ? 'up-bad' : 'up-ok' ?>"><?= $lockActive ? 'قيد التنفيذ / مقفول' : 'جاهز للتحديث' ?></span></div></div>
  <div class="up-stat"><div class="small text-muted">عدد النسخ الاحتياطية</div><div class="h4 ua-u-mt-6"><?= count($backups) ?></div></div>
  <div class="up-stat"><div class="small text-muted">آخر مستخدم</div><div class="h5 ua-u-mt-6"><?= h($currentUser) ?></div></div>
  <div class="up-stat"><div class="small text-muted">حالة القفل</div><div class="small"><?= $lockActive ? h(($lockInfo['user'] ?? 'unknown') . ' @ ' . ($lockInfo['started_at'] ?? '')) : 'لا يوجد قفل نشط' ?></div></div>
</div>

<div class="up-tabbar" role="tablist" aria-label="قوائم صفحة التحديث">
  <button type="button" class="up-tabbtn active" data-target="upTabMain">التحديث</button>
  <button type="button" class="up-tabbtn" data-target="upTabBackups">النسخ الاحتياطية</button>
  <button type="button" class="up-tabbtn" data-target="upTabLogs">سجل العمليات</button>
</div>

<div id="upTabMain" class="up-tabpanel active">
  <div class="row">
    <div class="col-lg-7">
      <div class="card up-card">
        <div class="card-header"><h3 class="card-title">تحديث من ملف ZIP</h3></div>
        <div class="card-body">
          <form method="post" enctype="multipart/form-data" class="mb-3">
            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
            <div class="form-group">
              <label>ملف التحديث</label>
              <input type="file" name="package_zip" class="form-control" accept=".zip" required>
            </div>
            <div class="d-flex flex-wrap ua-u-gap-10">
              <button class="btn btn-secondary" name="action" value="inspect" <?= $lockActive ? 'disabled' : '' ?>>فحص الحزمة</button>
              <button type="button" class="btn btn-primary" name="action" value="install" <?= $lockActive ? 'disabled' : '' ?> data-confirm-title="تأكيد تثبيت التحديث" data-confirm-text="سيتم أخذ نسخة احتياطية قبل تثبيت الحزمة، ثم يبدأ التثبيت مباشرة. هل تريد المتابعة؟" onclick="return updOpenConfirm(this.form, this);">تثبيت التحديث</button>
            </div>
          </form>
        </div>
      </div>

      <?php if ($packagePreview): $m = $packagePreview['manifest']; ?>
      <div class="card up-card">
        <div class="card-header"><h3 class="card-title">تفاصيل الحزمة المفحوصة</h3></div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-6 mb-2"><b>اسم الحزمة:</b> <?= h($m['name']) ?></div>
            <div class="col-md-6 mb-2"><b>الإصدار:</b> <?= h($m['version']) ?></div>
            <div class="col-md-6 mb-2"><b>الهدف:</b> <?= h($m['target']) ?></div>
            <div class="col-md-6 mb-2"><b>المجلد الجذري:</b> <span class="up-mono"><?= h($m['root_dir']) ?></span></div>
            <div class="col-md-6 mb-2"><b>عدد الملفات:</b> <?= (int)$packagePreview['files_count'] ?></div>
            <div class="col-md-6 mb-2"><b>الحد الأدنى المدعوم:</b> <?= h($m['min_supported_version'] !== '' ? $m['min_supported_version'] : 'غير محدد') ?></div>
          </div>
          <div class="mb-2"><b>الوصف:</b> <?= h($m['description'] !== '' ? $m['description'] : '—') ?></div>
          <div class="mb-2"><b>ملفات محمية:</b> <?= h(implode(' , ', $m['protected_files']) ?: 'لا يوجد') ?></div>
          <details>
            <summary>عرض الملفات</summary>
            <div class="up-pre up-mono mt-2"><?= h(implode(PHP_EOL, (array)$m['files'])) ?></div>
          </details>
          <?php if (!empty($m['migrations'])): ?>
          <details class="mt-2">
            <summary>عرض migrations</summary>
            <div class="up-pre up-mono mt-2"><?= h(implode(PHP_EOL, (array)$m['migrations'])) ?></div>
          </details>
          <?php endif; ?>
        </div>
      </div>
      <?php endif; ?>

      <?php if ($installReport): ?>
      <div class="card up-card">
        <div class="card-header"><h3 class="card-title">تقرير التثبيت الأخير</h3></div>
        <div class="card-body">
          <div class="mb-2"><b>اسم النسخة الاحتياطية:</b> <span class="up-mono"><?= h($installReport['backup']) ?></span></div>
          <div class="mb-2"><b>نسخة قاعدة البيانات:</b> <?= !empty($installReport['db_backup']['ok']) ? 'تم إنشاؤها' : h($installReport['db_backup']['message'] ?? 'غير متاحة') ?></div>
          <div class="mb-2"><b>عدد الملفات المطبقة:</b> <?= count((array)$installReport['files']) ?></div>
          <div class="mb-2"><b>عدد migrations المنفذة:</b> <?= count((array)$installReport['migrations']) ?></div>
        </div>
      </div>
      <?php endif; ?>
    </div>

    <div class="col-lg-5">
      <div class="card up-card mb-3">
        <div class="card-header"><h3 class="card-title">فحص الجاهزية</h3></div>
        <div class="card-body p-0">
          <table class="table table-sm up-table ua-u-m0">
            <thead><tr><th>العنصر</th><th>الحالة</th><th>ملاحظة</th></tr></thead>
            <tbody>
            <?php foreach ($checks as $check): ?>
              <tr>
                <td><?= h($check['label']) ?></td>
                <td><span class="up-badge <?= $check['ok'] ? 'up-ok' : 'up-bad' ?>"><?= $check['ok'] ? 'سليم' : 'يحتاج معالجة' ?></span></td>
                <td><?= h($check['note']) ?></td>
              </tr>
            <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>

      <div class="card up-card mb-3">
        <div class="card-header"><h3 class="card-title">استرجاع نسخة احتياطية</h3></div>
        <div class="card-body">
          <?php if (empty($backups)): ?>
            <div class="text-muted">لا توجد نسخ احتياطية حتى الآن.</div>
          <?php else: ?>
          <form method="post">
            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">
            <input type="hidden" name="action" value="restore">
            <div class="form-group">
              <label>اختر النسخة</label>
              <select class="form-control" name="backup_name" required>
                <option value="">— اختر —</option>
                <?php foreach ($backups as $row): ?>
                  <option value="<?= h($row['name']) ?>"><?= h($row['name']) ?> | <?= h($row['package_name'] ?: $row['package_version']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-check mb-3">
              <input class="form-check-input" type="checkbox" value="1" id="restore_db" name="restore_db">
              <label class="form-check-label" for="restore_db">استرجاع قاعدة البيانات أيضًا إذا كانت النسخة تحتوي SQL</label>
            </div>
            <button type="button" class="btn btn-warning" name="action" value="restore" data-confirm-title="تأكيد استرجاع النسخة" data-confirm-text="سيتم استبدال ملفات النظام بالنسخة الاحتياطية المحددة، وقد يتم استرجاع قاعدة البيانات أيضًا إذا فعّلت الخيار. هل تريد المتابعة؟" onclick="return updOpenConfirm(this.form, this);">استرجاع النسخة</button>
          </form>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</div>

<div id="upTabBackups" class="up-tabpanel">
  <div class="card up-card">
    <div class="card-header"><h3 class="card-title">آخر النسخ الاحتياطية</h3></div>
    <div class="card-body p-0">
      <?php if (empty($backups)): ?>
        <div class="p-3 text-muted">لا توجد نسخ احتياطية حتى الآن.</div>
      <?php else: ?>
      <div class="ua-u-scroll-y-lg">
        <table class="table table-sm up-table ua-u-m0">
          <thead><tr><th>النسخة</th><th>الوقت</th><th>DB</th><th>الإصدار</th></tr></thead>
          <tbody>
            <?php foreach ($backups as $row): ?>
            <tr>
              <td><span class="up-mono"><?= h($row['name']) ?></span><div class="small text-muted"><?= h($row['package_name'] ?: $row['package_version']) ?></div></td>
              <td><?= h($row['time']) ?></td>
              <td><?= $row['db_backup'] ? 'نعم' : 'لا' ?></td>
              <td><?= h($row['from_version'] ?: '—') ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<div id="upTabLogs" class="up-tabpanel">
  <div class="card up-card">
    <div class="card-header"><h3 class="card-title">سجل العمليات</h3></div>
    <div class="card-body p-0">
      <?php if (empty($logRows)): ?>
        <div class="p-3 text-muted">لا يوجد سجل بعد.</div>
      <?php else: ?>
      <div class="ua-u-overflow-auto">
        <table class="table table-sm table-striped up-table ua-u-m0 ua-u-table-wide">
          <thead>
            <tr>
              <th>الوقت</th>
              <th>العملية</th>
              <th>المستخدم</th>
              <th>من</th>
              <th>إلى</th>
              <th>الحزمة</th>
              <th>النسخة الاحتياطية</th>
              <th>تفاصيل</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($logRows as $row): ?>
            <tr>
              <td><?= h((string)($row['time'] ?? '')) ?></td>
              <td><?= h((string)($row['type'] ?? '')) ?></td>
              <td><?= h((string)($row['by'] ?? '')) ?></td>
              <td><?= h((string)($row['from_version'] ?? '')) ?></td>
              <td><?= h((string)($row['to_version'] ?? '')) ?></td>
              <td><?= h((string)($row['package_name'] ?? ($row['package_file'] ?? ''))) ?></td>
              <td><span class="up-mono"><?= h((string)($row['backup'] ?? '')) ?></span></td>
              <td class="small">
                <?php if (!empty($row['error'])): ?><?= h((string)$row['error']) ?><?php else: ?>
                  ملفات: <?= (int)($row['files_count'] ?? 0) ?> / Migrations: <?= (int)($row['migrations_count'] ?? 0) ?>
                <?php endif; ?>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>
</div>

</div>
</section>
</div>
<script>
(function(){
  const toastWrap = document.getElementById('upToastWrap');
  const toastItems = <?= json_encode($toastItems, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>;
  const defaultDuration = 12000;
  function showToast(type, message, duration){
    if(!toastWrap || !message) return;
    const el = document.createElement('div');
    el.className = 'up-toast up-toast-' + type;
    const icon = type === 'success' ? '✓' : (type === 'error' ? '⚠' : 'ℹ');
    el.innerHTML = '<div class="up-toast-icon">'+icon+'</div><div class="up-toast-body"></div><button type="button" class="up-toast-close" aria-label="إغلاق">×</button>';
    el.querySelector('.up-toast-body').textContent = message;
    el.querySelector('.up-toast-close').addEventListener('click', function(){ closeToast(el); });
    toastWrap.appendChild(el);
    requestAnimationFrame(() => el.classList.add('show'));
    const ttl = Math.max(10000, Math.min(15000, duration || defaultDuration));
    el._timer = setTimeout(() => closeToast(el), ttl);
  }
  function closeToast(el){
    if(!el || el.dataset.closing === '1') return;
    el.dataset.closing = '1';
    if(el._timer) clearTimeout(el._timer);
    el.classList.remove('show');
    el.classList.add('hide');
    setTimeout(() => { try { el.remove(); } catch(e){} }, 260);
  }
  if(Array.isArray(toastItems)){
    toastItems.forEach((item, idx) => setTimeout(() => showToast(item.type || 'info', item.message || '', defaultDuration), idx * 220));
  }
  const overlay = document.getElementById('upConfirmOverlay');
  const titleEl = document.getElementById('upConfirmTitle');
  const textEl = document.getElementById('upConfirmText');
  const cancelBtn = document.getElementById('upConfirmCancel');
  const okBtn = document.getElementById('upConfirmOk');
  let pendingForm = null;
  let pendingTrigger = null;
  window.updOpenConfirm = function(form, trigger){
    if(!overlay || !form) return true;
    pendingForm = form;
    pendingTrigger = trigger || null;
    titleEl.textContent = (trigger && trigger.dataset.confirmTitle) ? trigger.dataset.confirmTitle : 'تأكيد العملية';
    textEl.textContent = (trigger && trigger.dataset.confirmText) ? trigger.dataset.confirmText : 'سيتم تنفيذ العملية المطلوبة. هل تريد المتابعة؟';
    overlay.classList.add('show');
    overlay.setAttribute('aria-hidden', 'false');
    return false;
  };
  function closeConfirm(){
    if(!overlay) return;
    overlay.classList.remove('show');
    overlay.setAttribute('aria-hidden', 'true');
  }
  if(cancelBtn) cancelBtn.addEventListener('click', function(){ pendingForm = null; pendingTrigger = null; closeConfirm(); });
  if(okBtn) okBtn.addEventListener('click', function(){
    const form = pendingForm;
    const trigger = pendingTrigger;
    pendingForm = null;
    pendingTrigger = null;
    closeConfirm();
    if(!form) return;
    if(trigger && trigger.name){
      let hidden = form.querySelector('input[data-upd-confirm-submit="1"]');
      if(!hidden){
        hidden = document.createElement('input');
        hidden.type = 'hidden';
        hidden.setAttribute('data-upd-confirm-submit','1');
        form.appendChild(hidden);
      }
      hidden.name = trigger.name;
      hidden.value = trigger.value || '';
    }
    form.submit();
  });
  if(overlay) overlay.addEventListener('click', function(e){ if(e.target === overlay) closeConfirm(); });
  document.addEventListener('keydown', function(e){ if(e.key === 'Escape' && overlay && overlay.classList.contains('show')) closeConfirm(); });

  const tabButtons = Array.from(document.querySelectorAll('.up-tabbtn'));
  const tabPanels = Array.from(document.querySelectorAll('.up-tabpanel'));
  function activateTab(targetId){
    tabButtons.forEach(btn => btn.classList.toggle('active', btn.dataset.target === targetId));
    tabPanels.forEach(panel => panel.classList.toggle('active', panel.id === targetId));
  }
  tabButtons.forEach(btn => btn.addEventListener('click', function(){ activateTab(this.dataset.target); }));
})();
</script>

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