<?php
try {
    $pdo = new PDO('mysql:host=127.0.0.1', 'root', 'entesql', [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
    $pdo->exec("CREATE DATABASE IF NOT EXISTS apartment_manager CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
    $pdo->exec("USE apartment_manager");

    $pdo->exec("CREATE TABLE IF NOT EXISTS users (
      role ENUM('admin','user') DEFAULT 'user',
      id INT AUTO_INCREMENT PRIMARY KEY,
      username VARCHAR(100) UNIQUE,
      password VARCHAR(255),
      fullname VARCHAR(200),
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS incomes (
      id INT AUTO_INCREMENT PRIMARY KEY,
      apartment VARCHAR(100),
      amount DECIMAL(12,2),
      category VARCHAR(100),
      note TEXT,
      date DATE,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS expenses (
      id INT AUTO_INCREMENT PRIMARY KEY,
      apartment VARCHAR(100),
      amount DECIMAL(12,2),
      category VARCHAR(100),
      note TEXT,
      date DATE,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB;");

    $exists = $pdo->query("SELECT COUNT(*) FROM users WHERE username='admin'")->fetchColumn();
    if ($exists == 0) {
        $hash = password_hash('admin123', PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("INSERT INTO users (username,password,fullname,role) VALUES ('admin',?, 'Administrator','admin')");
        $stmt->execute([$hash]);
    }
    echo "Install complete. Login with admin / admin123. Please delete or secure install.php.";
} catch (Exception $e) {
    echo 'Error: '.htmlspecialchars($e->getMessage());
}
?>