<?php
// Create admin_users table and admin_login_logs table
// This script creates the necessary tables for admin authentication

require_once '../config.php';

echo "<h2>Admin Authentication Setup</h2>";
echo "<p>Creating admin_users and admin_login_logs tables...</p>";

// Function to check if table exists
function tableExists($conn, $tableName) {
    $result = mysqli_query($conn, "SHOW TABLES LIKE '$tableName'");
    return mysqli_num_rows($result) > 0;
}

// Create admin_users table
if (!tableExists($conn, 'admin_users')) {
    echo "<p>Creating admin_users table...</p>";
    
    $createAdminUsers = "
    CREATE TABLE admin_users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(191) NOT NULL UNIQUE,
        password_hash VARCHAR(255) NOT NULL,
        email VARCHAR(191) NULL,
        full_name VARCHAR(255) NULL,
        role VARCHAR(50) DEFAULT 'admin',
        status ENUM('active', 'inactive', 'suspended') DEFAULT 'active',
        last_login TIMESTAMP NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX idx_username (username),
        INDEX idx_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    if (mysqli_query($conn, $createAdminUsers)) {
        echo "<p style='color: green;'>✓ admin_users table created successfully!</p>";
    } else {
        echo "<p style='color: red;'>✗ Error creating admin_users table: " . mysqli_error($conn) . "</p>";
    }
} else {
    echo "<p style='color: blue;'>ℹ admin_users table already exists.</p>";
}

// Create admin_login_logs table
if (!tableExists($conn, 'admin_login_logs')) {
    echo "<p>Creating admin_login_logs table...</p>";
    
    $createAdminLoginLogs = "
    CREATE TABLE admin_login_logs (
        id INT AUTO_INCREMENT PRIMARY KEY,
        admin_id INT NULL,
        username VARCHAR(191) NOT NULL,
        ip_address VARCHAR(45),
        user_agent TEXT,
        login_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        login_status ENUM('success', 'failed', 'logout', 'password_changed') NOT NULL,
        failure_reason TEXT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX idx_admin_id (admin_id),
        INDEX idx_username (username),
        INDEX idx_login_time (login_time),
        INDEX idx_login_status (login_status),
        FOREIGN KEY (admin_id) REFERENCES admin_users(id) ON DELETE SET NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
    
    if (mysqli_query($conn, $createAdminLoginLogs)) {
        echo "<p style='color: green;'>✓ admin_login_logs table created successfully!</p>";
    } else {
        echo "<p style='color: red;'>✗ Error creating admin_login_logs table: " . mysqli_error($conn) . "</p>";
    }
} else {
    echo "<p style='color: blue;'>ℹ admin_login_logs table already exists.</p>";
}

// Check if we need to create a default admin user
$result = mysqli_query($conn, "SELECT COUNT(*) as count FROM admin_users");
$row = mysqli_fetch_assoc($result);
$adminCount = $row['count'];

if ($adminCount == 0) {
    echo "<p>No admin users found. Creating default admin user...</p>";
    
    // Create default admin user
    $defaultUsername = 'admin';
    $defaultPassword = 'admin123'; // Change this in production!
    $defaultEmail = 'admin@databundleshub.com';
    $defaultFullName = 'System Administrator';
    
    $passwordHash = password_hash($defaultPassword, PASSWORD_DEFAULT);
    
    $insertAdmin = "INSERT INTO admin_users (username, password_hash, email, full_name, role, status) VALUES (?, ?, ?, ?, 'admin', 'active')";
    $stmt = mysqli_prepare($conn, $insertAdmin);
    
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "ssss", $defaultUsername, $passwordHash, $defaultEmail, $defaultFullName);
        
        if (mysqli_stmt_execute($stmt)) {
            echo "<p style='color: green;'>✓ Default admin user created successfully!</p>";
            echo "<p><strong>Default Login Credentials:</strong></p>";
            echo "<ul>";
            echo "<li>Username: <code>$defaultUsername</code></li>";
            echo "<li>Password: <code>$defaultPassword</code></li>";
            echo "</ul>";
            echo "<p style='color: orange;'><strong>⚠️ IMPORTANT:</strong> Please change the default password immediately after first login!</p>";
        } else {
            echo "<p style='color: red;'>✗ Error creating default admin user: " . mysqli_stmt_error($stmt) . "</p>";
        }
        mysqli_stmt_close($stmt);
    } else {
        echo "<p style='color: red;'>✗ Error preparing statement: " . mysqli_error($conn) . "</p>";
    }
} else {
    echo "<p style='color: blue;'>ℹ Found $adminCount admin user(s) in the database.</p>";
}

echo "<hr>";
echo "<p><strong>Setup Complete!</strong></p>";
echo "<p>You can now:</p>";
echo "<ul>";
echo "<li>Login to the admin panel using the credentials above</li>";
echo "<li>Change the default password from the admin dashboard</li>";
echo "<li>Create additional admin users if needed</li>";
echo "</ul>";

echo "<p><a href='admin_login.php' style='background: #3B82F6; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px;'>Go to Admin Login</a></p>";
?>
