<?php
require_once __DIR__ . '/inc/helpers.php';
ensure_dirs();
try{
  $pdo=db();
  $pdo->exec("CREATE TABLE IF NOT EXISTS users(
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(60) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    is_admin TINYINT(1) NOT NULL DEFAULT 0,
    avatar_type ENUM('dicebear','upload') NOT NULL DEFAULT 'dicebear',
    avatar_value VARCHAR(255) NOT NULL DEFAULT '',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
  $pdo->exec("CREATE TABLE IF NOT EXISTS clients(
    id INT AUTO_INCREMENT PRIMARY KEY,
    customer_number VARCHAR(16) NOT NULL UNIQUE,
    nombre VARCHAR(120) NOT NULL,
    apellidos VARCHAR(120) NULL,
    direccion VARCHAR(255) NULL,
    nif_cif VARCHAR(20) NULL,
    telefono VARCHAR(30) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
  $pdo->exec("CREATE TABLE IF NOT EXISTS client_files(
    id INT AUTO_INCREMENT PRIMARY KEY,
    client_id INT NOT NULL,
    original_name VARCHAR(255) NOT NULL,
    stored_name VARCHAR(255) NOT NULL UNIQUE,
    uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
  $c=(int)($pdo->query("SELECT COUNT(*) c FROM users")->fetch()['c']??0);
  if($c===0){
    $admin_pwd='Admin#2025!Cambiar';
    $user_pwd='User#2025!Cambiar';
    $ins=$pdo->prepare("INSERT INTO users(username,password_hash,is_admin,avatar_type,avatar_value) VALUES(?,?,?,?,?)");
    $ins->execute(['admin', password_hash_str($admin_pwd), 1, 'dicebear', 'admin']);
    $ins->execute(['usuario', password_hash_str($user_pwd), 0, 'dicebear', 'usuario']);
    echo "<h3>✅ Instalación completada</h3><ul>";
    echo "<li><b>admin</b> / ".h($admin_pwd)."</li>";
    echo "<li><b>usuario</b> / ".h($user_pwd)."</li></ul>";
    echo "<p><a href='login.php'>Ir al login</a></p>"; exit;
  }
  echo "<h3>ℹ️ Ya estaba instalado</h3><p><a href='login.php'>Ir al login</a></p>";
}catch(Throwable $e){ http_response_code(500); echo "<h3>❌ Error</h3><pre>".h($e->getMessage())."</pre>"; }
