<?php
$page_title = 'Install Setup';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidInstallSetup = ((string)($_GET['ua_android'] ?? '') === '1') || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidInstallSetup) $UA_PAGE_CSS = ['assets/css/android_install_setup.css'];

require_once __DIR__ . '/header.php';
require_once __DIR__ . '/sidebar.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';

require_login();

$msg = '';
$err = '';
$configFile = UA_INSTALL_CONFIG_FILE;
$config = ua_install_config();

function ua_setup_int($value, int $default, int $min, int $max): int {
  $n = (int)$value;
  if ($n < $min) return $default;
  if ($n > $max) return $default;
  return $n;
}

function ua_write_install_config(array $config, string &$error = ''): bool {
  $file = UA_INSTALL_CONFIG_FILE;
  $dir = dirname($file);
  if (!is_dir($dir) || !is_writable($dir)) {
    $error = 'Install config directory is not writable.';
    return false;
  }

  $php = "<?php\n";
  $php .= "// Runtime install configuration.\n";
  $php .= "// Generated by admin/install_setup.php at " . date('Y-m-d H:i:s') . "\n\n";
  $php .= "return " . var_export($config, true) . ";\n";

  $tmp = $file . '.tmp';
  if (@file_put_contents($tmp, $php, LOCK_EX) === false) {
    $error = 'Could not write temporary install config.';
    return false;
  }
  if (!@rename($tmp, $file)) {
    @unlink($tmp);
    $error = 'Could not replace install config.';
    return false;
  }
  return true;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $installType = strtolower(trim((string)($_POST['install_type'] ?? 'server')));
  if (!in_array($installType, ua_valid_install_types(), true)) {
    $installType = 'server';
  }

  $serverUrl = trim((string)($_POST['server_url'] ?? ''));
  if ($serverUrl === '') $serverUrl = 'http://127.0.0.1:8080/';

  $db = [
    'host' => trim((string)($_POST['db_host'] ?? '127.0.0.1')),
    'port' => ua_setup_int($_POST['db_port'] ?? 3306, 3306, 1, 65535),
    'name' => trim((string)($_POST['db_name'] ?? 'isp_db')),
    'user' => trim((string)($_POST['db_user'] ?? 'root')),
    'pass' => (string)($_POST['db_pass'] ?? ''),
    'charset' => trim((string)($_POST['db_charset'] ?? 'utf8mb4')),
  ];
  if ($db['host'] === '') $db['host'] = '127.0.0.1';
  if ($db['name'] === '') $db['name'] = 'isp_db';
  if ($db['user'] === '') $db['user'] = 'root';
  if ($db['charset'] === '') $db['charset'] = 'utf8mb4';

  $newConfig = [
    'install_type' => $installType,
    'server_url' => $serverUrl,
    'database' => $db,
  ];

  if (function_exists('ua_save_install_config') ? ua_save_install_config($newConfig, $err) : ua_write_install_config($newConfig, $err)) {
    $config = $newConfig;
    $msg = $installType === 'agent'
      ? 'تم حفظ نسخة المعتمد. ستكون بوابة المعتمد هي الواجهة الرئيسية بعد تسجيل الدخول.'
      : 'تم حفظ إعدادات النسخة.';
  }
}

$db = $config['database'] ?? [];
if (!is_array($db)) $db = [];
$currentInstallType = (string)($config['install_type'] ?? 'server');
if ($uaAndroidInstallSetup) { require __DIR__ . '/android_install_setup.php'; require_once __DIR__ . '/footer.php'; return; }
?>
<div class="content-wrapper ua-extracted-page ua-u-text-right" dir="rtl">
  <section class="content">
    <div class="container-fluid">
      <div class="card mb-3">
        <div class="card-body">
          <h1 class="mb-2">إعداد نوع النسخة</h1>
          <div class="text-muted">هذه الصفحة تضبط ملف التشغيل الذي سيستخدمه الـ Installer والـ Launcher لاحقاً.</div>
        </div>
      </div>

      <?php if ($msg !== ''): ?>
        <div class="alert alert-success"><?= h($msg) ?></div>
      <?php endif; ?>
      <?php if ($err !== ''): ?>
        <div class="alert alert-danger"><?= h($err) ?></div>
      <?php endif; ?>

      <form method="post" class="card">
        <div class="card-body">
          <div class="row">
            <div class="col-md-4 mb-3">
              <label class="form-label">نوع النسخة</label>
              <select class="form-control" name="install_type">
                <?php foreach (ua_valid_install_types() as $type): ?>
                  <option value="<?= h($type) ?>" <?= $currentInstallType === $type ? 'selected' : '' ?>><?= h($type) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-8 mb-3">
              <label class="form-label">رابط نسخة السيرفر</label>
              <input class="form-control" name="server_url" value="<?= h((string)($config['server_url'] ?? '')) ?>" placeholder="http://SERVER-IP:PORT/">
            </div>
          </div>

          <hr>

          <div class="row">
            <div class="col-md-4 mb-3">
              <label class="form-label">Database Host</label>
              <input class="form-control" name="db_host" value="<?= h((string)($db['host'] ?? '127.0.0.1')) ?>">
            </div>
            <div class="col-md-2 mb-3">
              <label class="form-label">Port</label>
              <input class="form-control" name="db_port" type="number" min="1" max="65535" value="<?= h((string)($db['port'] ?? 3306)) ?>">
            </div>
            <div class="col-md-3 mb-3">
              <label class="form-label">Database Name</label>
              <input class="form-control" name="db_name" value="<?= h((string)($db['name'] ?? 'isp_db')) ?>">
            </div>
            <div class="col-md-3 mb-3">
              <label class="form-label">Charset</label>
              <input class="form-control" name="db_charset" value="<?= h((string)($db['charset'] ?? 'utf8mb4')) ?>">
            </div>
          </div>

          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Database User</label>
              <input class="form-control" name="db_user" value="<?= h((string)($db['user'] ?? 'root')) ?>">
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Database Password</label>
              <input class="form-control" name="db_pass" type="password" value="<?= h((string)($db['pass'] ?? '')) ?>">
            </div>
          </div>

          <div class="d-flex gap-2">
            <button class="btn btn-primary" type="submit">حفظ الإعدادات</button>
            <a class="btn btn-outline-secondary" href="app_settings.php">رجوع</a>
          </div>
        </div>
      </form>

      <div class="card mt-3">
        <div class="card-body">
          <div><b>ملف الإعداد:</b> <?= h($configFile) ?></div>
          <div><b>الوضع الحالي:</b> <?= h($currentInstallType) ?></div>
          <div><b>الواجهة الرئيسية:</b> <?= h($currentInstallType === 'agent' ? 'بوابة المعتمد' : 'لوحة التحكم') ?></div>
        </div>
      </div>
    </div>
  </section>
</div>
<?php require_once __DIR__ . '/footer.php'; ?>
