Path : /home/vishqocm/pcib.in/
File Upload :
Current File : /home/vishqocm/pcib.in/install.php

<?php
// Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if already installed
if (file_exists('installed.php')) {
    die('The system is already installed. Please remove installed.php to reinstall.');
}

// Database configuration
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'popularcomputer';

// Function to test database connection
function testConnection($host, $user, $pass) {
    try {
        $conn = new mysqli($host, $user, $pass);
        if ($conn->connect_error) {
            throw new Exception("Connection failed: " . $conn->connect_error);
        }
        return true;
    } catch (Exception $e) {
        return false;
    }
}

// Function to create database and tables
function createDatabase($host, $user, $pass, $db_name) {
    try {
        // Create connection without database
        $conn = new mysqli($host, $user, $pass);
        
        // Create database
        $sql = "CREATE DATABASE IF NOT EXISTS $db_name";
        if (!$conn->query($sql)) {
            throw new Exception("Error creating database: " . $conn->error);
        }
        
        // Select database
        $conn->select_db($db_name);
        
        // Create users table
        $sql = "CREATE TABLE IF NOT EXISTS users (
            id INT(11) NOT NULL AUTO_INCREMENT,
            username VARCHAR(50) NOT NULL UNIQUE,
            email VARCHAR(100) NOT NULL UNIQUE,
            password VARCHAR(255) NOT NULL,
            first_name VARCHAR(50),
            last_name VARCHAR(50),
            role ENUM('admin', 'instructor', 'student') NOT NULL,
            status ENUM('active', 'inactive') NOT NULL DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
        
        if (!$conn->query($sql)) {
            throw new Exception("Error creating users table: " . $conn->error);
        }
        
        // Create courses table
        $sql = "CREATE TABLE IF NOT EXISTS courses (
            id INT(11) NOT NULL AUTO_INCREMENT,
            title VARCHAR(255) NOT NULL,
            description TEXT,
            price DECIMAL(10,2) NOT NULL,
            instructor_id INT(11),
            status ENUM('active', 'inactive') NOT NULL DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            FOREIGN KEY (instructor_id) REFERENCES users(id) ON DELETE SET NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
        
        if (!$conn->query($sql)) {
            throw new Exception("Error creating courses table: " . $conn->error);
        }
        
        // Create enrollments table
        $sql = "CREATE TABLE IF NOT EXISTS enrollments (
            id INT(11) NOT NULL AUTO_INCREMENT,
            user_id INT(11) NOT NULL,
            course_id INT(11) NOT NULL,
            status ENUM('active', 'completed', 'dropped') NOT NULL DEFAULT 'active',
            progress INT(11) NOT NULL DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
        
        if (!$conn->query($sql)) {
            throw new Exception("Error creating enrollments table: " . $conn->error);
        }
        
        // Create submissions table
        $sql = "CREATE TABLE IF NOT EXISTS submissions (
            id INT(11) NOT NULL AUTO_INCREMENT,
            user_id INT(11) NOT NULL,
            course_id INT(11) NOT NULL,
            title VARCHAR(255) NOT NULL,
            content TEXT,
            status ENUM('pending', 'graded') NOT NULL DEFAULT 'pending',
            grade INT(11),
            feedback TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
        
        if (!$conn->query($sql)) {
            throw new Exception("Error creating submissions table: " . $conn->error);
        }
        
        // Create payments table
        $sql = "CREATE TABLE IF NOT EXISTS payments (
            id INT(11) NOT NULL AUTO_INCREMENT,
            user_id INT(11) NOT NULL,
            course_id INT(11) NOT NULL,
            amount DECIMAL(10,2) NOT NULL,
            status ENUM('pending', 'completed', 'failed') NOT NULL DEFAULT 'pending',
            payment_method VARCHAR(50),
            transaction_id VARCHAR(100),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
        
        if (!$conn->query($sql)) {
            throw new Exception("Error creating payments table: " . $conn->error);
        }
        
        // Create slider_images table
        $sql = "CREATE TABLE IF NOT EXISTS slider_images (
            id INT(11) NOT NULL AUTO_INCREMENT,
            title VARCHAR(255) NOT NULL,
            description TEXT,
            image_url VARCHAR(255) NOT NULL,
            link_url VARCHAR(255),
            order_number INT(11) NOT NULL DEFAULT 0,
            status ENUM('active', 'inactive') NOT NULL DEFAULT 'active',
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
        
        if (!$conn->query($sql)) {
            throw new Exception("Error creating slider_images table: " . $conn->error);
        }
        
        return true;
    } catch (Exception $e) {
        return false;
    }
}

// Function to create admin user
function createAdminUser($host, $user, $pass, $db_name, $admin_data) {
    try {
        $conn = new mysqli($host, $user, $pass, $db_name);
        
        // Hash password
        $admin_password = password_hash($admin_data['password'], PASSWORD_DEFAULT);
        
        // Prepare SQL statement
        $sql = "INSERT INTO users (username, email, password, first_name, last_name, role, status)
                VALUES (?, ?, ?, ?, ?, 'admin', 'active')";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssss", 
            $admin_data['username'],
            $admin_data['email'],
            $admin_password,
            $admin_data['first_name'],
            $admin_data['last_name']
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Error creating admin user: " . $stmt->error);
        }
        
        return true;
    } catch (Exception $e) {
        return false;
    }
}

// Function to create required directories
function createDirectories() {
    $directories = [
        'admin',
        'config',
        'includes',
        'uploads',
        'uploads/courses',
        'uploads/slider'
    ];
    
    foreach ($directories as $dir) {
        if (!file_exists($dir)) {
            if (!mkdir($dir, 0755, true)) {
                throw new Exception("Failed to create directory: $dir");
            }
        }
    }
    
    return true;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $errors = [];
    
    // Database configuration
    $db_host = $_POST['db_host'] ?? 'localhost';
    $db_user = $_POST['db_user'] ?? 'root';
    $db_pass = $_POST['db_pass'] ?? '';
    $db_name = $_POST['db_name'] ?? 'lms_db';
    
    // Admin user configuration
    $admin_username = $_POST['admin_username'] ?? '';
    $admin_email = $_POST['admin_email'] ?? '';
    $admin_password = $_POST['admin_password'] ?? '';
    $admin_first_name = $_POST['admin_first_name'] ?? '';
    $admin_last_name = $_POST['admin_last_name'] ?? '';
    
    // Validate database configuration
    if (empty($db_host)) $errors[] = "Database host is required";
    if (empty($db_user)) $errors[] = "Database username is required";
    if (empty($db_name)) $errors[] = "Database name is required";
    
    // Validate admin user configuration
    if (empty($admin_username)) $errors[] = "Admin username is required";
    if (empty($admin_email) || !filter_var($admin_email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Valid admin email is required";
    }
    if (empty($admin_password) || strlen($admin_password) < 6) {
        $errors[] = "Admin password must be at least 6 characters long";
    }
    if (empty($admin_first_name)) $errors[] = "Admin first name is required";
    if (empty($admin_last_name)) $errors[] = "Admin last name is required";
    
    if (empty($errors)) {
        try {
            // Create required directories
            if (!createDirectories()) {
                throw new Exception("Failed to create required directories");
            }
            
            // Test database connection
            if (testConnection($db_host, $db_user, $db_pass)) {
                // Create database and tables
                if (createDatabase($db_host, $db_user, $db_pass, $db_name)) {
                    // Create admin user
                    $admin_data = [
                        'username' => $admin_username,
                        'email' => $admin_email,
                        'password' => $admin_password,
                        'first_name' => $admin_first_name,
                        'last_name' => $admin_last_name
                    ];
                    
                    if (createAdminUser($db_host, $db_user, $db_pass, $db_name, $admin_data)) {
                        // Create database.php file
                        $db_config = "<?php
// Database configuration
\$db_host = '$db_host';
\$db_user = '$db_user';
\$db_pass = '$db_pass';
\$db_name = '$db_name';

// Create connection
try {
    \$conn = new mysqli(\$db_host, \$db_user, \$db_pass, \$db_name);
    
    // Check connection
    if (\$conn->connect_error) {
        throw new Exception(\"Connection failed: \" . \$conn->connect_error);
    }
} catch (Exception \$e) {
    // Log the error
    error_log(\"Database connection error: \" . \$e->getMessage());
    
    // Show user-friendly error message
    die(\"Sorry, there was a problem connecting to the database. Please try again later.\");
}";
                        
                        file_put_contents('config/database.php', $db_config);
                        
                        // Create installed.php file
                        file_put_contents('installed.php', '<?php return true;');
                        
                        // Redirect to login page
                        header('Location: admin/login.php');
                        exit();
                    } else {
                        $errors[] = "Error creating admin user. Please try again.";
                    }
                } else {
                    $errors[] = "Error creating database and tables. Please check your database credentials.";
                }
            } else {
                $errors[] = "Could not connect to the database. Please check your credentials.";
            }
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Install Learning Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: #f8f9fc;
        }
        .install-container {
            max-width: 800px;
            margin: 50px auto;
            padding: 30px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .install-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .install-header h1 {
            color: #4e73df;
            font-size: 24px;
            margin-bottom: 10px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-control {
            border-radius: 5px;
            padding: 10px;
        }
        .btn-install {
            background: #4e73df;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            border: none;
            width: 100%;
            font-weight: 600;
        }
        .btn-install:hover {
            background: #224abe;
        }
        .alert {
            border-radius: 5px;
        }
        .section-title {
            color: #4e73df;
            font-size: 18px;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #4e73df;
        }
        .requirements {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fc;
            border-radius: 5px;
        }
        .requirements h3 {
            color: #4e73df;
            font-size: 18px;
            margin-bottom: 15px;
        }
        .requirements ul {
            margin-bottom: 0;
        }
        .requirements li {
            margin-bottom: 5px;
        }
        .requirements .check {
            color: #28a745;
        }
        .requirements .cross {
            color: #dc3545;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="install-container">
            <div class="install-header">
                <h1>Install Learning Management System</h1>
                <p>Please enter your database credentials and admin account details to begin installation.</p>
            </div>
            
            <div class="requirements">
                <h3>System Requirements</h3>
                <ul>
                    <li>
                        PHP Version (>= 7.4): 
                        <?php echo version_compare(PHP_VERSION, '7.4.0', '>=') ? 
                            '<span class="check">✓</span> ' . PHP_VERSION : 
                            '<span class="cross">✗</span> ' . PHP_VERSION; ?>
                    </li>
                    <li>
                        MySQL/MariaDB: 
                        <?php echo function_exists('mysqli_connect') ? 
                            '<span class="check">✓</span> Available' : 
                            '<span class="cross">✗</span> Not Available'; ?>
                    </li>
                    <li>
                        GD Library: 
                        <?php echo extension_loaded('gd') ? 
                            '<span class="check">✓</span> Available' : 
                            '<span class="cross">✗</span> Not Available'; ?>
                    </li>
                    <li>
                        Config Directory Writable: 
                        <?php echo is_writable('config') || @mkdir('config', 0755) ? 
                            '<span class="check">✓</span> Yes' : 
                            '<span class="cross">✗</span> No'; ?>
                    </li>
                    <li>
                        Uploads Directory Writable: 
                        <?php echo is_writable('uploads') || @mkdir('uploads', 0755) ? 
                            '<span class="check">✓</span> Yes' : 
                            '<span class="cross">✗</span> No'; ?>
                    </li>
                </ul>
            </div>
            
            <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <ul class="mb-0">
                    <?php foreach ($errors as $error): ?>
                    <li><?php echo htmlspecialchars($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <h3 class="section-title">Database Configuration</h3>
                <div class="form-group">
                    <label for="db_host">Database Host</label>
                    <input type="text" class="form-control" id="db_host" name="db_host" value="<?php echo htmlspecialchars($db_host); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="db_user">Database Username</label>
                    <input type="text" class="form-control" id="db_user" name="db_user" value="<?php echo htmlspecialchars($db_user); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="db_pass">Database Password</label>
                    <input type="password" class="form-control" id="db_pass" name="db_pass" value="<?php echo htmlspecialchars($db_pass); ?>">
                </div>
                
                <div class="form-group">
                    <label for="db_name">Database Name</label>
                    <input type="text" class="form-control" id="db_name" name="db_name" value="<?php echo htmlspecialchars($db_name); ?>" required>
                </div>
                
                <h3 class="section-title">Admin Account Setup</h3>
                <div class="form-group">
                    <label for="admin_username">Admin Username</label>
                    <input type="text" class="form-control" id="admin_username" name="admin_username" value="<?php echo htmlspecialchars($admin_username ?? ''); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="admin_email">Admin Email</label>
                    <input type="email" class="form-control" id="admin_email" name="admin_email" value="<?php echo htmlspecialchars($admin_email ?? ''); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="admin_password">Admin Password</label>
                    <input type="password" class="form-control" id="admin_password" name="admin_password" required>
                </div>
                
                <div class="form-group">
                    <label for="admin_first_name">First Name</label>
                    <input type="text" class="form-control" id="admin_first_name" name="admin_first_name" value="<?php echo htmlspecialchars($admin_first_name ?? ''); ?>" required>
                </div>
                
                <div class="form-group">
                    <label for="admin_last_name">Last Name</label>
                    <input type="text" class="form-control" id="admin_last_name" name="admin_last_name" value="<?php echo htmlspecialchars($admin_last_name ?? ''); ?>" required>
                </div>
                
                <button type="submit" class="btn btn-install">Install System</button>
            </form>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>