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

// Create connection
$conn = new mysqli($servername, $username, $password);

// 1 & 2 & 3. Check and Create Database
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$conn->query("CREATE DATABASE IF NOT EXISTS `$dbname`");
$conn->select_db($dbname);

// 4 & 5. Create pages table
$sql_pages = "CREATE TABLE IF NOT EXISTS pages (
    id INT(11) NOT NULL AUTO_INCREMENT,
    page_name VARCHAR(50) NOT NULL,
    title VARCHAR(255),
    content TEXT NOT NULL,
    PRIMARY KEY (id)
)";

if ($conn->query($sql_pages) === TRUE) {
    echo "Table 'pages' checked/created successfully.\n";
} else {
    echo "Error creating table 'pages': " . $conn->error . "\n";
}

// 6. Insert sample data if missing
$check = $conn->query("SELECT * FROM pages WHERE page_name='home_intro'");
if ($check->num_rows == 0) {
    $insert = "INSERT INTO pages (page_name, title, content) VALUES ('home_intro', 'Welcome to BALIMEEN', '“Driven by our mission to build responsibly and serve with integrity, Balimeen Private Limited provides efficient, high-quality construction services while creating meaningful employment opportunities that contribute to the growth of communities and society as a whole.”')";
    if ($conn->query($insert) === TRUE) {
        echo "Sample data inserted successfully.\n";
    } else {
        echo "Error inserting data: " . $conn->error . "\n";
    }
} else {
    echo "Sample data already exists.\n";
}

// Ensure other tables like services and admin_users exist if they were missed.
$conn->query("CREATE TABLE IF NOT EXISTS admin_users (id INT(11) NOT NULL AUTO_INCREMENT, username VARCHAR(50) NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY (id))");
$conn->query("CREATE TABLE IF NOT EXISTS services (id INT(11) NOT NULL AUTO_INCREMENT, title VARCHAR(100) NOT NULL, description TEXT NOT NULL, image_url VARCHAR(255) DEFAULT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id))");
$conn->query("CREATE TABLE IF NOT EXISTS blogs (id INT(11) NOT NULL AUTO_INCREMENT, title VARCHAR(255) NOT NULL, content TEXT NOT NULL, image_url VARCHAR(255) DEFAULT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id))");

$conn->close();
?>
