<?php
$configPath = __DIR__ . '/../config/config.php';
$defaults = [
    'db_host' => 'localhost',
    'db_name' => '',
    'db_user' => '',
    'db_pass' => '',
    'base_url' => '',
    'app_name' => 'HM HM ERP RRHH v5',
];
if (file_exists($configPath)) {
    @include $configPath;
    if (defined('DB_HOST')) $defaults['db_host'] = DB_HOST;
    if (defined('DB_NAME')) $defaults['db_name'] = DB_NAME;
    if (defined('DB_USER')) $defaults['db_user'] = DB_USER;
    if (defined('DB_PASS')) $defaults['db_pass'] = DB_PASS;
    if (defined('BASE_URL')) $defaults['base_url'] = BASE_URL;
    if (defined('APP_NAME')) $defaults['app_name'] = APP_NAME;
}

$message = null;
$error = null;
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $host = trim($_POST['db_host'] ?? 'localhost');
    $name = trim($_POST['db_name'] ?? '');
    $user = trim($_POST['db_user'] ?? '');
    $pass = $_POST['db_pass'] ?? '';
    $baseUrl = rtrim(trim($_POST['base_url'] ?? ''), '/');
    $appName = trim($_POST['app_name'] ?? 'HM HM ERP RRHH v5');

    try {
        if ($name === '' || $user === '') {
            throw new RuntimeException('Completá al menos DB Name y DB User.');
        }

        $pdo = new PDO(
            "mysql:host={$host};dbname={$name};charset=utf8mb4",
            $user,
            $pass,
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );

        $sql = file_get_contents(__DIR__ . '/../database/install.sql');
        if ($sql === false) {
            throw new RuntimeException('No se pudo leer database/install.sql');
        }
        $pdo->exec($sql);

        $config = "<?php\n"
            . "define('APP_NAME', " . var_export($appName, true) . ");\n"
            . "define('BASE_URL', " . var_export($baseUrl, true) . ");\n"
            . "define('DB_HOST', " . var_export($host, true) . ");\n"
            . "define('DB_NAME', " . var_export($name, true) . ");\n"
            . "define('DB_USER', " . var_export($user, true) . ");\n"
            . "define('DB_PASS', " . var_export($pass, true) . ");\n"
            . "define('TIMEZONE', 'America/Asuncion');\n";

        if (file_put_contents($configPath, $config) === false) {
            throw new RuntimeException('No se pudo escribir config/config.php. Verificá permisos de escritura.');
        }

        $message = 'Instalación ejecutada correctamente. Ya podés entrar al login con admin@local.test / admin123.';
        $defaults = [
            'db_host' => $host,
            'db_name' => $name,
            'db_user' => $user,
            'db_pass' => $pass,
            'base_url' => $baseUrl,
            'app_name' => $appName,
        ];
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

function e($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Instalador HM HM ERP RRHH v5</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body{background:#0f172a;background:linear-gradient(135deg,#0f172a 0%,#111827 100%);min-height:100vh}
    .card{border:0;border-radius:24px;box-shadow:0 20px 50px rgba(0,0,0,.25)}
    .logo{max-width:180px;height:auto}
    .muted{color:#64748b}
  </style>
</head>
<body class="d-flex align-items-center py-5">
<div class="container">
  <div class="row justify-content-center">
    <div class="col-xl-8 col-lg-10">
      <div class="card overflow-hidden">
        <div class="row g-0">
          <div class="col-md-4 text-white p-4 d-flex flex-column justify-content-center" style="background:linear-gradient(180deg,#0b5ed7 0%,#0a3ea9 100%)">
            <img src="../assets/img/logo.png" alt="HM" class="logo mb-4">
            <h3 class="fw-bold">Instalador web</h3>
            <p class="mb-0 opacity-75">Creá la estructura base y el archivo de configuración para publicar rápido en cPanel.</p>
          </div>
          <div class="col-md-8 p-4 p-md-5">
            <h2 class="fw-bold mb-1">HM HM ERP RRHH v5 v3</h2>
            <p class="muted mb-4">Completá los datos de conexión MySQL. La base debe existir previamente en cPanel.</p>

            <?php if ($message): ?>
              <div class="alert alert-success"><?= e($message) ?></div>
            <?php endif; ?>
            <?php if ($error): ?>
              <div class="alert alert-danger"><?= e($error) ?></div>
            <?php endif; ?>

            <form method="post" class="row g-3">
              <div class="col-md-4">
                <label class="form-label">DB Host</label>
                <input name="db_host" class="form-control" value="<?= e($defaults['db_host']) ?>" required>
              </div>
              <div class="col-md-4">
                <label class="form-label">DB Name</label>
                <input name="db_name" class="form-control" value="<?= e($defaults['db_name']) ?>" required>
              </div>
              <div class="col-md-4">
                <label class="form-label">DB User</label>
                <input name="db_user" class="form-control" value="<?= e($defaults['db_user']) ?>" required>
              </div>
              <div class="col-md-6">
                <label class="form-label">DB Pass</label>
                <input name="db_pass" class="form-control" value="<?= e($defaults['db_pass']) ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label">BASE_URL</label>
                <input name="base_url" class="form-control" value="<?= e($defaults['base_url']) ?>" placeholder="https://tu-dominio.com/erp">
              </div>
              <div class="col-12">
                <label class="form-label">Nombre de la app</label>
                <input name="app_name" class="form-control" value="<?= e($defaults['app_name']) ?>">
              </div>
              <div class="col-12 d-flex gap-2 flex-wrap">
                <button class="btn btn-primary" onclick="return confirm('Esto creará o actualizará las tablas base. ¿Continuar?')">Ejecutar instalación</button>
                <a class="btn btn-outline-secondary" href="../login.php">Ir al login</a>
              </div>
            </form>

            <hr class="my-4">
            <div class="small muted">
              Acceso inicial luego de instalar: <strong>admin@local.test</strong> / <strong>admin123</strong>.
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
</html>
