<?php
require_once __DIR__ . '/../app/lib/util.php';

session_start();

$cfgPath = __DIR__ . '/../app/config.php';
if (file_exists($cfgPath)) {
  echo "Ya está instalado. Borra app/config.php si quieres reinstalar."; exit;
}

$error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $db_host = trim($_POST['db_host'] ?? 'localhost');
  $db_name = trim($_POST['db_name'] ?? '');
  $db_user = trim($_POST['db_user'] ?? '');
  $db_pass = (string)($_POST['db_pass'] ?? '');
  $admin_user = trim($_POST['admin_user'] ?? 'admin');
  $admin_pass = (string)($_POST['admin_pass'] ?? '');

  if ($db_name==='' || $db_user==='' || $admin_pass==='') {
    $error = "Completa DB name, DB user y clave del admin.";
  } else {
    try {
      $dsn = 'mysql:host=' . $db_host . ';dbname=' . $db_name . ';charset=utf8mb4';
      $pdo = new PDO($dsn, $db_user, $db_pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      ]);

      // write config
      $cfg = "<?php\nreturn " . var_export([
        'db_host'=>$db_host,'db_name'=>$db_name,'db_user'=>$db_user,'db_pass'=>$db_pass
      ], true) . ";\n";
      file_put_contents($cfgPath, $cfg);

      // run schema
      $schema = file_get_contents(__DIR__ . '/../app/schema.sql');
      $pdo->exec($schema);

      // seed admin + default session
      $hash = password_hash($admin_pass, PASSWORD_DEFAULT);
      $stmt = $pdo->prepare("INSERT INTO users(username,password_hash,role,active) VALUES(?,?, 'admin', 1)");
      $stmt->execute([$admin_user, $hash]);
      $adminId = (int)$pdo->lastInsertId();

      $stmt = $pdo->prepare("INSERT INTO inventory_sessions(name, created_by, status) VALUES(?, ?, 'abierta')");
      $stmt->execute(['Inventario 2025', $adminId]);
      $sessionId = (int)$pdo->lastInsertId();

      // Import data from bundled files (optional but requested)
      // 1) Physical CSV: data/inventario_todo.csv columns: Vitrina, Codigo, Fecha
      $csv = __DIR__ . '/../data/inventario_todo.csv';
      if (file_exists($csv)) {
        $handle = fopen($csv, 'r');
        $header = fgetcsv($handle);
        $ins = $pdo->prepare("INSERT INTO physical_items(session_id, code, vitrina, counted_at) VALUES(?, ?, ?, ?)");
        $rowCount = 0;
        while (($row = fgetcsv($handle)) !== false) {
          // Map by header name (robust)
          $map = array_combine($header, $row);
          $code = trim((string)($map['Codigo'] ?? ''));
          if ($code === '') continue;
          $vitrina = trim((string)($map['Vitrina'] ?? ''));
          $fecha = trim((string)($map['Fecha'] ?? ''));
          $dt = null;
          if ($fecha !== '') {
            // Try parse as datetime string
            $ts = strtotime($fecha);
            if ($ts !== false) $dt = gmdate('Y-m-d H:i:s', $ts);
          }
          $ins->execute([$sessionId, $code, $vitrina, $dt]);
          $rowCount++;
          if ($rowCount % 5000 === 0) { /* keep going */ }
        }
        fclose($handle);
      }

      // 2) System inventory from Excel: data/Conteo Inventario Time Store.xlsx sheet "Iventario"
      // Requires PhpSpreadsheet; bundled via composer is not included. We'll do a lightweight approach:
      // If you have PhpSpreadsheet installed, enable import in settings.php. Otherwise you can import CSV export of inventory.
      // To keep installation simple, we won't auto-import the Excel here.

      header('Location: login.php?installed=1'); exit;

    } catch (Exception $e) {
      $error = "Error: " . $e->getMessage();
      if (file_exists($cfgPath)) @unlink($cfgPath);
    }
  }
}
?>
<!doctype html>
<html lang="es"><head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Instalar Inventarios</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container py-4">
  <h3>Instalación - Inventarios (PHP 7)</h3>
  <?php if ($error): ?><div class="alert alert-danger"><?= htmlspecialchars($error,ENT_QUOTES,'UTF-8') ?></div><?php endif; ?>
  <form method="post" class="card p-3">
    <h5>Base de datos</h5>
    <div class="form-row">
      <div class="form-group col-md-4">
        <label>DB Host</label><input class="form-control" name="db_host" value="<?= htmlspecialchars($_POST['db_host']??'localhost') ?>">
      </div>
      <div class="form-group col-md-4">
        <label>DB Name</label><input class="form-control" name="db_name" value="<?= htmlspecialchars($_POST['db_name']??'') ?>" required>
      </div>
      <div class="form-group col-md-4">
        <label>DB User</label><input class="form-control" name="db_user" value="<?= htmlspecialchars($_POST['db_user']??'') ?>" required>
      </div>
    </div>
    <div class="form-group">
      <label>DB Pass</label><input type="password" class="form-control" name="db_pass" value="<?= htmlspecialchars($_POST['db_pass']??'') ?>">
    </div>
    <hr>
    <h5>Usuario Administrador</h5>
    <div class="form-row">
      <div class="form-group col-md-6">
        <label>Usuario</label><input class="form-control" name="admin_user" value="<?= htmlspecialchars($_POST['admin_user']??'admin') ?>">
      </div>
      <div class="form-group col-md-6">
        <label>Clave</label><input type="password" class="form-control" name="admin_pass" required>
      </div>
    </div>
    <button class="btn btn-primary">Instalar</button>
  </form>
  <p class="mt-3 text-muted">Nota: Este instalador carga automáticamente tu conteo físico desde data/inventario_todo.csv.</p>
</div>
</body></html>
