<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Inversion";

// Crear conexión
$conn = new mysqli($servername, $username, $password);

// Verificar conexión
if ($conn->connect_error) {
    die("Conexión fallida: " . $conn->connect_error);
}

// Crear la base de datos
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
if ($conn->query($sql) === TRUE) {
    echo "Base de datos creada correctamente.<br>";
} else {
    echo "Error al crear la base de datos: " . $conn->error . "<br>";
}

// Seleccionar la base de datos
$conn->select_db($dbname);

// Crear las tablas
$queries = [
    "CREATE TABLE IF NOT EXISTS usuario (
        idusu INT AUTO_INCREMENT PRIMARY KEY,
        nomusu VARCHAR(100) NOT NULL,
        usu VARCHAR(50) NOT NULL UNIQUE,
        conusu VARCHAR(255) NOT NULL
    )",
    "CREATE TABLE IF NOT EXISTS inversionista (
        idinv INT AUTO_INCREMENT PRIMARY KEY,
        nominv VARCHAR(150) NOT NULL,
        mailinv VARCHAR(150) UNIQUE,
        dirinv TEXT,
        telinv VARCHAR(20),
        reninv INT NOT NULL
    )",
    "CREATE TABLE IF NOT EXISTS inversion (
        idreginv INT AUTO_INCREMENT PRIMARY KEY,
        idinv INT NOT NULL,
        fecinv DATE NOT NULL,
        mntinv DECIMAL(10,2) NOT NULL,
        reninv INT NOT NULL,
        estado TINYINT(1) NOT NULL DEFAULT 1,  
        FOREIGN KEY (idinv) REFERENCES inversionista(idinv) ON DELETE CASCADE
    )"
];

foreach ($queries as $query) {
    if ($conn->query($query) === TRUE) {
        echo "Tabla creada correctamente.<br>";
    } else {
        echo "Error al crear la tabla: " . $conn->error . "<br>";
    }
}

$conn->close();
?>